diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_path_diagnostics.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_path_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..219336bcde27c897b81d6c253255dca79eb11d1c --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_path_diagnostics.py @@ -0,0 +1,727 @@ +"""Read-only answer-source diagnostics for the frozen two-chain experiments. + +Matching an answer to a candidate is a behavioral description, not evidence that +the model used that internal path. Multiple matching roles are never tie-broken. +""" + +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, write_json + +LEARNING_ROLES = ("default", "actual", "other_default", "other_actual") +EDIT_ROLES = ( + "new_default", + "new_actual", + "old_default", + "old_actual", + "other_default", + "other_actual", +) +# Codes are shared across files. Role names differ between learning and editing. +NOT_APPLICABLE, TERMINATION_ERROR, OTHER, INDISTINGUISHABLE = -1, 0, 1, 2 +ROLE_CODE_START = 3 + + +def file_sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def classify_answers(prediction, ended, candidates): + """Return exclusive categories plus *all* matched role bits, including overlaps. + + An unfinished generation is a termination error even if its value matches. + Correctness is deliberately separate: a correct answer can have ambiguous roles. + """ + prediction, ended, candidates = map(np.asarray, (prediction, ended, candidates)) + if ( + candidates.ndim != 2 + or prediction.shape != ended.shape + or candidates.shape[0] != len(prediction) + ): + raise ValueError("Incompatible prediction/candidate shapes") + if not 1 <= candidates.shape[1] <= 8: + raise ValueError("Candidate role bitset requires one to eight roles") + matched = prediction[:, None] == candidates + n_matches = matched.sum(axis=1) + bits = (matched.astype(np.uint8) * (1 << np.arange(candidates.shape[1]))).sum(axis=1) + category = np.full(len(prediction), OTHER, dtype=np.int8) + unique = n_matches == 1 + category[unique] = ROLE_CODE_START + matched[unique].argmax(axis=1) + category[n_matches > 1] = INDISTINGUISHABLE + category[~ended.astype(bool)] = TERMINATION_ERROR + return category, bits.astype(np.uint8) + + +def candidate_answers(world, chain, target=None): + """Candidate values for all people, with no dependence on model predictions.""" + other = 1 - chain + old_default = world.answers[world.root_ids[chain, world.memberships[chain]]] + old_actual = world.answers[world.actual_ids[chain]] + current = world.answers if target is None else target + other_default = current[world.root_ids[other, world.memberships[other]]] + other_actual = current[world.actual_ids[other]] + if target is None: + roles = LEARNING_ROLES + values = (old_default, old_actual, other_default, other_actual) + else: + roles = EDIT_ROLES + values = ( + target[world.root_ids[chain, world.memberships[chain]]], + target[world.actual_ids[chain]], + old_default, + old_actual, + other_default, + other_actual, + ) + return roles, np.column_stack(values) + + +def score_saved_arrays(arrays, answers): + prediction, ended = arrays["prediction"], arrays["ended"] + if prediction.shape != answers.shape or ended.shape != answers.shape: + raise ValueError("Saved prediction length differs from truth") + if not np.isin(ended, [False, True]).all(): + raise ValueError("Invalid termination flags") + correct = (prediction == answers) & ended.astype(bool) + if not np.array_equal(correct, arrays["correct"]): + raise ValueError("Saved correctness differs from value-plus-EOS scoring") + return correct + + +def annotate_predictions(world, arrays, target=None): + """Full-query arrays plus candidate matrices aligned with derived_query_ids.""" + answers = world.answers if target is None else target + correct = score_saved_arrays(arrays, answers) + category = np.full(len(answers), NOT_APPLICABLE, dtype=np.int8) + bits = np.zeros(len(answers), dtype=np.uint8) + candidates = [] + for chain in range(2): + roles, values = candidate_answers(world, chain, target) + ids = world.derived_ids[chain] + category[ids], bits[ids] = classify_answers( + arrays["prediction"][ids], arrays["ended"][ids], values + ) + candidates.append(values) + return { + "query_id": np.arange(len(answers), dtype=np.int32), + "prediction": np.asarray(arrays["prediction"], dtype=np.int32), + "ended": np.asarray(arrays["ended"], dtype=bool), + "correct": correct, + "class_code": category, + "matched_role_bits": bits, + "derived_query_ids": world.derived_ids.astype(np.int32), + "candidate_tokens": np.stack(candidates).astype(np.int32), + "candidate_roles": np.array(roles), + } + + +def learning_subsets(world): + """Overlapping diagnostic groups; every row retains its own denominator.""" + yield "all_queries", np.arange(len(world.answers)) + yield "base", np.arange(world.n_base) + yield "independent_attributes", np.flatnonzero(np.isin(world.relation, [3, 4, 5, 6])) + for chain, name in enumerate(CHAINS): + for relation, ids in ( + ("membership", world.membership_ids[chain]), + ("default", world.root_ids[chain]), + ("actual", world.actual_ids[chain]), + ): + yield f"{name}/base/{relation}", ids + for split, ids in ( + ("all", world.derived_ids[chain]), + ("trained", world.train_ids[chain]), + ("heldout", world.heldout_ids[chain]), + ): + yield f"{name}/qa/{split}/all", ids + for label, mask in ( + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + yield ( + f"{name}/qa/{split}/{label}", + np.intersect1d(ids, world.derived_ids[chain, mask]), + ) + + +def editing_subsets(world, pair, chain, target): + yield "E/all", pair["E"] + yield "E/default", np.intersect1d(pair["E"], world.root_ids[chain]) + yield "E/actual", np.intersect1d(pair["E"], world.actual_ids[chain]) + # Membership in the 45-person manipulated cohort differs from factual conflict: + # six old exceptions can also conflict; coherent edits have no *new* conflicts. + actual_conflict = target[world.derived_ids[chain]] != target[world.actual_ids[chain]] + for split, ids in ( + ("all", pair["D"]), + ("trained", np.intersect1d(pair["D"], world.train_ids[chain])), + ("heldout", np.intersect1d(pair["D"], world.heldout_ids[chain])), + ): + yield f"D/{split}/all", ids + for label, group in ( + ("manipulated_conflict_cohort", pair["conflict_D"]), + ("factual_conflict", world.derived_ids[chain, actual_conflict]), + ("no_factual_conflict", world.derived_ids[chain, ~actual_conflict]), + ("old_exception", world.derived_ids[chain, world.exceptions[chain]]), + ("ordinary", world.derived_ids[chain, ~world.exceptions[chain]]), + ): + yield f"D/{split}/{label}", np.intersect1d(ids, group) + for pool_name, pool in ( + ("full", np.flatnonzero(pair["strata"] >= 0)), + ("editor_heldout", pair["heldout"]), + ): + yield f"U/{pool_name}/all", pool + for stratum in range(4): + yield ( + f"U/{pool_name}/stratum_{stratum}", + np.intersect1d(pool, np.flatnonzero(pair["strata"] == stratum)), + ) + + +def summary_rows(world, annotations, subsets, identity, old_correct=None): + """Counts are sufficient to reaggregate without hiding empty or ambiguous cells.""" + classes, bits = annotations["class_code"], annotations["matched_role_bits"] + for label, ids in subsets: + ids = np.asarray(ids) + correct = annotations["correct"][ids] + row = { + **identity, + "subset": label, + "n": len(ids), + "correct": int(correct.sum()), + "accuracy": float(correct.mean()) if len(ids) else None, + "termination_error": int((~annotations["ended"][ids]).sum()), + "role_not_applicable": int((classes[ids] == NOT_APPLICABLE).sum()), + "other_answer": int((classes[ids] == OTHER).sum()), + "indistinguishable": int((classes[ids] == INDISTINGUISHABLE).sum()), + "indistinguishable_wrong": int(((classes[ids] == INDISTINGUISHABLE) & ~correct).sum()), + } + # Stable CSV schema, even though learning uses only four roles. + for role in dict.fromkeys((*LEARNING_ROLES, *EDIT_ROLES)): + role_names = list(annotations["candidate_roles"]) + if role in role_names: + index = role_names.index(role) + row[f"unique_{role}"] = int((classes[ids] == ROLE_CODE_START + index).sum()) + row[f"matches_{role}"] = int( + (((bits[ids] & (1 << index)) != 0) & annotations["ended"][ids]).sum() + ) + else: + row[f"unique_{role}"] = row[f"matches_{role}"] = 0 + if old_correct is not None: + known = old_correct[ids] + row["old_known"] = int(known.sum()) + row["old_known_coverage"] = float(known.mean()) if len(ids) else None + row["old_known_now_wrong"] = int((known & ~correct).sum()) + row["damage_rate"] = ( + (float((known & ~correct).sum() / known.sum()) if known.any() else None) + if label.startswith("U/") + else None + ) + else: + row.update( + old_known=None, old_known_coverage=None, old_known_now_wrong=None, damage_rate=None + ) + yield row + + +def _write_csv(path, rows): + with Path(path).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def _safe_output(output, source_roots): + output = Path(output).resolve() + if any(output == root or root in output.parents for root in source_roots): + raise ValueError("Diagnostics must not be written into source experiment directories") + output.mkdir(parents=True, exist_ok=True) + return output + + +def analyze_saved(repository, output, manifest_path="configs/bios-cross-scale-development-v1.json"): + """Re-score the complete matrix using CPU arrays; never invoke old summary writers.""" + repository = Path(repository).resolve() + manifest_path = repository / manifest_path + manifest = json.loads(manifest_path.read_text()) + source_roots = [(repository / size["output"]).resolve() for size in manifest["sizes"]] + output = _safe_output(output, source_roots) + ledger = {} + + def record(path): + path = Path(path).resolve() + key = str(path.relative_to(repository)) if repository in path.parents else str(path) + digest = file_sha256(path) + if key in ledger and ledger[key] != digest: + raise ValueError(f"Source changed during analysis: {path}") + ledger[key] = digest + + record(manifest_path) + worlds, pairs = {}, {} + learning_rows, editing_rows, error_rows = [], [], [] + counts = { + "models": 0, + "learning_checkpoints": 0, + "edit_cases": 0, + "edit_checkpoints": 0, + "scored_query_predictions": 0, + "classified_derived_predictions": 0, + } + for size, root in zip(manifest["sizes"], source_roots, strict=True): + contract_path = root / "launch-contract.json" + record(contract_path) + contract = json.loads(contract_path.read_text()) + study = contract["study"] + expected_runs = { + (w, seed, condition) + for w in study["worlds"] + for seed in study["seeds"] + for condition in CONDITIONS + } + seen_runs = set() + for config_path in sorted(root.glob("world-*/config.json")): + record(config_path) + config = json.loads(config_path.read_text()) + if config["sources"] != contract["sources"] or config["study"] != study: + raise ValueError(f"Run contract mismatch: {config_path}") + for name, digest in config["sources"].items(): + path = repository / "src/llm_memory_editability" / name + if file_sha256(path) != digest: + raise ValueError(f"Frozen source changed: {name}") + record(path) + run = config_path.parent + key = (config["world"], config["seed"], config["condition"]) + if key in seen_runs: + raise ValueError("Duplicate model") + seen_runs.add(key) + if not (run / "complete.json").exists(): + raise ValueError(f"Incomplete run: {run}") + record(run / "complete.json") + world_seed = config["world"] + if world_seed not in worlds: + worlds[world_seed] = make_cross_world( + world_seed, repository / "data/bios-organization-v1" + ) + world = worlds[world_seed] + if config["truth_sha256"] != array_hash(world.answers) or config[ + "prompts_sha256" + ] != array_hash(world.prompts): + raise ValueError("Generated data mismatch") + common = { + "width": size["width"], + "parameters": config["parameters"], + "world": world_seed, + "seed": config["seed"], + "condition": config["condition"], + } + out_run = output / "queries" / f"width-{size['width']}" / run.name + out_run.mkdir(parents=True, exist_ok=True) + baseline = None + for step in study["checkpoints"]: + prediction_path = run / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {name: loaded[name] for name in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays) + np.savez_compressed(out_run / f"learning-{step}.npz", **annotated) + identity = { + **common, + "phase": "learning", + "chain": "", + "kind": "", + "scope": "", + "step": step, + } + learning_rows.extend( + summary_rows(world, annotated, learning_subsets(world), identity) + ) + counts["learning_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + if step == study["steps"]: + baseline = arrays["correct"] + if baseline is None: + raise ValueError("Missing learning endpoint") + for chain, name in enumerate(CHAINS): + pair_key = (world_seed, chain) + if pair_key not in pairs: + pairs[pair_key] = edit_pair(world, chain) + pair = pairs[pair_key] + for kind in ("coherent", "exception"): + target = pair[kind] + for scope in ("mlp", "all"): + case = f"{name}-{kind}-{scope}" + dest = run / "edits" / case + record(dest / "complete.json") + record(dest / "sets.npz") + with np.load(dest / "sets.npz", allow_pickle=False) as loaded: + for field, expected in pair.items(): + if not np.array_equal(loaded[field], expected): + raise ValueError(f"Edit set mismatch: {dest}/{field}") + if not np.array_equal(loaded["old_correct"], baseline): + raise ValueError(f"Edit baseline mismatch: {dest}") + for step in study["edit_checkpoints"]: + prediction_path = dest / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {k: loaded[k] for k in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays, target) + np.savez_compressed(out_run / f"{case}-{step}.npz", **annotated) + identity = { + **common, + "phase": "editing", + "chain": name, + "kind": kind, + "scope": scope, + "step": step, + } + editing_rows.extend( + summary_rows( + world, + annotated, + editing_subsets(world, pair, chain, target), + identity, + baseline, + ) + ) + # Readable per-D query ledger, with every ambiguity explicitly retained. + roles, values = candidate_answers(world, chain, target) + for query in pair["D"]: + person = world.person[query] + matches = [ + role + for i, role in enumerate(roles) + if annotated["matched_role_bits"][query] & (1 << i) + ] + code = int(annotated["class_code"][query]) + category = { + TERMINATION_ERROR: "termination_error", + OTHER: "other", + INDISTINGUISHABLE: "indistinguishable", + } + error_rows.append( + { + **identity, + "query": int(query), + "person": int(person), + "heldout": bool(query in world.heldout_ids[chain]), + "old_exception": bool(world.exceptions[chain, person]), + "manipulated_conflict_cohort": bool( + query in pair["conflict_D"] + ), + "factual_conflict": bool( + values[person, 0] != values[person, 1] + ), + "prediction": int(arrays["prediction"][query]), + "ended": bool(arrays["ended"][query]), + "correct": bool(arrays["correct"][query]), + "class": category.get( + code, + roles[code - ROLE_CODE_START] + if code >= ROLE_CODE_START + else "", + ), + "matched_roles": "|".join(matches), + **{ + role: int(values[person, i]) + for i, role in enumerate(roles) + }, + } + ) + counts["edit_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + counts["edit_cases"] += 1 + counts["models"] += 1 + print(json.dumps({"event": "p0_model_scored", **common, **counts}), flush=True) + if seen_runs != expected_runs: + raise ValueError(f"Incomplete or unexpected model grid: width {size['width']}") + if ( + counts["models"] != manifest["learning_runs"] + or counts["edit_cases"] != manifest["edit_cases"] + ): + raise ValueError("Incomplete matrix") + _write_csv(output / "learning-strata.csv", learning_rows) + _write_csv(output / "editing-strata.csv", editing_rows) + _write_csv(output / "propagation-queries.csv", error_rows) + # Verify that reading/analysis did not mutate any source and that no parallel + # process changed this historical input batch while it was being analyzed. + for name, digest in ledger.items(): + if file_sha256(repository / name) != digest: + raise ValueError(f"Source changed during analysis: {name}") + write_json(output / "sources.json", ledger) + write_json( + output / "schema.json", + { + "class_codes": { + "not_applicable_to_base_query": -1, + "termination_error": 0, + "other": 1, + "indistinguishable": 2, + "unique_role_start": 3, + }, + "learning_roles": LEARNING_ROLES, + "editing_roles": EDIT_ROLES, + "matched_role_bits": "bit i indicates value matches role i; EOS checked separately", + "candidate_tokens_shape": "chain, person, role; " + "maps to derived_query_ids[chain, person]", + "interpretation": "Candidate answer agreement is not causal evidence for a path. " + "Overlapping roles are never assigned a preferred interpretation.", + "subset_rows_overlap": True, + "manipulated_conflict_cohort": "Original 45 people, also tagged in coherent controls; " + "factual_conflict is measured from actual target answers.", + }, + ) + code_hashes = { + str(path.relative_to(repository)): file_sha256(path) + for path in (Path(__file__).resolve(), repository / "scripts/analyze_bios_paths.py") + } + audit = { + "complete": True, + **counts, + "source_files": len(ledger), + "sources_sha256": file_sha256(output / "sources.json"), + "analysis_sources": code_hashes, + "errors": [], + "source_data_modified": False, + "source_hashes_rechecked_after_analysis": True, + } + write_json(output / "audit.json", audit) + _report(output, audit, learning_rows, editing_rows) + return audit + + +def _report(output, audit, learning_rows, editing_rows): + lines = [ + "# P0:已有预测的行为诊断", + "", + f"完成{audit['models']}个模型、{audit['edit_cases']}个编辑;" + f"重计分{audit['learning_checkpoints']}个学习和{audit['edit_checkpoints']}个编辑检查点。", + "", + "候选答案相同的角色记为不可区分;答案重合不能证明内部路径。" + "终止失败独立于答案值记录。下表为案例等权均值,非独立查询推断。", + "", + "| 宽度 | 编辑 | 案例 | 冲突留出D | 新实际城市匹配 | 不可区分 | 终止失败 |", + "|---:|---|---:|---:|---:|---:|---:|", + ] + grouped = defaultdict(list) + for row in editing_rows: + if ( + row["kind"] == "exception" + and row["step"] == 512 + and row["subset"] == "D/heldout/manipulated_conflict_cohort" + ): + grouped[row["width"], row["scope"]].append(row) + for (width, scope), rows in sorted(grouped.items()): + rates = [ + np.mean([r[key] / r["n"] for r in rows]) + for key in ("correct", "matches_new_actual", "indistinguishable", "termination_error") + ] + lines.append( + f"| {width} | {scope} | {len(rows)} | " + + " | ".join(f"{100 * rate:.2f}%" for rate in rates) + + " |" + ) + lines += [ + "", + "新实际城市匹配是允许与旧实际/另一条链答案重合的描述性比例;" + "唯一匹配和全部角色位图均另存,不能据此宣称捷径已证实。", + "", + "学习分层见 learning-strata.csv;编辑分层见 editing-strata.csv;" + "每条传播查询见 propagation-queries.csv;全部逐查询数组见 queries/。", + "自主两步前向诊断尚须单独执行并记录模型权重来源。", + "", + ] + (output / "report.md").write_text("\n".join(lines)) + + +def free_generate_values(model, prompts, lengths, device, batch_size=512): + """Exactly the frozen value-plus-EOS generation convention, without targets.""" + import torch + + from .bios_train import precision + + predictions, ended = [], [] + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[begin : begin + batch_size], device=device) + n = torch.as_tensor(lengths[begin : begin + batch_size], device=device) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)} + + +def autonomous_two_step(model, world, chain, device, batch_size=512, answers=None): + """Generate bridge identity, then query that predicted identity, never the true one. + + Truth is accessed only for scoring after both model calls. A wrong but valid + bridge may coincidentally lead to a correct city; keep that outcome and the + first-hop correctness separately. Invalid/unterminated bridges fail outright. + """ + membership_ids = world.membership_ids[chain] + first = free_generate_values( + model, world.prompts[membership_ids], world.lengths[membership_ids], device, batch_size + ) + allowed_subjects = world.prompts[world.root_ids[chain], 1] + valid = first["ended"] & np.isin(first["prediction"], allowed_subjects) + second_prediction = np.full(len(membership_ids), -1, dtype=np.int64) + second_ended = np.zeros(len(membership_ids), dtype=bool) + if valid.any(): + # Root queries have the same grammar and relation token. Do not choose a + # template using true membership; replace the subject using generated data. + root_template = world.prompts[world.root_ids[chain, 0]] + prompts = np.broadcast_to(root_template, (int(valid.sum()), 5)).copy() + prompts[:, 1] = first["prediction"][valid] + lengths = np.full(len(prompts), world.lengths[world.root_ids[chain, 0]], dtype=np.int64) + second = free_generate_values(model, prompts, lengths, device, batch_size) + second_prediction[valid], second_ended[valid] = second["prediction"], second["ended"] + target = world.answers if answers is None else answers + return { + "query_id": world.derived_ids[chain], + "bridge_prediction": first["prediction"], + "bridge_ended": first["ended"], + "bridge_valid": valid, + "bridge_correct": (first["prediction"] == target[membership_ids]) & first["ended"], + "prediction": second_prediction, + "ended": second_ended, + "correct": valid & second_ended & (second_prediction == target[world.derived_ids[chain]]), + } + + +def diagnose_two_step_run( + run, output, device="cuda", learning_steps=(15360,), include_edits=False, batch_size=512 +): + """Independent, resumable forward-only jobs; no optimizer or training mutations.""" + import torch + + from .bios_model import CausalLM, ModelConfig + + run, output = Path(run).resolve(), Path(output).resolve() + repository = Path(__file__).resolve().parents[2] + output = _safe_output(output, [run]) + config = json.loads((run / "config.json").read_text()) + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if array_hash(world.answers) != config["truth_sha256"]: + raise ValueError("Two-step world differs from trained world") + device = torch.device(device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + jobs = [ + ( + f"learning-{step}", + run / f"model-{step}.pt", + world.answers, + run / f"predictions-{step}.npz", + ) + for step in learning_steps + ] + if include_edits: + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + for kind in ("coherent", "exception"): + for scope in ("mlp", "all"): + dest = run / "edits" / f"{name}-{kind}-{scope}" + jobs.append( + ( + dest.name, + dest / "model-final.pt", + pair[kind], + dest / f"predictions-{config['study']['edit_steps']}.npz", + ) + ) + for label, checkpoint, answers, direct_path in jobs: + dest = output / label + dest.mkdir(parents=True, exist_ok=True) + identity = { + "run": str(run), + "checkpoint": str(checkpoint), + "checkpoint_sha256": file_sha256(checkpoint), + "direct_predictions_sha256": file_sha256(direct_path), + "config_sha256": file_sha256(run / "config.json"), + "diagnostic_source_sha256": file_sha256(__file__), + "answer_sha256": array_hash(answers), + "batch_size": batch_size, + "device_type": device.type, + "torch": torch.__version__, + "precision": "BF16 autocast; FP32 weights" if device.type == "cuda" else "FP32", + } + complete_path = dest / "complete.json" + if complete_path.exists(): + saved = json.loads(complete_path.read_text()) + if saved["identity"] != identity: + raise ValueError(f"Changed diagnostic identity: {dest}") + continue + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + with np.load(direct_path) as data: + direct = {k: data[k] for k in ("prediction", "ended", "correct")} + score_saved_arrays(direct, answers) + rows = [] + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device, batch_size, answers) + ids = world.derived_ids[chain] + arrays.update({f"direct_{k}": v[ids] for k, v in direct.items()}) + np.savez_compressed(dest / f"{name}.npz", **arrays) + for split, mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("trained", np.isin(ids, world.train_ids[chain])), + ("heldout", np.isin(ids, world.heldout_ids[chain])), + ): + for population, population_mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + selected = mask & population_mask + n = int(selected.sum()) + rows.append( + { + "chain": name, + "split": split, + "population": population, + "n": n, + **{ + key: int(arrays[key][selected].sum()) + for key in ( + "correct", + "direct_correct", + "bridge_valid", + "bridge_correct", + ) + }, + } + ) + _write_csv(dest / "summary.csv", rows) + write_json( + complete_path, + { + "identity": identity, + "complete": True, + "queries": int(world.derived_ids.size), + "oracle_bridging": False, + }, + ) + del model, saved + if device.type == "cuda": + torch.cuda.empty_cache() + print( + json.dumps({"event": "two_step_complete", "run": str(run), "case": label}), flush=True + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_path_minimal.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_path_minimal.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2ed53451de1a88abe78ee5e58cb49745597c2b --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_path_minimal.py @@ -0,0 +1,379 @@ +"""Two-layer follow-up: common-error removal versus competing new answers.""" + +import argparse +import fcntl +import itertools +import json +import os +import subprocess +import sys +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig +from .bios_path_transfer import ROOT, inner, norm, path_mode, sha, stamp, tensor_sha + +CONFIG = ROOT / "configs/bios-path-minimal-v1.json" + + +def toy_data(config, device): + people = config["people"] + person = torch.arange(people, device=device).repeat_interleave(3) + relation = torch.arange(3, device=device).repeat(people) + value_start = 3 + people + 3 + tokens = torch.stack( + (torch.ones_like(person), 3 + person, 3 + people + relation, torch.full_like(person, 2)), -1 + ) + labels = value_start + (person + (relation == 2)) % 3 + return tokens, labels, value_start + + +def probe_data(config, person, kind, device): + tokens, old, values = toy_data(config, device) + ids = torch.arange(person * 3, person * 3 + 3, device=device) + a, b, c = values + (person + 1) % 3, values + (person + 2) % 3, values + person % 3 + labels = old[ids].clone() + labels[0], labels[1] = a if kind == "coherent" else b, a + return tokens[ids], labels, (a, b, c) + + +def gradients(model, tokens, labels, arm): + projection = model.blocks[0].mlp.down + captured = {} + + def hook(module, inputs, output): + captured["z"], captured["h"] = inputs[0], output + + handle = projection.register_forward_hook(hook) + try: + with path_mode(model, 0, arm): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits.double(), labels, reduction="none") + actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) + z, delta = captured["z"].detach(), delta.detach() + g = torch.einsum("btd,btk->btdk", delta, z).sum(1) + if norm(g.sum(0) - actual) / max(norm(actual), 1e-30) > 5e-5: + raise ValueError("Minimal-model gradient reconstruction failed") + return {"logits": logits.detach(), "loss": loss.detach(), "g": g, "z": z, "delta": delta} + finally: + handle.remove() + + +@torch.no_grad() +def evaluate(model, tokens, labels, values): + logits = model(tokens)[:, -1].double() + p = logits.softmax(-1) + a, b, c = values + return { + "loss": F.cross_entropy(logits, labels, reduction="none").cpu().tolist(), + "prediction": logits.argmax(-1).cpu().tolist(), + "probabilities_abc": p[:, [a, b, c]].cpu().tolist(), + "source_target_probability": p[0, labels[0]].item(), + "derived_margin_ab": (logits[1, a] - logits[1, b]).item(), + "isotropic_same_probability_reference": (p[1].square().sum() - p[1, a] - p[1, b]).item(), + } + + +def freeze(config): + directory = ROOT / config["artifacts"] + directory.mkdir(parents=True, exist_ok=True) + path = directory / "preregistration-lock.json" + if path.exists(): + raise FileExistsError("Cannot replace minimal-model prospective lock") + section = ( + "### 18.7 " + (ROOT / "docs/experimental-protocol.md").read_text().split("### 18.7 ", 1)[1] + ) + (directory / "preregistration.md").write_text(section) + files = [ + CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_path_minimal.py", + ROOT / "scripts/analyze_bios_path_margin.py", + ROOT / "tests/test_bios_path_minimal.py", + ROOT / "src/llm_memory_editability/bios_path_transfer.py", + ROOT / "src/llm_memory_editability/bios_model.py", + ROOT / "docs/development-artifacts/path-transfer-v1/audit.json", + ] + sources = {} + for file in files: + relative = file.relative_to(ROOT) + sources[str(relative)] = sha(file) + destination = directory / "frozen-files" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(file.read_bytes()) + write_json( + path, + { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(directory / "preregistration.md"), + "torch": torch.__version__, + }, + ) + return {"lock": str(path), "sha256": sha(path)} + + +def verify(config): + directory = ROOT / config["artifacts"] + path = directory / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Minimal config/runtime changed") + for name, digest in lock["sources"].items(): + if sha(ROOT / name) != digest: + raise ValueError("Minimal frozen source changed: " + name) + if sha(directory / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Minimal protocol changed") + return sha(path) + + +def learn(config, seed, device, out): + torch.manual_seed(seed) + tokens, labels, values = toy_data(config, device) + model = CausalLM(ModelConfig(values + 3, config["width"], 2, config["heads"], context=8)).to( + device + ) + if (out / "parent.pt").exists(): + saved = torch.load(out / "parent.pt", map_location=device, weights_only=False) + model.load_state_dict(saved["model"]) + return model + optimizer = torch.optim.AdamW( + model.parameters(), lr=config["train_lr"], weight_decay=config["train_weight_decay"] + ) + trajectory = [] + for step in range(config["train_steps"] + 1): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits, labels) + if step in (0, 128, 512, config["train_steps"]): + trajectory.append( + { + "step": step, + "loss": loss.item(), + "accuracy": logits.argmax(-1).eq(labels).float().mean().item(), + } + ) + if step == config["train_steps"]: + break + optimizer.zero_grad(set_to_none=True) + loss.backward() + optimizer.step() + torch.save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": config["train_steps"], + }, + out / "parent.pt", + ) + write_json(out / "learning.json", trajectory) + return model + + +def trajectory(model, parent, config, person, kind, arm, device, directory): + model.load_state_dict(parent) + model.eval() + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name == config["target_parameter"]) + tokens, labels, values = probe_data(config, person, kind, device) + w = model.blocks[0].mlp.down.weight + timeline, steps, factors = [], [], [] + for step in range(config["edit_steps"] + 1): + measure = step % config["measure_every"] == 0 or step == config["edit_steps"] + full = gradients( + model, tokens if measure else tokens[:1], labels if measure else labels[:1], "full" + ) + source = full if arm == "full" else gradients(model, tokens[:1], labels[:1], arm) + if not torch.equal(full["logits"][:1], source["logits"][:1]): + # Different batch sizes allow only normal FP32 GEMM rounding. + if (full["logits"][:1] - source["logits"][:1]).abs().max().item() > 3e-5: + raise ValueError("Minimal forward mismatch") + raw, original = source["g"][0], full["g"][0] + direction = raw * (norm(original) / norm(raw)) if norm(raw) else raw + if measure: + row = { + "step": step, + **evaluate(model, tokens, labels, values), + "source_gradient_norm": norm(original), + "intervened_gradient_norm": norm(raw), + "kernel_source": inner(full["g"][0], direction), + "kernel_derived": inner(full["g"][1], direction), + "kernel_retention": inner(full["g"][2], direction), + "kernel_derived_full": inner(full["g"][1], original), + } + timeline.append(row) + factors.append( + { + key: value.detach().cpu().numpy() + for key, value in { + "z": full["z"], + "delta": full["delta"], + "source_z": source["z"][:1], + "source_delta": source["delta"][:1], + }.items() + } + ) + if step == config["edit_steps"]: + break + before_weight = w.detach().clone() if measure else None + with torch.no_grad(): + w.add_(direction, alpha=-config["edit_lr"]) + if measure: + after = evaluate(model, tokens, labels, values) + actual_delta = w.detach() - before_weight + row["one_step_observed_derived"] = after["loss"][1] - row["loss"][1] + row["one_step_predicted_derived"] = inner(full["g"][1], actual_delta) + row["one_step_margin_change"] = after["derived_margin_ab"] - row["derived_margin_ab"] + steps.append( + { + "step": step, + "source_loss": full["loss"][0].item(), + "direction_norm": norm(direction), + "source_gradient_norm": norm(original), + } + ) + for name, value in model.state_dict().items(): + if name != config["target_parameter"] and not torch.equal(value, parent[name]): + raise ValueError("Minimal frozen parameter changed") + directory.mkdir(parents=True, exist_ok=True) + write_json( + directory / "trajectory.json", + { + "person": person, + "kind": kind, + "arm": arm, + "values_abc": values, + "labels": labels.cpu().tolist(), + "timeline": timeline, + "steps": steps, + }, + ) + np.savez_compressed( + directory / "factors.npz", + **{key: np.stack([factor[key] for factor in factors]) for key in factors[0]}, + ) + torch.save(w.detach().cpu(), directory / "edited-weight.pt") + write_json( + directory / "complete.json", + { + "finished_at": stamp(), + "steps": len(steps), + "weight_sha256": tensor_sha(w), + "frozen_parameters_unchanged": True, + "files": { + name: sha(directory / name) + for name in ("trajectory.json", "factors.npz", "edited-weight.pt") + }, + }, + ) + + +def run(config, seed, device): + lock_hash = verify(config) + if seed not in config["seeds"]: + raise ValueError("Unknown seed") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + out = ROOT / config["output"] / f"seed-{seed}" + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + write_json( + out / "runtime.json", + { + "started_at": stamp(), + "lock_sha256": lock_hash, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + ) + model = learn(config, seed, device, out) + parent = {k: v.detach().clone() for k, v in model.state_dict().items()} + for person, kind, arm in itertools.product( + config["people_to_edit"], config["kinds"], config["arms"] + ): + directory = out / f"person-{person}-{kind}-{arm}" + if not (directory / "complete.json").exists(): + trajectory(model, parent, config, person, kind, arm, device, directory) + print( + json.dumps( + { + "event": "trajectory", + "seed": seed, + "person": person, + "kind": kind, + "arm": arm, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "finished_at": stamp(), + "lock_sha256": lock_hash, + "files": { + str(path.relative_to(out)): sha(path) + for path in out.rglob("*") + if path.is_file() and path != out / "complete.json" and path.name != ".lock" + }, + }, + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("freeze", "worker", "dispatch")) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--gpus", nargs="+", type=int, default=[5, 8]) + args = parser.parse_args() + config = json.loads(CONFIG.read_text()) + if args.command == "freeze": + print(json.dumps(freeze(config))) + elif args.command == "worker": + run(config, args.seed, torch.device(args.device)) + else: + verify(config) + output = ROOT / config["output"] + output.mkdir(parents=True, exist_ok=True) + workers = [] + for index, seed in enumerate(config["seeds"]): + log = (output / f"seed-{seed}.log").open("a") + env = { + **os.environ, + "CUDA_VISIBLE_DEVICES": str(args.gpus[index % len(args.gpus)]), + "PYTHONPATH": str(ROOT / "src"), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + proc = subprocess.Popen( + [ + sys.executable, + str(ROOT / "scripts/run_bios_path_minimal.py"), + "worker", + "--seed", + str(seed), + ], + env=env, + cwd=ROOT, + stdout=log, + stderr=subprocess.STDOUT, + ) + workers.append((proc, log)) + codes = [] + for proc, log in workers: + codes.append(proc.wait()) + log.close() + write_json(output / "dispatch.json", {"finished_at": stamp(), "returncodes": codes}) + if any(codes): + raise RuntimeError("Minimal worker failed; see retained logs") + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_path_transfer.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_path_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..0c54e9cfda468b9a153577dd716a037dde1577f1 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_path_transfer.py @@ -0,0 +1,653 @@ +"""Prospective v2.13: forward-preserving path interventions and local transfer. + +Only a single MLP output weight is differentiated/updated in production. +Downstream parameters are frozen; the custom attention paths alter its input VJP. +""" + +import argparse +import fcntl +import hashlib +import itertools +import json +import os +import platform +import subprocess +import sys +import time +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path +from types import MethodType + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import edit_pair, make_cross_world +from .bios_cross_train import tensor_queries +from .bios_data import EOS, array_hash, write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = ROOT / "configs/bios-path-transfer-v1.json" +ARMS = ("full", "no_cross", "no_mlp", "fixed_qk") + + +def stamp(): + return datetime.now(timezone.utc).isoformat() + + +def sha(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def tensor_sha(value): + return hashlib.sha256(value.detach().cpu().contiguous().numpy().tobytes()).hexdigest() + + +def inner(a, b): + return (a.double() * b.double()).sum().item() + + +def norm(a): + return a.double().norm().item() + + +def relative(a, b): + return norm(a - b) / max(norm(b), 1e-30) + + +def cosine(a, b): + return inner(a, b) / max(norm(a) * norm(b), 1e-30) + + +def attention_surrogate(module, x, mode): + """Correct input Jacobian for frozen QK, or only the diagonal position blocks. + + no_cross makes T copies of the input: copy s only differentiates x_s, + then computes output s with the full original causal context. Thus Q_s, + K_s and V_s derivatives survive; all x_t -> output_s, t != s vanish. + """ + batch, length, width = x.shape + heads, dim = module.heads, width // module.heads + if mode == "no_cross": + expanded = x[:, None].expand(batch, length, length, width) + diagonal = torch.eye(length, device=x.device, dtype=x.dtype)[None, :, :, None] + routed = expanded.detach() + diagonal * (expanded - expanded.detach()) + q, k, v = module.qkv(routed).reshape(batch, length, length, 3, heads, dim).unbind(3) + index = torch.arange(length, device=x.device) + q = q[:, index, index] # B, query, H, D + scores = torch.einsum("bshd,bsthd->bhst", q, k) / dim**0.5 + mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() + a = scores.masked_fill(~mask, -torch.inf).softmax(-1) + output = torch.einsum("bhst,bsthd->bshd", a, v).reshape(batch, length, width) + else: + q, k, v = module.qkv(x).reshape(batch, length, 3, heads, dim).unbind(2) + scores = torch.einsum("bshd,bthd->bhst", q, k) / dim**0.5 + mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() + a = scores.masked_fill(~mask, -torch.inf).softmax(-1) + if mode == "fixed_qk": + a = a.detach() + elif mode != "manual_full": + raise ValueError(mode) + output = torch.einsum("bhst,bthd->bshd", a, v).reshape(batch, length, width) + return module.proj(output) + + +@contextmanager +def path_mode(model, layer, arm): + if arm not in (*ARMS, "manual_full"): + raise ValueError(arm) + saved = [] + try: + for block in model.blocks[layer + 1 :]: + if arm == "no_mlp": + module = block.mlp + original = module.forward + + def stopped(self, x, original=original): + with torch.no_grad(): + return original(x) + + module.forward = MethodType(stopped, module) + saved.append((module, original)) + elif arm != "full": + module = block.attention + original = module.forward + + def altered(self, x, original=original, arm=arm): + with torch.no_grad(): + reference = original(x) + surrogate = attention_surrogate(self, x, arm) + return reference + (surrogate - surrogate.detach()) + + module.forward = MethodType(altered, module) + saved.append((module, original)) + yield + finally: + for module, original in saved: + module.forward = original + + +def cases(world): + result = [] + for chain in range(2): + pair = edit_pair(world, chain) + for group in pair["groups"]: + members = np.flatnonzero(world.memberships[chain] == group) + eligible = members[ + np.isin(world.derived_ids[chain, members], world.heldout_ids) + & np.isin(world.derived_ids[chain, members], pair["conflict_D"]) + ] + if not len(eligible): + raise ValueError("No prespecified heldout conflict person") + person = int(eligible[0]) + others = members[ + (members != person) + & ~world.exceptions[chain, members] + & np.isin(world.derived_ids[chain, members], world.heldout_ids) + ] + if not len(others): + raise ValueError("No prespecified second heldout person") + other = int(others[0]) + distant = int(np.flatnonzero(~np.isin(world.memberships[chain], pair["groups"]))[0]) + root = int(world.root_ids[chain, group]) + actual = int(world.actual_ids[chain, person]) + default = int(pair["coherent"][root]) + alternative = int(pair["exception"][actual]) + if default == alternative: + raise ValueError("Selected person is not a new conflict") + for kind in ("root", "coherent", "conflict"): + source = root if kind == "root" else actual + target = alternative if kind == "conflict" else default + associated = actual if kind == "root" else root + ids = [ + source, + int(world.derived_ids[chain, person]), + int(world.derived_ids[chain, other]), + associated, + int(world.actual_ids[1 - chain, person]), + int(world.actual_ids[chain, distant]), + ] + targets = [target, default, default, default, *world.answers[ids[-2:]].tolist()] + result.append( + { + "name": f"chain-{chain}-group-{int(group)}-{kind}", + "chain": chain, + "group": int(group), + "kind": kind, + "person": person, + "other_person": other, + "ids": ids, + "targets": targets, + "old_targets": world.answers[ids].tolist(), + "roles": [ + "source", + "derived_same", + "derived_other", + "associated", + "retention_local", + "retention_distant", + ], + } + ) + return result + + +def example_data(world, case, device): + # Use the original interface, including teacher-forced answer for EOS loss. + targets = world.answers.copy() + targets[case["ids"]] = case["targets"] + all_data = tensor_queries(world, device, targets) + ids = torch.tensor(case["ids"], device=device) + return {key: value[ids] for key, value in all_data.items()} + + +def subset(data, ids): + return {key: value[ids] for key, value in data.items()} + + +def losses(logits, labels): + return ( + F.cross_entropy( + logits.double().reshape(-1, logits.shape[-1]), labels.reshape(-1), reduction="none" + ) + .reshape(-1, 2) + .mean(-1) + ) + + +def measure(model, data, layer, arm): + projection = model.blocks[layer].mlp.down + captured = {} + + def hook(module, inputs, output): + captured["z"], captured["h"] = inputs[0], output + + handle = projection.register_forward_hook(hook) + try: + with path_mode(model, layer, arm): + logits = model(data["tokens"], data["positions"]) + loss = losses(logits, data["labels"]) + actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) + z = captured["z"].detach() + delta = delta.detach() + per_position = torch.einsum("btd,btk->btdk", delta, z) + mask = torch.zeros(z.shape[:2], device=z.device, dtype=torch.bool) + mask.scatter_(1, data["positions"], True) + g = per_position.sum(1) + supervised = (per_position * mask[:, :, None, None]).sum(1) + unsupervised = (per_position * ~mask[:, :, None, None]).sum(1) + return { + "z": z, + "delta": delta, + "g": g, + "supervised": supervised, + "unsupervised": unsupervised, + "mask": mask, + "loss": loss.detach(), + "logits": logits.detach(), + "reconstruction_error": relative(g.sum(0), actual), + "decomposition_error": relative(supervised + unsupervised, g), + } + finally: + handle.remove() + + +@torch.no_grad() +def assess(model, data): + logits = model(data["tokens"], data["positions"]) + loss = losses(logits, data["labels"]) + first = model(data["prompts"], (data["lengths"] - 1)[:, None])[:, 0].argmax(-1) + continuation = data["tokens"].clone() + rows = torch.arange(len(first), device=first.device) + continuation[rows, data["lengths"]] = first + ended = model(continuation, data["lengths"][:, None])[:, 0].argmax(-1).eq(EOS) + return loss, first, ended + + +def frozen_files(config): + paths = [ + CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_path_transfer.py", + ROOT / "tests/test_bios_path_transfer.py", + ] + for name in ("bios_model.py", "bios_cross.py", "bios_cross_train.py", "bios_data.py"): + paths.append(ROOT / "src/llm_memory_editability" / name) + for world in config["worlds"]: + directory = ROOT / config["source_world_root"] / f"world-{world}" + paths += [ + directory / "world.npz", + directory / "metadata.json", + directory / "evaluation.npz", + ] + for world, seed in itertools.product(config["worlds"], config["seeds"]): + directory = ROOT / config["parent_root"] / f"world-{world}-seed-{seed}-neither" + paths += [directory / "config.json", directory / "learning-complete.json"] + paths += [directory / f"model-{step}.pt" for step in config["states"]] + return paths + + +def freeze(config): + directory = ROOT / config["artifacts"] + directory.mkdir(parents=True, exist_ok=True) + lock_path = directory / "preregistration-lock.json" + if lock_path.exists(): + raise FileExistsError("Cannot replace a prospective lock") + protocol = ( + "## 18. " + (ROOT / "docs/experimental-protocol.md").read_text().split("## 18. ", 1)[1] + ) + (directory / "preregistration.md").write_text(protocol) + manifests = {} + for world in config["worlds"]: + generated = make_cross_world(world, ROOT / config["source_world_root"]) + selected = cases(generated) + if len(selected) != config["cases_per_state"]: + raise ValueError("Case count mismatch") + manifests[str(world)] = { + "truth_sha256": array_hash(generated.answers), + "prompts_sha256": array_hash(generated.prompts), + "cases": selected, + } + write_json(directory / "cases.json", manifests) + sources = {} + for path in frozen_files(config): + relative_path = path.relative_to(ROOT) + sources[str(relative_path)] = sha(path) + if relative_path.parts[0] in ("src", "scripts", "tests", "configs"): + destination = directory / "frozen-files" / relative_path + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(path.read_bytes()) + lock = { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(directory / "preregistration.md"), + "cases_sha256": sha(directory / "cases.json"), + "torch": torch.__version__, + "numpy": np.__version__, + "python": platform.python_version(), + } + write_json(lock_path, lock) + return {"path": str(lock_path), "sha256": sha(lock_path)} + + +def verify_lock(config): + directory = ROOT / config["artifacts"] + path = directory / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Frozen config/runtime mismatch") + for name, digest in lock["sources"].items(): + if sha(ROOT / name) != digest: + raise ValueError("Frozen input changed: " + name) + for name, key in (("preregistration.md", "protocol_sha256"), ("cases.json", "cases_sha256")): + if sha(directory / name) != lock[key]: + raise ValueError("Prospective manifest changed") + return sha(path) + + +def save_factors(path, baseline, sources, data): + arrays = { + "positions": data["positions"].cpu().numpy(), + "labels": data["labels"].cpu().numpy(), + "tokens": data["tokens"].cpu().numpy(), + } + for prefix, result in [("evaluation", baseline), *sources.items()]: + for key in ("z", "delta", "loss"): + arrays[prefix + "_" + key] = result[key].cpu().numpy() + np.savez_compressed(path, **arrays) + + +def run_case(model, world, case, config, destination): + layer = config["target_layer"] + w = model.blocks[layer].mlp.down.weight + parent = w.detach().clone() + frozen_before = { + name: tensor_sha(value) + for name, value in model.state_dict().items() + if name != config["target_parameter"] + } + data = example_data(world, case, w.device) + baseline = measure(model, data, layer, "full") + before, old_prediction, old_ended = assess(model, data) + sources, diagnostics, updates = {}, [], [] + with torch.no_grad(): + if not torch.equal(before, baseline["loss"]): + raise ValueError("Evaluation/gradient forward mismatch") + for arm in config["arms"]: + source = measure(model, subset(data, slice(0, 1)), layer, arm) + sources[arm] = source + error = (source["logits"] - sources["full"]["logits"]).abs().max().item() + if error > config["forward_tolerance"]: + raise ValueError(f"Forward preservation failed: {error}") + if ( + max(source["reconstruction_error"], baseline["reconstruction_error"]) + > config["gradient_tolerance"] + ): + raise ValueError("Outer-product reconstruction failed") + direction = source["g"][0] + gfull = sources["full"]["g"][0] + if arm == "no_cross" and norm(source["unsupervised"]) > 1e-9: + raise ValueError("Cross-position cut did not eliminate unsupervised-position gradient") + for j, role in enumerate(case["roles"]): + row = { + "arm": arm, + "role": role, + "probe": j, + "forward_error": error, + "reconstruction_error": source["reconstruction_error"], + "gradient_norm": norm(direction), + "gradient_cosine_full": cosine(direction, gfull), + "supervised_norm": norm(source["supervised"]), + "unsupervised_norm": norm(source["unsupervised"]), + "kernel": inner(baseline["g"][j], direction), + "source_loss": source["loss"].item(), + "probe_loss": before[j].item(), + } + for left, right in itertools.product(("supervised", "unsupervised"), repeat=2): + row[f"kernel_{left}_{right}"] = inner(baseline[left][j], source[right][0]) + diagnostics.append(row) + for scale, fraction in itertools.product(config["scales"], config["step_fractions"]): + denominator = norm(gfull if scale == "shared_lr" else direction) + eta = fraction * norm(parent) / denominator if denominator else 0.0 + with torch.no_grad(): + w.copy_(parent - eta * direction) + displacement = w.detach() - parent + weight_hash = tensor_sha(w) + after, predicted_token, ended = assess(model, data) + predicted = (baseline["g"].double() * displacement.double()).sum((-1, -2)) + for j, role in enumerate(case["roles"]): + updates.append( + { + "arm": arm, + "scale": scale, + "fraction": fraction, + "eta": eta, + "update_norm": norm(displacement), + "weight_sha256": weight_hash, + "role": role, + "probe": j, + "id": case["ids"][j], + "target": case["targets"][j], + "old_target": case["old_targets"][j], + "before": before[j].item(), + "after": after[j].item(), + "observed_change": (after[j] - before[j]).item(), + "predicted_change": predicted[j].item(), + "ideal_predicted_change": -eta * inner(baseline["g"][j], direction), + "baseline_prediction": int(old_prediction[j]), + "baseline_ended": bool(old_ended[j]), + "prediction": int(predicted_token[j]), + "ended": bool(ended[j]), + } + ) + with torch.no_grad(): + w.copy_(parent) + if not torch.equal(w, parent): + raise ValueError("Parent weight was not restored") + frozen_after = { + name: tensor_sha(value) + for name, value in model.state_dict().items() + if name != config["target_parameter"] + } + if frozen_before != frozen_after: + raise ValueError("A frozen parameter changed") + destination.mkdir(parents=True, exist_ok=True) + save_factors(destination / "factors.npz", baseline, sources, data) + write_json( + destination / "measurements.json", + {"case": case, "diagnostics": diagnostics, "updates": updates}, + ) + write_json( + destination / "receipt.json", + { + "finished_at": stamp(), + "files": { + name: sha(destination / name) for name in ("factors.npz", "measurements.json") + }, + "baseline_reconstruction_error": baseline["reconstruction_error"], + "frozen_parameters_unchanged": True, + "parent_restored": True, + }, + ) + + +def verify_receipt(directory): + receipt = json.loads((directory / "receipt.json").read_text()) + for name, digest in receipt["files"].items(): + if sha(directory / name) != digest: + raise ValueError("Receipt mismatch: " + str(directory / name)) + + +def run(config, world_id, seed, device): + lock_hash = verify_lock(config) + if world_id not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("Worker outside the frozen matrix") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + world = make_cross_world(world_id, ROOT / config["source_world_root"]) + name = f"world-{world_id}-seed-{seed}-neither" + source = ROOT / config["parent_root"] / name + out = ROOT / config["output"] / name + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as stream: + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + started = time.monotonic() + write_json( + out / "runtime.json", + { + "started_at": stamp(), + "lock_sha256": lock_hash, + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if "cuda" in str(device) else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "torch": torch.__version__, + }, + ) + for step in config["states"]: + checkpoint = torch.load( + source / f"model-{step}.pt", map_location="cpu", weights_only=False + ) + if checkpoint["step"] != step: + raise ValueError("Parent step mismatch") + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + model.eval() + for pname, parameter in model.named_parameters(): + parameter.requires_grad_(pname == config["target_parameter"]) + selected = cases(world) + state_out = out / f"step-{step}" + state_out.mkdir(exist_ok=True) + # Original-forward repeated gradient, not a new scientific sample. + sham_data = subset(example_data(world, selected[0], device), slice(0, 1)) + first = measure(model, sham_data, config["target_layer"], "full") + second = measure(model, sham_data, config["target_layer"], "full") + sham_error = relative(first["g"], second["g"]) + if sham_error > config["gradient_tolerance"]: + raise ValueError("Sham gradient failed") + write_json(state_out / "sham.json", {"relative_gradient_error": sham_error}) + for case in selected: + destination = state_out / case["name"] + if (destination / "receipt.json").exists(): + verify_receipt(destination) + else: + run_case(model, world, case, config, destination) + print( + json.dumps( + { + "event": "case", + "world": world_id, + "seed": seed, + "step": step, + "case": case["name"], + } + ), + flush=True, + ) + del model, checkpoint + files = { + str(path.relative_to(out)): sha(path) + for path in out.rglob("*") + if path.is_file() and path.name not in (".lock", "complete.json") + } + write_json( + out / "complete.json", + { + "finished_at": stamp(), + "seconds": time.monotonic() - started, + "lock_sha256": lock_hash, + "cases": len(config["states"]) * len(selected), + "files": files, + }, + ) + + +def dispatch(config, gpus): + verify_lock(config) + output = ROOT / config["output"] + output.mkdir(parents=True, exist_ok=True) + jobs = list(itertools.product(config["worlds"], config["seeds"])) + active, finished = [], [] + with (output / ".dispatch.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + while jobs or active: + for gpu in gpus: + if jobs and not any(item["gpu"] == gpu for item in active): + world, seed = jobs.pop(0) + path = output / f"world-{world}-seed-{seed}-neither" + if (path / "complete.json").exists(): + finished.append({"world": world, "seed": seed, "reused": True}) + continue + log = (output / f"world-{world}-seed-{seed}.log").open("a") + env = { + **os.environ, + "CUDA_VISIBLE_DEVICES": str(gpu), + "PYTHONPATH": str(ROOT / "src"), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + command = [ + sys.executable, + str(ROOT / "scripts/run_bios_path_transfer.py"), + "worker", + "--world", + str(world), + "--seed", + str(seed), + "--device", + "cuda:0", + ] + proc = subprocess.Popen( + command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT + ) + active.append( + {"gpu": gpu, "world": world, "seed": seed, "process": proc, "log": log} + ) + for item in active[:]: + code = item["process"].poll() + if code is not None: + item["log"].close() + record = {k: item[k] for k in ("gpu", "world", "seed")} + finished.append({**record, "returncode": code}) + active.remove(item) + write_json( + output / "dispatch.json", + { + "updated_at": stamp(), + "pending": jobs, + "running": [{k: x[k] for k in ("gpu", "world", "seed")} for x in active], + "finished": finished, + }, + ) + if active: + time.sleep(2) + if any(item.get("returncode", 0) for item in finished): + raise RuntimeError("One or more workers failed; inspect preserved logs") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("freeze", "worker", "dispatch")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--gpus", type=int, nargs="+", default=[5, 8]) + args = parser.parse_args() + config = json.loads(CONFIG.read_text()) + if args.command == "freeze": + print(json.dumps(freeze(config))) + elif args.command == "worker": + run(config, args.world, args.seed, torch.device(args.device)) + else: + dispatch(config, args.gpus) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_readout_control.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_readout_control.py new file mode 100644 index 0000000000000000000000000000000000000000..877089e7e83d985cfb9e4b5e65920b2db8312d4d --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_readout_control.py @@ -0,0 +1,373 @@ +"""H5: original E93 exception edits of all weights except tied token/readout weights.""" + +import argparse +import fcntl +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_metrics, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +SCOPE = "all-freeze-embedding" +STUDY = { + "protocol": "v2.8-h5-readout-control-E93", + "widths": [256, 768], + "parent_step": 15360, + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kind": "exception", + "scope": SCOPE, + "frozen": "token.weight, shared by input embedding and output F.linear readout", + "trainable": "all other parameters, including absolute position embedding", + "lr": 3e-5, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 48, + "E": 93, + "D": 96, + "R": 4096, + "reference_scopes": ["mlp", "all"], + "selection": "all fixed512 endpoints; no best step", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("H5 configuration differs from the fixed contract") + + +def control_sources(): + return { + **source_hashes(), + "bios_cross_continue.py": file_hash(Path(__file__).with_name("bios_cross_continue.py")), + Path(__file__).name: file_hash(__file__), + } + + +def select_control_parameters(model): + """The ordinary model passes this same Parameter directly to F.linear.""" + excluded = id(model.token.weight) + selected = [] + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) != excluded) + parameter.grad = None + if parameter.requires_grad: + selected.append(parameter) + assert model.position.weight.requires_grad and not model.token.weight.requires_grad + return selected + + +def sampling_stream(world_seed, chain, steps=512, batch=128): + rng = rng_for(world_seed, 908, chain) + return rng.integers(93, size=(steps, batch)), rng.integers(4096, size=(steps, batch)) + + +def score_arrays(arrays, truth): + for key in ("prediction", "ended", "correct"): + if arrays[key].shape != truth.shape: + raise ValueError("H5 prediction array shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("H5 EOS/correct flags must be Boolean") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def validate_parent_config(config, world): + width = config["model"]["width"] + if width not in STUDY["widths"] or config["world"] not in (0, 1): + raise ValueError("H5 parent outside original size/world matrix") + expected = dict( + vocab_size=world.vocab_size, width=width, layers=8, heads=width // 64, context=128 + ) + if config["model"] != expected or config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("H5 needs original unrestricted low-prevalence architecture") + expected_study = dict( + steps=15360, + lr=1e-4, + documents_per_step=16, + facts_per_document=10, + QA_per_chain_per_step=20, + document_QA_weights=[0.8, 0.2], + ) + if any(config["study"][key] != value for key, value in expected_study.items()): + raise ValueError("H5 parent is not the original learning budget") + if config["seed"] not in (0, 1) or config["condition"] not in CONDITIONS: + raise ValueError("H5 parent outside original initialization/organization matrix") + if config["sources"] != source_hashes() or config["truth_sha256"] != array_hash(world.answers): + raise ValueError("H5 parent source or truth mismatch") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("H5 numerical software differs from parent") + + +def reference_contract(parent, world, old_arrays): + hashes = {} + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + assert len(pair["E"]) == 93 and len(pair["D"]) == 96 and len(pair["replay"]) == 4096 + e, r = sampling_stream(world.seed, chain) + for scope in ("mlp", "all"): + dest = parent / "edits" / f"{name}-exception-{scope}" + with np.load(dest / "sets.npz") as actual: + for key, value in pair.items(): + np.testing.assert_array_equal(actual[key], value) + np.testing.assert_array_equal(actual["old_correct"], old_arrays["correct"]) + np.testing.assert_array_equal(actual["edit_sampling"], e) + np.testing.assert_array_equal(actual["replay_sampling"], r) + points = json.loads((dest / "trajectory.json").read_text()) + if [point["step"] for point in points] != list(CHECKPOINTS): + raise ValueError("Original MLP/All reference checkpoint grid differs") + if json.loads((dest / "complete.json").read_text())["status"] != "complete": + raise ValueError("Original MLP/All reference incomplete") + for step in CHECKPOINTS: + with np.load(dest / f"predictions-{step}.npz") as saved: + arrays = score_arrays(dict(saved), pair["exception"]) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], old_arrays[key]) + for filename in ( + "sets.npz", + "trajectory.json", + "complete.json", + *(f"predictions-{step}.npz" for step in CHECKPOINTS), + ): + hashes[str((dest / filename).relative_to(parent))] = file_hash(dest / filename) + return hashes + + +def load_parent(parent): + config = json.loads((parent / "config.json").read_text()) + world = make_cross_world(config["world"]) + validate_parent_config(config, world) + with np.load(parent / "predictions-15360.npz") as saved: + arrays = score_arrays(dict(saved), world.answers) + references = reference_contract(parent, world, arrays) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if checkpoint["step"] != 15360 or checkpoint["config"] != config["model"]: + raise ValueError("H5 parent checkpoint identity differs") + if ( + complete["status"] != "complete" + or state_hash(checkpoint["model"]) != complete["model_sha256"] + ): + raise ValueError("H5 parent learning checkpoint is not verified complete") + provenance = dict( + directory=str(parent), + model_sha256=complete["model_sha256"], + reference_files_sha256=references, + files_sha256={ + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + ) + return config, world, arrays, checkpoint, provenance + + +def run_case(model, baseline, data, world, parent_arrays, chain, output, identity_hash, device): + dest = output / f"{CHAINS[chain]}-exception-{SCOPE}" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_control_parameters(model) + frozen = baseline["token.weight"] + pair = edit_pair(world, chain) + e, r = sampling_stream(world.seed, chain) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=parent_arrays["correct"], + edit_sampling=e, + replay_sampling=r, + ) + new_data = tensor_queries(world, device, pair["exception"]) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW(selected, lr=3e-5, weight_decay=0.1, fused=device.type == "cuda") + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("H5 resume identity differs") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("H5 resume step differs") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], 3e-5) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS: + if not torch.equal(model.token.weight.detach().cpu(), frozen): + raise ValueError("Frozen input/output token weights changed") + if not timeline or timeline[-1]["step"] != step: + arrays = score_arrays( + evaluate(model, new_data, pair["exception"]), pair["exception"] + ) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_arrays[key]) + timeline.append( + dict( + step=step, + edit_seconds=seconds, + **edit_metrics(world, pair, arrays, parent_arrays["correct"]), + ) + ) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e[step]], device=device) + ri = torch.as_tensor(pair["replay"][r[step]], device=device) + choices = torch.as_tensor(r[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - start + atomic_torch_save( + dict(model=model.state_dict(), config=model.config_dict(), step=512), + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + dict( + status="complete", + scope=SCOPE, + kind="exception", + chain=CHAINS[chain], + final=timeline[-1], + model_sha256=state_hash(model.state_dict()), + frozen_token_sha256=state_hash({"token.weight": frozen}), + ), + ) + print( + json.dumps(dict(event="H5_edit_complete", case=dest.name, final=timeline[-1])), flush=True + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("H5 output must be separate from immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, world, arrays, checkpoint, provenance = load_parent(parent) + device = torch.device(args.device) + identity = dict( + world=world.seed, + seed=config["seed"], + condition=config["condition"], + width=config["model"]["width"], + study=STUDY, + sources=control_sources(), + parent=provenance, + torch=torch.__version__, + cuda=torch.version.cuda, + numpy=np.__version__, + device_type=device.type, + ) + path = output / "config.json" + if path.exists() and json.loads(path.read_text()) != identity: + raise ValueError("Frozen H5 worker contract changed") + if not path.exists(): + write_json(path, identity) + if (output / "complete.json").exists(): + return + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()} + data = tensor_queries(world, device) + try: + observed = score_arrays(evaluate(model, data, world.answers), world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], arrays[key]) + for chain in range(2): + run_case( + model, baseline, data, world, arrays, chain, output, file_hash(path), device + ) + write_json( + output / "complete.json", + dict(status="complete", edit_cases=2, steps=512, scope=SCOPE, finished=time.time()), + ) + except Exception as error: + write_json( + output / "failure.json", + dict(type=type(error).__name__, message=str(error), time=time.time()), + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-readout-control-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_relation_response.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_relation_response.py new file mode 100644 index 0000000000000000000000000000000000000000..2e69b15143ef5b90779481035823b06102c3b5ab --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_relation_response.py @@ -0,0 +1,187 @@ +"""A paired four-cell test of which fact controls a composite answer. + +The editor is unchanged. Derivative probes use answer contrasts, never a +composite target loss. Isolated directions preserve the OTHER direct query's +two a/c and b/c contrasts to first order, not its entire output distribution. +""" + +from dataclasses import replace + +import torch + +from .bios_direction import Suffix +from .bios_direction_cross import cross_tasks + +CELLS = ("aa", "ab", "ba", "bb") +LAYER = 4 + + +def factorial_tasks(world, seed, device): + """Rows select root targets; columns select personal targets; a/b stay fixed.""" + originals = cross_tasks(world, seed, device) + result = [] + for pair_index in range(6): + base = originals[2 * pair_index] + for cell in CELLS: + labels, tokens = base.labels.clone(), base.tokens.clone() + root, actual = base.sets["E"] + labels[root, 0] = base.metadata[cell[0]] + labels[actual, 0] = base.metadata[cell[1]] + labels[base.sets["D"], 0] = base.metadata[cell[0]] + rows = torch.arange(len(tokens), device=tokens.device) + tokens[rows, base.positions[:, 0] + 1] = labels[:, 0] + metadata = dict( + base.metadata, + cell=cell, + pair_index=pair_index, + kind="coherent" if cell[0] == cell[1] else "independent", + root_target=base.metadata[cell[0]], + actual_target=base.metadata[cell[1]], + ) + result.append( + replace( + base, + name=base.name.rsplit("-", 1)[0] + "-" + cell, + labels=labels, + tokens=tokens, + metadata=metadata, + ) + ) + return result + + +def check_reused_task(task, manifest): + """Compare actual information, including teacher-forced EOS prefixes.""" + current = task.manifest() + for key in ("sets", "labels", "old_labels", "tokens_sha256"): + assert current[key] == manifest[key], key + for key in ("world", "seed", "chain", "group", "person", "a", "b", "c", "original_ids"): + assert current["metadata"][key] == manifest["metadata"][key], key + + +def make_probe(model, task): + ids = task.sets["E"] + task.sets["D_focal"] + positions = task.positions[ids, :1] + tokens = task.tokens[ids, :5].clone() + # No desired answer is present even at masked future positions. + tokens.masked_fill_(torch.arange(5, device=tokens.device)[None] > positions, 0) + return Suffix(model, LAYER, tokens, positions) + + +def values(probe, weight, metadata): + logits = probe(weight[None])[0, :, 0] + a, b, c = (metadata[k] for k in ("a", "b", "c")) + contrasts = torch.stack((logits[:, a] - logits[:, c], logits[:, b] - logits[:, c]), -1) + return logits, contrasts + + +def derivatives(probe, weight, metadata): + w = weight.detach().clone().requires_grad_() + logits, contrasts = values(probe, w, metadata) + gradients = torch.stack( + [ + torch.autograd.grad(contrasts[i, j], w, retain_graph=True)[0] + for i in range(3) + for j in range(2) + ] + ).reshape(3, 2, *w.shape) + return logits.detach(), contrasts.detach(), gradients.detach() + + +def isolated_directions(gradients): + """Minimum-norm direct-fact controls; D is excluded from construction. + + A unit control changes the chosen fact's (a-c,b-c) by (+.5,-.5), + hence its a-b contrast by 1; the other fact has both contrasts fixed. + """ + g = gradients[:2].flatten(0, 1).flatten(1).double() + gram = g @ g.T + eig, vec = torch.linalg.eigh(gram) + keep = eig > eig[-1].clamp_min(1e-30) * 1e-10 + inverse = (vec * torch.where(keep, 1 / eig.clamp_min(1e-300), 0)[None]) @ vec.T + targets = torch.tensor([[0.5, -0.5, 0, 0], [0, 0, 0.5, -0.5]], device=g.device) + controls = targets.double() @ inverse @ g + achieved = controls @ g.T + gd = (gradients[2, 0] - gradients[2, 1]).flatten().double() + coefficients = controls @ gd + residual = gd - (gd @ g.T) @ inverse @ g + summary = { + "rank": int(keep.sum()), + "spectrum": eig.cpu().tolist(), + "control_residual": float((achieved - targets).abs().max()), + "root_response": float(coefficients[0]), + "actual_response": float(coefficients[1]), + "unexplained_D_gradient_fraction": float(residual.norm() / gd.norm().clamp_min(1e-30)), + "root_control_norm": float(controls[0].norm()), + "actual_control_norm": float(controls[1].norm()), + } + return controls.reshape(2, *gradients.shape[-2:]).to(gradients.dtype), summary + + +@torch.no_grad() +def calibrate_controls(probe, weight, metadata, gradients, magnitudes): + controls, summary = isolated_directions(gradients) + baseline_logits, baseline = values(probe, weight, metadata) + rows = [] + if summary["control_residual"] > 1e-5: + return summary, rows + for index, name in enumerate(("root", "actual")): + for magnitude in magnitudes: + for sign in (-1, 1): + delta = sign * magnitude * controls[index] + cap = min(1.0, float(1e-3 * weight.norm() / delta.norm().clamp_min(1e-30))) + delta = delta * cap + changed, after = values(probe, weight + delta, metadata) + observed = after - baseline + predicted = (gradients.double() * delta.double()).sum((-1, -2)) + other = 1 - index + logp = baseline_logits.double().log_softmax(-1) + new_logp = changed.double().log_softmax(-1) + kl = (logp.exp() * (logp - new_logp)).sum(-1) + rows.append( + dict( + control=name, + magnitude=magnitude, + sign=sign, + cap=cap, + actual_target_increment=sign * magnitude * cap, + delta_norm=float(delta.norm()), + predicted_ab=(predicted[:, 0] - predicted[:, 1]).cpu().tolist(), + observed_ab=(observed[:, 0] - observed[:, 1]).cpu().tolist(), + other_ac_bc_drift=float(observed[other].abs().max()), + other_output_kl=float(kl[other]), + direct_argmax_changes=int( + (changed[:2].argmax(-1) != baseline_logits[:2].argmax(-1)).sum() + ), + ) + ) + return summary, rows + + +def first_adam_update(model, task, config): + """Exact first-step algebra of the frozen soft-functional Adam editor.""" + ids = task.sets["E"] + task.sets["R"] + suffix = Suffix(model, LAYER, task.tokens[ids], task.positions[ids]) + w = model.blocks[LAYER].mlp.down.weight.detach().clone().requires_grad_() + logits = suffix(w[None])[0] + logp = logits.double().log_softmax(-1) + labels = task.labels[ids] + ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1) + n = len(task.sets["E"]) + # The original-parent KL has exactly zero derivative at the parent. + loss = ce[:n].mean() + ce[n:].mean() + gradient = torch.autograd.grad(loss, w)[0] + m, v = 0.1 * gradient, 0.001 * gradient.square() + t = torch.ones((), device=w.device) + raw = -(m / (1 - 0.9**t)) / ((v / (1 - 0.999**t)).sqrt() + 1e-8) + return config["lr"] * raw + + +def factorial_effects(margins): + aa, ab, ba, bb = (float(margins[cell]) for cell in CELLS) + return dict( + intercept=(aa + ab + ba + bb) / 4, + root=(aa + ab - ba - bb) / 4, + actual=(aa - ab + ba - bb) / 4, + interaction=(aa - ab - ba + bb) / 4, + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..3943eb3bac42c3c9c13d8b3c40061fc830348860 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py @@ -0,0 +1,372 @@ +"""Locked independent-world behavioral confirmation, never a route-mediation claim. + +The original learning implementation and the audited E39 update implementation +are called directly. An external prospective lock is mandatory before execution. +""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_train import learning, source_hashes +from .bios_data import write_json +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import autonomous_two_step +from .bios_shortcut_confirmation_sets import make_confirmation_edit_pair +from .bios_shortcut_control import high_exception_world +from .bios_shortcut_edit_v2 import STUDY as DEVELOPMENT_EDIT_STUDY +from .bios_shortcut_edit_v2 import run_case +from .bios_shortcut_matched_edit import KINDS, PHASES + +PROTOCOL = "v2.9-shortcut-behavior-confirmation" +WORLDS = tuple(range(100, 108)) +LEARNING_CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360) + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + while chunk := stream.read(4 * 1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def confirmation_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + "scripts/prepare_bios_shortcut_confirmation.py": file_hash( + directory.parents[1] / "scripts/prepare_bios_shortcut_confirmation.py" + ), + **{ + name: file_hash(directory / name) + for name in ( + "bios_shortcut_confirmation.py", + "bios_shortcut_confirmation_sets.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit_v2.py", + "bios_cross_continue.py", + "bios_path_diagnostics.py", + ) + }, + } + + +def validate_config(config): + expected = { + "protocol": PROTOCOL, + "worlds": list(WORLDS), + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "phases": list(PHASES), + "chains": list(CHAINS), + "supports": [0, 1], + "width": 256, + "layers": 8, + "heads": 4, + "steps": 15360, + "checkpoints": list(LEARNING_CHECKPOINTS), + "lr": 0.0001, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "learning_runs": 96, + "edit_cases": 768, + "edit_steps": 512, + "edit_checkpoints": [0, 32, 128, 512], + "edit_lr": 0.00003, + "retention_kl": 1.0, + "edit_scope": "mlp", + "edit_mlp_layers": [3, 4, 5], + "edit_batch": 128, + "replay_batch": 128, + "edit_weight_decay": 0.1, + "E": 39, + "D": 96, + "R": 4096, + "base_world_root": "data/bios-shortcut-confirmation-v1", + "source_root": "data/bios-source", + } + for key, value in expected.items(): + if config.get(key) != value: + raise ValueError(f"Prospective confirmation contract differs: {key}") + for key in ("steps", "checkpoints", "lr", "retention_kl", "E", "D", "R"): + source = {"steps": "edit_steps", "checkpoints": "edit_checkpoints", "lr": "edit_lr"} + if DEVELOPMENT_EDIT_STUDY[key] != config[source.get(key, key)]: + raise ValueError(f"Imported E39 scientific update differs: {key}") + if config.get("edit_sampling") != "shared original world932chain stream across supports": + raise ValueError("The two supports retain the original paired sampling stream") + + +def validate_frozen_design(config_path, lock_path): + config = json.loads(Path(config_path).read_text()) + validate_config(config) + lock = json.loads(Path(lock_path).read_text()) + if lock.get("status") != "frozen_before_any_confirmation_model_or_outcome": + raise ValueError("A prospective confirmation lock is required") + if lock["config_sha256"] != file_hash(config_path): + raise ValueError("Confirmation configuration changed after locking") + if lock["sources"] != confirmation_sources(): + raise ValueError("Confirmation scientific sources changed after locking") + environment = {"torch": torch.__version__, "cuda": torch.version.cuda, "numpy": np.__version__} + if lock["environment"] != environment: + raise ValueError("Confirmation numerical environment changed after locking") + if not lock.get("analysis_sources"): + raise ValueError("The prospective analysis implementation must also be locked") + root = Path(__file__).resolve().parents[2] + for relative, checksum in lock["analysis_sources"].items(): + if file_hash(root / relative) != checksum: + raise ValueError(f"Prospective analysis source changed: {relative}") + if not lock.get("data_source_files"): + raise ValueError("Original data source files must be prospectively locked") + for relative, checksum in lock["data_source_files"].items(): + if file_hash(root / relative) != checksum: + raise ValueError(f"Original data source changed: {relative}") + return config, lock + + +def validate_lock(config_path, lock_path, args): + config, lock = validate_frozen_design(config_path, lock_path) + if torch.device(args.device).type != "cuda" or lock.get("device_type") != "cuda": + raise ValueError("Confirmation requires CUDA BF16 execution, never mixed CPU precision") + if args.world not in WORLDS or args.seed not in (0, 1): + raise ValueError("Only the eight reserved worlds and two initializations are allowed") + if args.phase not in PHASES or args.condition not in CONDITIONS: + raise ValueError("Condition outside the prospective matrix") + expected_output = ( + Path(lock["output_root"]) + / args.phase + / "width-256" + / f"world-{args.world}-seed-{args.seed}-{args.condition}" + ).resolve() + if Path(args.output).resolve() != expected_output: + raise ValueError("Output differs from the prospective matrix") + return config, lock + + +def validate_prepared_world(config, config_path, lock_path, world): + if world not in WORLDS: + raise ValueError("Requested world is outside the prospective preparation matrix") + root = Path(__file__).resolve().parents[2] / config["base_world_root"] + receipt = json.loads((root / "preparation-audit.json").read_text()) + lock = json.loads(Path(lock_path).read_text()) + if ( + receipt.get("complete") is not True + or receipt["config_sha256"] != file_hash(config_path) + or receipt["lock_sha256"] != file_hash(lock_path) + or receipt["worlds"] != list(WORLDS) + ): + raise ValueError("Base worlds lack a complete prospectively locked preparation") + if receipt.get("source_files_sha256") != lock["data_source_files"]: + raise ValueError("Prepared world source files differ from the prospective lock") + filenames = ("world.npz", "metadata.json", "audit.json") + expected_files = {f"world-{seed}/{name}" for seed in WORLDS for name in filenames} + if set(receipt.get("files_sha256", {})) != expected_files: + raise ValueError("Prepared world file manifest differs from the prospective matrix") + for name in filenames: + relative = f"world-{world}/{name}" + if receipt["files_sha256"].get(relative) != file_hash(root / relative): + raise ValueError(f"Prepared world changed: {relative}") + metadata = json.loads((root / f"world-{world}/metadata.json").read_text()) + if type(metadata.get("seed")) is not int or metadata["seed"] != world: + raise ValueError("Prepared world metadata seed differs from the requested world") + return root, receipt + + +def case_identity(worker_identity, chain, support, kind, pair): + payload = { + "worker_identity": worker_identity, + "chain": chain, + "support": support, + "kind": kind, + "pair_contract": pair["contract"], + } + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + + +def expected_weight_artifacts(): + names = [f"learning/model-{step}.pt" for step in LEARNING_CHECKPOINTS] + names.append("learning/resume.pt") + names.extend( + f"edits/support-{support}/{chain}-{kind}-mlp/{filename}" + for support in (0, 1) + for chain in CHAINS + for kind in KINDS + for filename in ("model-final.pt", "resume.pt") + ) + return names + + +def scientific_artifacts(output): + for relative in expected_weight_artifacts(): + if not (output / relative).is_file(): + raise ValueError(f"Required confirmation weight artifact is missing: {relative}") + paths = [output / "launch-contract.json", output / "manipulation.npz"] + paths.extend(p for p in (output / "learning").iterdir() if p.is_file()) + paths.extend(p for p in (output / "edits").rglob("*") if p.is_file()) + return { + str(p.relative_to(output)): {"bytes": p.stat().st_size, "sha256": file_hash(p)} + for p in sorted(paths) + } + + +def run(args): + config, _ = validate_lock(args.config, args.lock, args) + output = Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=True) + with (output / ".worker.lock").open("w") as handle: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + base_root, data_receipt = validate_prepared_world( + config, args.config, args.lock, args.world + ) + if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported(): + raise ValueError("A healthy CUDA device with BF16 support is required") + identity = { + "protocol": PROTOCOL, + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "phase": args.phase, + "config_sha256": file_hash(args.config), + "preregistration_lock_sha256": file_hash(args.lock), + "sources": confirmation_sources(), + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": "cuda", + "precision": "BF16 autocast; FP32 model and optimizer", + "prepared_worlds_audit_sha256": file_hash(base_root / "preparation-audit.json"), + "world_files_sha256": { + name: checksum + for name, checksum in data_receipt["files_sha256"].items() + if name.startswith(f"world-{args.world}/") + }, + } + path = output / "launch-contract.json" + if path.exists() and json.loads(path.read_text()) != identity: + raise ValueError("Confirmation worker identity changed") + if not path.exists(): + write_json(path, identity) + if (output / "complete.json").exists(): + return + try: + low = make_cross_world(args.world, source_root=base_root) + high, manipulation, selected, donors = high_exception_world(low) + world = low if args.phase == "low" else high + pairs = { + (chain, support): make_confirmation_edit_pair(low, high, chain, support) + for chain in range(2) + for support in (0, 1) + } + for chain in range(2): + for key in ("groups", "E", "D", "selected_people"): + if np.intersect1d(pairs[chain, 0][key], pairs[chain, 1][key]).size: + raise ValueError(f"The two supports overlap: {key}") + atomic_numpy_save( + output / "manipulation.npz", + selections=selected, + donors=donors, + low_answers=low.answers, + high_answers=high.answers, + high_exceptions=high.exceptions, + ) + study = { + **config, + "confirmation_sources": identity["sources"], + "phase": args.phase, + "manipulation": manipulation, + } + learning_output = output / "learning" + learning_output.mkdir(exist_ok=True) + device = torch.device(args.device) + model, data = learning(args, world, learning_output, study, device) + with np.load(learning_output / "predictions-15360.npz") as saved: + baseline_predictions = { + key: saved[key] for key in ("prediction", "ended", "correct", "value_nll") + } + np.testing.assert_array_equal( + baseline_predictions["correct"], + (baseline_predictions["prediction"] == world.answers) + & baseline_predictions["ended"], + ) + completed = json.loads((learning_output / "learning-complete.json").read_text()) + if completed["model_sha256"] != state_hash(model.state_dict()): + raise ValueError("Learning baseline differs from completed weights") + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update( + {f"direct_{key}": value[ids] for key, value in baseline_predictions.items()} + ) + atomic_numpy_save(learning_output / f"two-step-{name}.npz", **arrays) + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + identity_hash = file_hash(path) + for support in (0, 1): + edit_output = output / "edits" / f"support-{support}" + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain, support], + args.phase, + kind, + chain, + edit_output, + case_identity( + identity_hash, chain, support, kind, pairs[chain, support] + ), + baseline_predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "protocol": PROTOCOL, + "learning_steps": 15360, + "edit_cases": 8, + "edit_steps": 512, + "lock_sha256": file_hash(args.lock), + "artifacts": scientific_artifacts(output), + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--config", required=True) + parser.add_argument("--lock", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py new file mode 100644 index 0000000000000000000000000000000000000000..8535796aba3f18178d69d214c04bc922b0dfa21d --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py @@ -0,0 +1,192 @@ +"""Two prospectively fixed E39 supports; preparation never launches a model. + +Support zero exactly preserves development selection. Support one uses a +separate deterministic stream and excludes the first support's entire groups. +The original E39 audit validates both; all training and target budgets match. +""" + +import numpy as np + +from .bios_data import array_hash, rng_for +from .bios_shortcut_control import audit_high_exception +from .bios_shortcut_matched_edit import ( + KINDS, + PHASES, + U_STRATA, + audit_matched_edit_pair, +) +from .bios_shortcut_matched_edit import ( + make_matched_edit_pair as development_pair, +) + +BUDGET = { + "prevalence_levels": 2, + "worlds": 8, + "initializations": 2, + "organizations": 3, + "models": 96, + "chains": 2, + "update_types": 2, + "supports_per_chain": 2, + "scopes": ["mlp"], + "edit_cases": 768, +} + + +def make_confirmation_edit_pair(low, high, chain, support=0): + """Three roots + 36 actual facts; same IDs and support labels across phases. + + Each selected group contributes six QA-trained and six QA-heldout people + who remain ordinary in the high-prevalence world. Coherent assigns all 12 + to the new default. Exception assigns three default/three alternative in + each split. Histograms match ACROSS all three groups, not within a group. + """ + if chain not in (0, 1) or support not in (0, 1): + raise ValueError("Confirmation fixes two chains and two disjoint supports") + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high worlds must share their identity and query layout") + audit_high_exception(low, high) + first = development_pair(low, high, chain) + if support == 0: + first["contract"].update( + protocol="v2.9-shortcut-behavior-confirmation-E39", + status="prospectively_fixed_confirmation_support", + budget=BUDGET.copy(), + model_checkpoint="width256, independent-world 15360-step low/high learning", + ) + return first + eligible_groups = np.setdiff1d(np.arange(64), first["groups"]) + rng = rng_for(low.seed, 931, chain + 2 * support) + for _ in range(10000): + groups = rng.choice(eligible_groups, 3, replace=False) + if len(np.unique(low.defaults[chain, groups])) == 3: + break + else: + raise RuntimeError("Could not find three groups with distinct default cities") + selected = np.empty((3, 12), dtype=np.int64) + conflict = np.zeros((3, 12), dtype=bool) + conflict[:, :3] = conflict[:, 6:9] = True + targets = { + f"{phase}_{kind}": world.answers.copy() + for phase, world in (("low", low), ("high", high)) + for kind in KINDS + } + new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + for index, group in enumerate(groups): + ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] + if len(eligible) != 8: + raise ValueError("Expected eight still-ordinary people in each QA split") + selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] + actual = low.actual_ids[chain, selected[index]] + derived = low.derived_ids[chain, low.memberships[chain] == group] + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + target[low.root_ids[chain, group]] = new_default[index] + target[derived] = new_default[index] + target[actual] = new_default[index] + if kind == "exception": + target[actual[conflict[index]]] = alternative[index] + edited_people = selected.ravel() + selected_people = np.isin(low.memberships[chain], groups) + original = selected_people & low.exceptions[chain] + newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] + unedited_ordinary = ( + selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) + ) + e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) + d = low.derived_ids[chain, selected_people] + unchanged = np.ones(len(low.answers), dtype=bool) + unchanged[np.concatenate([e, d])] = False + affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] + original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) + newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) + relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(low.answers), -1, dtype=np.int64) + strata[unchanged & original_actual] = 0 + strata[unchanged & newly_actual] = 1 + strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 + strata[unchanged & ~affected_facts & relevant] = 3 + strata[unchanged & ~affected_facts & ~relevant] = 4 + heldout = [] + for stratum in range(5): + ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) + heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) + heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) + heldout = np.array(sorted(heldout), dtype=np.int64) + common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) + common_pool = np.setdiff1d(common_pool, heldout) + if len(common_pool) < 4096: + raise ValueError("Insufficient shared unchanged base facts for R4096") + replay = rng.choice(common_pool, 4096, replace=False) + paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) + pair = { + **targets, + "groups": groups, + "selected_people": selected, + "alternative_assignments": conflict, + "new_default": new_default, + "alternative": alternative, + "E": e, + "D": d, + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, edited_people]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), + "paired_reference_D": paired_reference, + "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "exception_conflict_D": paired_reference.copy(), + "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, original], + "D_newly_exception": low.derived_ids[chain, newly], + "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], + "R": replay, + "U_full": np.flatnonzero(unchanged), + "U_heldout": heldout, + "U_strata": strata, + } + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + actual_for_d = target[low.actual_ids[chain, selected_people]] + pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] + pair["contract"] = { + "protocol": "v2.9-shortcut-behavior-confirmation-E39", + "world": low.seed, + "chain": chain, + "support": support, + "status": "prospectively_fixed_confirmation_support", + "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, + "model_checkpoint": ("width256, independent-world 15360-step low/high learning"), + "histogram_matching_scope": ( + "all three groups combined; also separately for trained/heldout QA" + ), + "coherent_actuals_per_group": "12 new-default (six in each QA split)", + "exception_actuals_per_group": ( + "6 new-default + 6 alternative (three + three in each QA split)" + ), + "paired_reference_semantics": ( + "same 18 people; conflict only in exception, reference only in coherent" + ), + "R_semantics": ( + "4096 identical query IDs with identical original truths " + "and unchanged under all four targets" + ), + "U_semantics": ( + "common query IDs; score each phase against its own truth and old-correct coverage" + ), + "U_strata": U_STRATA.copy(), + "historical_E93_comparable": False, + "low_truth_sha256": array_hash(low.answers), + "high_truth_sha256": array_hash(high.answers), + "array_sha256": {key: array_hash(value) for key, value in pair.items()}, + } + audit_matched_edit_pair(low, high, chain, pair) + return pair diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_control.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_control.py new file mode 100644 index 0000000000000000000000000000000000000000..60ee531b9c2a08e1cf2cfba210a312300b93480d --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_control.py @@ -0,0 +1,242 @@ +"""P3: alter shortcut reliability while preserving marginal answer counts. + +The archived crossover generator and trainer are imported, never rewritten. +The two chains are manipulated simultaneously; QA identities remain unchanged. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import time +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CONDITIONS, audit, documents, make_cross_world, qa_schedule +from .bios_cross_train import learning, source_hashes +from .bios_data import array_hash, rng_for, write_json +from .bios_organization_train import atomic_numpy_save + + +def high_exception_world(old): + """Raise both chains from two to sixteen exceptions per 32-member group.""" + audit(old) + answers, exceptions = old.answers.copy(), old.exceptions.copy() + selections = np.empty((2, 64, 14), dtype=np.int64) + donors = np.empty((2, 14, 64), dtype=np.int64) + for chain in range(2): + rng = rng_for(old.seed, 930, chain) + for group in range(64): + ordinary = np.flatnonzero((old.memberships[chain] == group) & ~old.exceptions[chain]) + people = [] + for query_pool in (old.train_ids[chain], old.heldout_ids[chain]): + eligible = ordinary[np.isin(old.derived_ids[chain, ordinary], query_pool)] + people.extend(rng.permutation(eligible)[:7]) + selections[chain, group] = people + # Every lane contains one ordinary member per group. A city-deranged + # bijection preserves the histogram exactly, separately in each QA split. + for lane in range(14): + for _ in range(10000): + donor = rng.permutation(64) + if np.all(old.defaults[chain, donor] != old.defaults[chain]): + break + else: + raise RuntimeError("Could not construct a city-deranged permutation") + donors[chain, lane] = donor + selected = selections[chain, :, lane] + answers[old.actual_ids[chain, selected]] = old.city_tokens[old.defaults[chain, donor]] + exceptions[chain, selected] = True + world = replace(old, answers=answers, exceptions=exceptions) + record = audit_high_exception(old, world) + record["selection_sha256"] = array_hash(selections) + record["donors_sha256"] = array_hash(donors) + return world, record, selections, donors + + +def audit_high_exception(old, new): + """Fail if the manipulation changes anything outside its declared contract.""" + allowed = old.actual_ids.ravel() + unchanged = np.setdiff1d(np.arange(len(old.answers)), allowed) + np.testing.assert_array_equal(old.answers[unchanged], new.answers[unchanged]) + for field in ( + "prompts", + "lengths", + "relation", + "person", + "memberships", + "defaults", + "membership_ids", + "root_ids", + "actual_ids", + "derived_ids", + "train_ids", + "heldout_ids", + "city_tokens", + ): + np.testing.assert_array_equal(getattr(old, field), getattr(new, field)) + if old.token_labels != new.token_labels: + raise ValueError("Vocabulary changed") + records = [] + for chain in range(2): + ids = old.actual_ids[chain] + np.testing.assert_array_equal(np.sort(old.answers[ids]), np.sort(new.answers[ids])) + truth_exception = ( + new.answers[ids] != new.city_tokens[new.defaults[chain, new.memberships[chain]]] + ) + np.testing.assert_array_equal(truth_exception, new.exceptions[chain]) + if np.any(old.exceptions[chain] & ~new.exceptions[chain]): + raise ValueError("An original exception was removed") + for group in range(64): + members = new.memberships[chain] == group + if int(new.exceptions[chain, members].sum()) != 16: + raise ValueError("Expected sixteen exceptions per group") + for pool in (new.train_ids[chain], new.heldout_ids[chain]): + people = np.flatnonzero(members & np.isin(new.derived_ids[chain], pool)) + if len(people) != 16 or new.exceptions[chain, people].sum() != 8: + raise ValueError("QA split no longer has eight exceptions per group") + for pool in (new.train_ids[chain], new.heldout_ids[chain]): + people = np.flatnonzero(np.isin(new.derived_ids[chain], pool)) + np.testing.assert_array_equal( + np.sort(old.answers[ids[people]]), np.sort(new.answers[ids[people]]) + ) + records.append( + { + "chain": chain, + "old_exceptions": int(old.exceptions[chain].sum()), + "new_exceptions": int(new.exceptions[chain].sum()), + "changed_actual_facts": int((old.answers[ids] != new.answers[ids]).sum()), + "answer_histogram_preserved": True, + "split_histograms_preserved": True, + } + ) + for condition in CONDITIONS: + np.testing.assert_array_equal(documents(old, condition), documents(new, condition)) + np.testing.assert_array_equal(qa_schedule(old, 1280), qa_schedule(new, 1280)) + return { + "passed": True, + "world": old.seed, + "old_truth_sha256": array_hash(old.answers), + "new_truth_sha256": array_hash(new.answers), + "prompts_sha256": array_hash(new.prompts), + "chains": records, + "changed_total": int((old.answers != new.answers).sum()), + "document_identities_and_QA_split_preserved": True, + } + + +def shortcut_sources(): + diagnostic = Path(__file__).with_name("bios_path_diagnostics.py") + return { + **source_hashes(), + Path(__file__).name: hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + diagnostic.name: hashlib.sha256(diagnostic.read_bytes()).hexdigest(), + } + + +def run(args): + out = Path(args.output).resolve() + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + study = json.loads(Path(args.config).read_text()) + if study["width"] != 256 or study["steps"] != 15360: + raise ValueError("P3 freezes width 256 and 15360 steps") + old = make_cross_world(args.world) + world, manipulation, selected, donors = high_exception_world(old) + contract = { + "protocol": "v2.8-p3-shortcut-reliability", + "study": study, + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "sources": shortcut_sources(), + "manipulation": manipulation, + "environment": { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + } + contract_path = out / "launch-contract.json" + if contract_path.exists(): + frozen = json.loads(contract_path.read_text()) + for key in ( + "protocol", + "study", + "world", + "seed", + "condition", + "sources", + "manipulation", + ): + if frozen[key] != contract[key]: + raise ValueError(f"Frozen shortcut contract changed: {key}") + else: + write_json(contract_path, contract) + atomic_numpy_save( + out / "manipulation.npz", + selections=selected, + donors=donors, + old_answers=old.answers, + answers=world.answers, + exceptions=world.exceptions, + train_ids=world.train_ids, + heldout_ids=world.heldout_ids, + ) + if (out / "complete.json").exists(): + return + # Include adapter provenance in the archived trainer's own run identity. + study = {**study, "shortcut_contract": contract["sources"]} + torch.set_num_threads(args.threads) + try: + from .bios_path_diagnostics import autonomous_two_step + + device = torch.device(args.device) + model, _ = learning(args, world, out, study, device) + with np.load(out / f"predictions-{study['steps']}.npz") as saved: + direct = {k: saved[k] for k in ("prediction", "ended", "correct")} + for chain, name in enumerate(("company", "project")): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) + atomic_numpy_save(out / f"two-step-{name}.npz", **arrays) + write_json( + out / "complete.json", + { + "status": "complete", + "phase": "P3-learning-only", + "learning_steps": study["steps"], + "edit_cases": 0, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + { + "type": type(error).__name__, + "message": str(error), + "time": time.time(), + }, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--config", default="configs/bios-shortcut-control-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_edit.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..856a9a8a4fd753c498c4b965d5c30a057bdebffd --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_edit.py @@ -0,0 +1,446 @@ +"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents.""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_shortcut_control import high_exception_world, shortcut_sources +from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +STUDY = { + "protocol": "v2.8-p3-shortcut-matched-E39", + "width": 256, + "parent_step": 15360, + "phases": list(PHASES), + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kinds": list(KINDS), + "scope": "mlp", + "mlp_layers": [3, 4, 5], + "lr": 0.00003, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 96, + "E": 39, + "D": 96, + "R": 4096, + "primary_reference_D": 18, + "primary_reference_D_heldout": 9, + "status": "prepared conditional branch; no best-step selection", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("E39 editing configuration differs from the frozen prepared contract") + + +def editing_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ( + "bios_cross_continue.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit.py", + ) + }, + } + + +def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): + """No phase, organization, initialization, or update-type dependence.""" + rng = rng_for(world_seed, 932, chain) + return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch)) + + +def score_arrays(arrays, truth): + if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): + raise ValueError("Prediction shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("EOS and correctness must be Boolean arrays") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def query_metrics(correct, ids): + n = len(ids) + count = int(correct[ids].sum()) + return {"n": n, "correct": count, "accuracy": count / n if n else None} + + +def retention_metrics(correct, old_correct, ids): + n = len(ids) + known_ids = ids[old_correct[ids]] + broken = int((~correct[known_ids]).sum()) + return { + "n": n, + "known": len(known_ids), + "coverage": len(known_ids) / n if n else None, + "broken": broken, + "damage": broken / len(known_ids) if len(known_ids) else None, + } + + +def edit_metrics(pair, phase, kind, arrays, old_correct): + correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] + if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: + raise ValueError("Old-correct coverage array mismatch") + result = { + key: query_metrics(correct, pair[key]) + for key in ( + "E", + "E_roots", + "E_actual", + "D", + "D_trained", + "D_heldout", + "paired_reference_D", + "paired_reference_D_heldout", + "D_edited_actual", + "D_edited_aligned", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + } + if kind == "exception": + result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) + result["exception_conflict_D_heldout"] = query_metrics( + correct, pair["exception_conflict_D_heldout"] + ) + result["factual_conflict_D"] = query_metrics( + correct, pair[f"{phase}_{kind}_factual_conflict_D"] + ) + for pool in ("U_full", "U_heldout"): + ids = pair[pool] + result[pool] = { + **retention_metrics(correct, old_correct, ids), + "strata": { + str(group): retention_metrics( + correct, old_correct, ids[pair["U_strata"][ids] == group] + ) + for group in range(5) + }, + } + return result + + +def load_parent(parent, phase): + config = json.loads((parent / "config.json").read_text()) + expected_model = dict(vocab_size=4804, width=256, layers=8, heads=4, context=128) + if config["model"] != expected_model or config["study"]["steps"] != 15360: + raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") + if any( + config["study"][key] != value + for key, value in { + "lr": 1e-4, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + }.items() + ): + raise ValueError("E39 parent exposure or learning budget differs") + if ( + config["world"] not in (0, 1) + or config["seed"] not in (0, 1) + or config["condition"] not in CONDITIONS + ): + raise ValueError("Parent is outside the fixed development matrix") + if config["sources"] != source_hashes(): + raise ValueError("Parent frozen trainer sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent numerical software differs") + if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("Low parent is not an original unrestricted-context run") + if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): + raise ValueError("High parent manipulation/source provenance changed") + low = make_cross_world(config["world"]) + high, _, _, _ = high_exception_world(low) + world = low if phase == "low" else high + if config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent truth differs from its declared prevalence phase") + with np.load(parent / "predictions-15360.npz") as saved: + predictions = score_arrays( + {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, + world.answers, + ) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if ( + checkpoint["step"] != 15360 + or checkpoint["config"] != config["model"] + or complete["status"] != "complete" + ): + raise ValueError("Parent learning has not completed the specified checkpoint") + if state_hash(checkpoint["model"]) != complete["model_sha256"]: + raise ValueError("Parent checkpoint differs from completed learning weights") + provenance = { + "directory": str(parent), + "files_sha256": { + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + "model_sha256": complete["model_sha256"], + } + return config, checkpoint, predictions, low, high, world, provenance + + +def run_case( + model, + baseline, + data, + world, + pair, + phase, + kind, + chain, + output, + identity_hash, + parent_predictions, + device, +): + dest = output / f"{CHAINS[chain]}-{kind}-mlp" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + e_choices, r_choices = sampling_stream(world.seed, chain) + saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} + saved_sets.update( + old_correct=parent_predictions["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + atomic_numpy_save(dest / "sets.npz", **saved_sets) + write_json(dest / "data-contract.json", pair["contract"]) + target = pair[f"{phase}_{kind}"] + new_data = tensor_queries(world, device, target) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["R"]), 256): + ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW( + selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("E39 resume identity mismatch") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("E39 resume step mismatch") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, new_data, target) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_predictions[key]) + point = { + "step": step, + "edit_seconds": seconds, + **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "phase": phase, + "chain": CHAINS[chain], + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + print( + json.dumps( + { + "event": "E39_edit_complete", + "case": dest.name, + "E": timeline[-1]["E"]["accuracy"], + "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], + } + ), + flush=True, + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("E39 output must be separate from its immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, checkpoint, predictions, low, high, world, provenance = load_parent( + parent, args.phase + ) + pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] + identity = { + "phase": args.phase, + "world": world.seed, + "seed": config["seed"], + "condition": config["condition"], + "study": STUDY, + "sources": editing_sources(), + "parent": provenance, + "data_contracts": [pair["contract"] for pair in pairs], + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": torch.device(args.device).type, + } + identity_path = output / "config.json" + if identity_path.exists() and json.loads(identity_path.read_text()) != identity: + raise ValueError("E39 editing identity or sources changed") + if not identity_path.exists(): + write_json(identity_path, identity) + if (output / "complete.json").exists(): + return + device = torch.device(args.device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_queries(world, device) + try: + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + observed = evaluate(model, data, world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], predictions[key]) + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain], + args.phase, + kind, + chain, + output, + file_hash(identity_path), + predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": args.phase, + "edit_cases": 4, + "steps": 512, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..52dd3441331f501688eedfe95286f26462de3625 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py @@ -0,0 +1,446 @@ +"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents.""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_shortcut_control import high_exception_world, shortcut_sources +from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +STUDY = { + "protocol": "v2.8-p3-shortcut-matched-E39", + "width": 256, + "parent_step": 15360, + "phases": list(PHASES), + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kinds": list(KINDS), + "scope": "mlp", + "mlp_layers": [3, 4, 5], + "lr": 0.00003, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 96, + "E": 39, + "D": 96, + "R": 4096, + "primary_reference_D": 18, + "primary_reference_D_heldout": 9, + "status": "prepared conditional branch; no best-step selection", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("E39 editing configuration differs from the frozen prepared contract") + + +def editing_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ( + "bios_cross_continue.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit_v2.py", + ) + }, + } + + +def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): + """No phase, organization, initialization, or update-type dependence.""" + rng = rng_for(world_seed, 932, chain) + return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch)) + + +def score_arrays(arrays, truth): + if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): + raise ValueError("Prediction shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("EOS and correctness must be Boolean arrays") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def query_metrics(correct, ids): + n = len(ids) + count = int(correct[ids].sum()) + return {"n": n, "correct": count, "accuracy": count / n if n else None} + + +def retention_metrics(correct, old_correct, ids): + n = len(ids) + known_ids = ids[old_correct[ids]] + broken = int((~correct[known_ids]).sum()) + return { + "n": n, + "known": len(known_ids), + "coverage": len(known_ids) / n if n else None, + "broken": broken, + "damage": broken / len(known_ids) if len(known_ids) else None, + } + + +def edit_metrics(pair, phase, kind, arrays, old_correct): + correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] + if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: + raise ValueError("Old-correct coverage array mismatch") + result = { + key: query_metrics(correct, pair[key]) + for key in ( + "E", + "E_roots", + "E_actual", + "D", + "D_trained", + "D_heldout", + "paired_reference_D", + "paired_reference_D_heldout", + "D_edited_actual", + "D_edited_aligned", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + } + if kind == "exception": + result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) + result["exception_conflict_D_heldout"] = query_metrics( + correct, pair["exception_conflict_D_heldout"] + ) + result["factual_conflict_D"] = query_metrics( + correct, pair[f"{phase}_{kind}_factual_conflict_D"] + ) + for pool in ("U_full", "U_heldout"): + ids = pair[pool] + result[pool] = { + **retention_metrics(correct, old_correct, ids), + "strata": { + str(group): retention_metrics( + correct, old_correct, ids[pair["U_strata"][ids] == group] + ) + for group in range(5) + }, + } + return result + + +def load_parent(parent, phase): + config = json.loads((parent / "config.json").read_text()) + low = make_cross_world(config["world"]) + expected_model = dict(vocab_size=low.vocab_size, width=256, layers=8, heads=4, context=128) + if config["model"] != expected_model or config["study"]["steps"] != 15360: + raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") + if any( + config["study"][key] != value + for key, value in { + "lr": 1e-4, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + }.items() + ): + raise ValueError("E39 parent exposure or learning budget differs") + if ( + config["world"] not in (0, 1) + or config["seed"] not in (0, 1) + or config["condition"] not in CONDITIONS + ): + raise ValueError("Parent is outside the fixed development matrix") + if config["sources"] != source_hashes(): + raise ValueError("Parent frozen trainer sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent numerical software differs") + if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("Low parent is not an original unrestricted-context run") + if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): + raise ValueError("High parent manipulation/source provenance changed") + high, _, _, _ = high_exception_world(low) + world = low if phase == "low" else high + if config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent truth differs from its declared prevalence phase") + with np.load(parent / "predictions-15360.npz") as saved: + predictions = score_arrays( + {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, + world.answers, + ) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if ( + checkpoint["step"] != 15360 + or checkpoint["config"] != config["model"] + or complete["status"] != "complete" + ): + raise ValueError("Parent learning has not completed the specified checkpoint") + if state_hash(checkpoint["model"]) != complete["model_sha256"]: + raise ValueError("Parent checkpoint differs from completed learning weights") + provenance = { + "directory": str(parent), + "files_sha256": { + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + "model_sha256": complete["model_sha256"], + } + return config, checkpoint, predictions, low, high, world, provenance + + +def run_case( + model, + baseline, + data, + world, + pair, + phase, + kind, + chain, + output, + identity_hash, + parent_predictions, + device, +): + dest = output / f"{CHAINS[chain]}-{kind}-mlp" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + e_choices, r_choices = sampling_stream(world.seed, chain) + saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} + saved_sets.update( + old_correct=parent_predictions["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + atomic_numpy_save(dest / "sets.npz", **saved_sets) + write_json(dest / "data-contract.json", pair["contract"]) + target = pair[f"{phase}_{kind}"] + new_data = tensor_queries(world, device, target) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["R"]), 256): + ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW( + selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("E39 resume identity mismatch") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("E39 resume step mismatch") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, new_data, target) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_predictions[key]) + point = { + "step": step, + "edit_seconds": seconds, + **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "phase": phase, + "chain": CHAINS[chain], + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + print( + json.dumps( + { + "event": "E39_edit_complete", + "case": dest.name, + "E": timeline[-1]["E"]["accuracy"], + "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], + } + ), + flush=True, + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("E39 output must be separate from its immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, checkpoint, predictions, low, high, world, provenance = load_parent( + parent, args.phase + ) + pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] + identity = { + "phase": args.phase, + "world": world.seed, + "seed": config["seed"], + "condition": config["condition"], + "study": STUDY, + "sources": editing_sources(), + "parent": provenance, + "data_contracts": [pair["contract"] for pair in pairs], + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": torch.device(args.device).type, + } + identity_path = output / "config.json" + if identity_path.exists() and json.loads(identity_path.read_text()) != identity: + raise ValueError("E39 editing identity or sources changed") + if not identity_path.exists(): + write_json(identity_path, identity) + if (output / "complete.json").exists(): + return + device = torch.device(args.device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_queries(world, device) + try: + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + observed = evaluate(model, data, world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], predictions[key]) + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain], + args.phase, + kind, + chain, + output, + file_hash(identity_path), + predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": args.phase, + "edit_cases": 4, + "steps": 512, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..684e672ca551a48aacb2f4bc81db94092282f4cf --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py @@ -0,0 +1,327 @@ +"""Prepared E39 update sets shared by low/high shortcut-reliability worlds. + +This file generates and audits data only. It neither trains nor edits a model. +The 96 proposed MLP edits are distinct from the archived E93 experiment. +""" + +import numpy as np + +from .bios_data import array_hash, rng_for +from .bios_shortcut_control import audit_high_exception + +KINDS = ("coherent", "exception") +PHASES = ("low", "high") +BUDGET = { + "prevalence_levels": 2, + "worlds": 2, + "initializations": 2, + "organizations": 3, + "models": 24, + "chains": 2, + "update_types": 2, + "supports_per_chain": 1, + "scopes": ["mlp"], + "edit_cases": 96, +} +U_STRATA = { + "0": "original_exception_actual_in_affected_groups", + "1": "newly_exception_actual_in_affected_groups", + "2": "other_unchanged_facts_of_affected_people", + "3": "remaining_same_chain_facts", + "4": "remaining_cross_chain_or_independent_facts", +} + + +def make_matched_edit_pair(low, high, chain, support=0): + """Three roots + 36 actual facts; same IDs and support labels across phases. + + Each selected group contributes six QA-trained and six QA-heldout people + who remain ordinary in the high-prevalence world. Coherent assigns all 12 + to the new default. Exception assigns three default/three alternative in + each split. Histograms match ACROSS all three groups, not within a group. + """ + if chain not in (0, 1) or support != 0: + raise ValueError("The prepared contract fixes two chains and support zero") + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high worlds must share their identity and query layout") + audit_high_exception(low, high) + rng = rng_for(low.seed, 931, chain) + for _ in range(10000): + groups = rng.choice(64, 3, replace=False) + if len(np.unique(low.defaults[chain, groups])) == 3: + break + else: + raise RuntimeError("Could not find three groups with distinct default cities") + selected = np.empty((3, 12), dtype=np.int64) + conflict = np.zeros((3, 12), dtype=bool) + conflict[:, :3] = conflict[:, 6:9] = True + targets = { + f"{phase}_{kind}": world.answers.copy() + for phase, world in (("low", low), ("high", high)) + for kind in KINDS + } + new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + for index, group in enumerate(groups): + ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] + if len(eligible) != 8: + raise ValueError("Expected eight still-ordinary people in each QA split") + selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] + actual = low.actual_ids[chain, selected[index]] + derived = low.derived_ids[chain, low.memberships[chain] == group] + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + target[low.root_ids[chain, group]] = new_default[index] + target[derived] = new_default[index] + target[actual] = new_default[index] + if kind == "exception": + target[actual[conflict[index]]] = alternative[index] + edited_people = selected.ravel() + selected_people = np.isin(low.memberships[chain], groups) + original = selected_people & low.exceptions[chain] + newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] + unedited_ordinary = ( + selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) + ) + e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) + d = low.derived_ids[chain, selected_people] + unchanged = np.ones(len(low.answers), dtype=bool) + unchanged[np.concatenate([e, d])] = False + affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] + original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) + newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) + relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(low.answers), -1, dtype=np.int64) + strata[unchanged & original_actual] = 0 + strata[unchanged & newly_actual] = 1 + strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 + strata[unchanged & ~affected_facts & relevant] = 3 + strata[unchanged & ~affected_facts & ~relevant] = 4 + heldout = [] + for stratum in range(5): + ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) + heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) + heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) + heldout = np.array(sorted(heldout), dtype=np.int64) + common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) + common_pool = np.setdiff1d(common_pool, heldout) + if len(common_pool) < 4096: + raise ValueError("Insufficient shared unchanged base facts for R4096") + replay = rng.choice(common_pool, 4096, replace=False) + paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) + pair = { + **targets, + "groups": groups, + "selected_people": selected, + "alternative_assignments": conflict, + "new_default": new_default, + "alternative": alternative, + "E": e, + "D": d, + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, edited_people]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), + "paired_reference_D": paired_reference, + "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "exception_conflict_D": paired_reference.copy(), + "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, original], + "D_newly_exception": low.derived_ids[chain, newly], + "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], + "R": replay, + "U_full": np.flatnonzero(unchanged), + "U_heldout": heldout, + "U_strata": strata, + } + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + actual_for_d = target[low.actual_ids[chain, selected_people]] + pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] + pair["contract"] = { + "protocol": "v2.8-p3-shortcut-matched-E39-prepared", + "world": low.seed, + "chain": chain, + "support": support, + "status": "data_only_not_executed", + "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, + "model_checkpoint": ( + "width256, original 15360-step learning; not P2 30720-step continuation" + ), + "histogram_matching_scope": ( + "all three groups combined; also separately for trained/heldout QA" + ), + "coherent_actuals_per_group": "12 new-default (six in each QA split)", + "exception_actuals_per_group": ( + "6 new-default + 6 alternative (three + three in each QA split)" + ), + "paired_reference_semantics": ( + "same 18 people; conflict only in exception, reference only in coherent" + ), + "R_semantics": ( + "4096 identical query IDs with identical original truths " + "and unchanged under all four targets" + ), + "U_semantics": ( + "common query IDs; score each phase against its own truth and old-correct coverage" + ), + "U_strata": U_STRATA.copy(), + "historical_E93_comparable": False, + "low_truth_sha256": array_hash(low.answers), + "high_truth_sha256": array_hash(high.answers), + "array_sha256": {key: array_hash(value) for key, value in pair.items()}, + } + audit_matched_edit_pair(low, high, chain, pair) + return pair + + +def audit_matched_edit_pair(low, high, chain, pair): + """Verify ID, target, split, marginal, primary-subset, and replay contracts.""" + audit_high_exception(low, high) + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high world identities differ") + e, d, selected, groups = (pair[key] for key in ("E", "D", "selected_people", "groups")) + if len(e) != 39 or len(np.unique(e)) != 39 or len(d) != 96 or len(np.unique(d)) != 96: + raise ValueError("E39/D96 support changed") + if len(groups) != 3 or len(np.unique(low.defaults[chain, groups])) != 3: + raise ValueError("Expected three groups with distinct original defaults") + if selected.shape != (3, 12) or len(np.unique(selected)) != 36: + raise ValueError("Expected twelve distinct people in each selected group") + if high.exceptions[chain, selected].any(): + raise ValueError("Selected edit people must be ordinary in both worlds") + np.testing.assert_array_equal( + pair["new_default"], low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + ) + np.testing.assert_array_equal( + pair["alternative"], low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + ) + np.testing.assert_array_equal( + d, low.derived_ids[chain, np.isin(low.memberships[chain], groups)] + ) + np.testing.assert_array_equal( + e, np.sort(np.r_[low.root_ids[chain, groups], low.actual_ids[chain, selected.ravel()]]) + ) + conflict = pair["alternative_assignments"] + if conflict.shape != (3, 12) or conflict.dtype != np.bool_: + raise ValueError("Invalid alternative assignment mask") + for index, group in enumerate(groups): + if not np.all(low.memberships[chain, selected[index]] == group): + raise ValueError("Selected person belongs to the wrong group") + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + people = selected[index, split * 6 : (split + 1) * 6] + if not np.isin(low.derived_ids[chain, people], pool).all(): + raise ValueError("Selected QA split changed") + if conflict[index, split * 6 : (split + 1) * 6].sum() != 3: + raise ValueError("Each group/split must have three default and three alternative") + root = low.root_ids[chain, group] + derived = low.derived_ids[chain, low.memberships[chain] == group] + actual = low.actual_ids[chain, selected[index]] + for phase in PHASES: + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + if target[root] != pair["new_default"][index] or not np.all( + target[derived] == target[root] + ): + raise ValueError( + "The three root rotations and their full propagation targets must agree" + ) + expected = np.full(12, target[root], dtype=np.int64) + if kind == "exception": + expected[conflict[index]] = pair["alternative"][index] + np.testing.assert_array_equal(target[actual], expected) + changed = np.union1d(e, d) + for phase, world in (("low", low), ("high", high)): + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + np.testing.assert_array_equal(np.flatnonzero(target != world.answers), changed) + for kind in KINDS: + np.testing.assert_array_equal(pair[f"low_{kind}"][changed], pair[f"high_{kind}"][changed]) + for _split, pool in ( + ("all", low.derived_ids[chain]), + ("trained", low.train_ids[chain]), + ("heldout", low.heldout_ids[chain]), + ): + people = selected.ravel()[np.isin(low.derived_ids[chain, selected.ravel()], pool)] + actual = low.actual_ids[chain, people] + np.testing.assert_array_equal( + np.sort(pair["low_coherent"][actual]), np.sort(pair["low_exception"][actual]) + ) + reference = np.sort(low.derived_ids[chain, selected[conflict]]) + np.testing.assert_array_equal(pair["paired_reference_D"], reference) + np.testing.assert_array_equal(pair["exception_conflict_D"], reference) + heldout_reference = np.intersect1d(reference, low.heldout_ids[chain]) + np.testing.assert_array_equal(pair["exception_conflict_D_heldout"], heldout_reference) + np.testing.assert_array_equal(pair["paired_reference_D_heldout"], heldout_reference) + if len(reference) != 18 or len(heldout_reference) != 9: + raise ValueError("Expected eighteen primary exception conflicts, nine heldout") + partition = [ + pair[key] + for key in ( + "D_edited_actual", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + ] + if [len(ids) for ids in partition] != [36, 6, 42, 12]: + raise ValueError("Incorrect fixed propagation strata") + np.testing.assert_array_equal(np.sort(np.concatenate(partition)), d) + affected = np.isin(low.memberships[chain], groups) + expected_subsets = { + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, selected.ravel()]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, selected.ravel()]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, affected & low.exceptions[chain]], + "D_newly_exception": low.derived_ids[ + chain, affected & high.exceptions[chain] & ~low.exceptions[chain] + ], + } + for key, expected in expected_subsets.items(): + np.testing.assert_array_equal(pair[key], expected) + for phase in PHASES: + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + conflicts = d[target[d] != target[low.actual_ids[chain, affected]]] + np.testing.assert_array_equal(pair[f"{phase}_{kind}_factual_conflict_D"], conflicts) + u = np.setdiff1d(np.arange(len(low.answers)), changed) + np.testing.assert_array_equal(pair["U_full"], u) + np.testing.assert_array_equal(pair["U_strata"] >= 0, np.isin(np.arange(len(low.answers)), u)) + replay = pair["R"] + if len(replay) != 4096 or len(np.unique(replay)) != 4096 or np.any(replay >= low.n_base): + raise ValueError("R must contain 4096 unique base-fact IDs") + if not np.isin(replay, u).all() or np.intersect1d(replay, pair["U_heldout"]).size: + raise ValueError("Replay leaks changed support/propagation or heldout retention") + if not np.isin(pair["U_heldout"], u).all(): + raise ValueError("Heldout retention includes changed targets") + np.testing.assert_array_equal(low.answers[replay], high.answers[replay]) + for phase in PHASES: + for kind in KINDS: + np.testing.assert_array_equal(pair[f"{phase}_{kind}"][replay], low.answers[replay]) + for key, value in pair.items(): + if isinstance(value, np.ndarray) and pair["contract"]["array_sha256"][key] != array_hash( + value + ): + raise ValueError(f"Matched update array provenance changed: {key}") + return { + "passed": True, + "E": 39, + "D": 96, + "exception_conflict_D": 18, + "exception_conflict_D_heldout": 9, + "R": 4096, + "budget_edit_cases": 96, + "histograms_match_across_three_groups_and_within_QA_split": True, + } diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_train.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_train.py new file mode 100644 index 0000000000000000000000000000000000000000..958bf5b4de4feec20d76d07a5d28016fec584d7a --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bios_train.py @@ -0,0 +1,353 @@ +"""Reproducible symbolic development trajectories for bioS-Work-v1. + +Every evaluated answer is greedily generated without a correct-answer prefix. +Two generated tokens is the fixed symbolic grammar budget (one value plus EOS). +""" + +import argparse +import hashlib +import json +import os +import platform +import subprocess +import time +from contextlib import nullcontext +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import ( + EOS, + N_BASE, + N_QUERIES, + RELATIONS, + array_hash, + curriculum, + load_world, + write_json, +) +from .bios_model import CausalLM, ModelConfig, matmul_flops + + +def precision(device): + return ( + torch.autocast(device_type="cuda", dtype=torch.bfloat16) + if device.type == "cuda" + else nullcontext() + ) + + +def tensor_data(world, device, answers=None): + answer = torch.as_tensor(world.answers if answers is None else answers, device=device) + prompts = torch.as_tensor(world.prompts, device=device) + lengths = torch.as_tensor(world.lengths, device=device) + tokens = torch.zeros((N_QUERIES, 6), dtype=torch.long, device=device) + tokens[:, :5] = prompts + rows = torch.arange(N_QUERIES, device=device) + tokens[rows, lengths] = answer + tokens[lengths == 4, 5] = EOS + positions = torch.stack([lengths - 1, lengths], dim=1) + labels = torch.stack([answer, torch.full_like(answer, EOS)], dim=1) + return { + "prompts": prompts, + "lengths": lengths, + "tokens": tokens, + "positions": positions, + "labels": labels, + } + + +@torch.no_grad() +def evaluate(model, data, world, batch_size=512, answers=None): + device = data["tokens"].device + targets = world.answers if answers is None else answers + predictions, ended, nll = [], [], [] + model.eval() + for begin in range(0, N_QUERIES, batch_size): + end = min(begin + batch_size, N_QUERIES) + lengths = data["lengths"][begin:end] + rows = torch.arange(end - begin, device=device) + with precision(device): + logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float() + first = logits.argmax(-1) + continuation = torch.zeros((end - begin, 6), dtype=torch.long, device=device) + continuation[:, :5] = data["prompts"][begin:end] + continuation[rows, lengths] = first + second = model(continuation, lengths[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + labels = torch.as_tensor(targets[begin:end], device=device) + nll.append(F.cross_entropy(logits, labels, reduction="none").cpu().numpy()) + predictions, ended, nll = ( + np.concatenate(predictions), + np.concatenate(ended), + np.concatenate(nll), + ) + correct = (predictions == targets) & ended + strata = { + "employer": world.relation == 0, + "company_default": world.relation == 1, + "actual_nonexception": (world.relation == 2) + & ~world.exceptions[np.maximum(world.person, 0)], + "actual_old_exception": (world.relation == 2) + & world.exceptions[np.maximum(world.person, 0)], + "independent_attributes": np.isin(world.relation, [3, 4, 5, 6]), + } + metrics = { + "base_accuracy": float(correct[:N_BASE].mean()), + "derived_accuracy": float(correct[N_BASE:].mean()), + "value_nll": float(nll[:N_BASE].mean()), + "nontermination_rate": float((~ended).mean()), + "strata": {k: float(correct[v].mean()) for k, v in strata.items()}, + "learning_threshold_passed": bool( + correct[:N_BASE].mean() >= 0.99 and correct[N_BASE:].mean() >= 0.99 + ), + } + return metrics, { + "prediction": predictions, + "ended": ended, + "correct": correct, + "value_nll": nll, + } + + +def code_fingerprint(): + root = Path(__file__).resolve().parents[2] + files = sorted((root / "src" / "llm_memory_editability").glob("*.py")) + return { + "git_revision": subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=root, text=True + ).strip(), + "git_dirty": bool( + subprocess.check_output(["git", "status", "--porcelain"], cwd=root, text=True).strip() + ), + "source_sha256": { + str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in files + }, + } + + +def train(args): + device = torch.device(args.device) + torch.set_num_threads(args.threads) + torch.manual_seed(args.seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + world = load_world(args.world) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + resume = torch.load(out / "resume.pt", weights_only=False) if args.resume else None + if resume is None and (out / "config.json").exists(): + raise ValueError("Output already contains a run; use a fresh output directory") + schedule = curriculum(world, args.order, args.steps) + model = CausalLM(ModelConfig(world.vocab_size)).to(device) + data = tensor_data(world, device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + checkpoints = sorted( + {0, *range(660, 5281, 660), *range(7280, args.steps + 1, 2000), args.steps} + ) + config = { + **vars(args), + "model": model.config_dict(), + "protocol": "v2.3", + "phase": "development", + "world_seed": world.seed, + "parameters": sum(p.numel() for p in model.parameters()), + "torch": torch.__version__, + "python": platform.python_version(), + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast, FP32 weights/loss/Adam moments", + "checkpoints": checkpoints, + "schedule_sha256": array_hash(schedule), + "truth_sha256": array_hash(world.answers), + "flops_method": "executed-shape matmul estimate; elementwise and evaluation excluded", + **code_fingerprint(), + } + timeline, anchors = [], {} + counts = np.zeros(N_QUERIES, dtype=np.int64) + weighted_exposure = np.zeros(8) + train_seconds = 0.0 + losses = [] + steps_since_checkpoint = 0 + first_step = 0 + if resume is None: + write_json(out / "config.json", config) + np.save(out / "schedule.npy", schedule) + else: + # Exact continuation from the last predefined checkpoint's full training state. + original = json.loads((out / "config.json").read_text()) + for key in ("schedule_sha256", "truth_sha256", "seed", "order", "steps", "lr"): + if original[key] != config[key]: + raise ValueError(f"Resume mismatch on {key}") + model.load_state_dict(resume["model"]) + optimizer.load_state_dict(resume["optimizer"]) + torch.set_rng_state(resume["torch_rng"]) + if device.type == "cuda" and resume["cuda_rng"] is not None: + torch.cuda.set_rng_state(resume["cuda_rng"], device) + timeline, anchors = resume["timeline"], resume["anchors"] + counts, weighted_exposure = resume["counts"], resume["weighted_exposure"] + train_seconds = resume["train_seconds"] + first_step = resume["step"] + resumes = ( + json.loads((out / "resumes.json").read_text()) + if (out / "resumes.json").exists() + else [] + ) + resumes.append({"from_step": first_step, **code_fingerprint()}) + write_json(out / "resumes.json", resumes) + if device.type == "cuda": + torch.cuda.reset_peak_memory_stats(device) + for step in range(first_step, args.steps + 1): + if step in checkpoints and not (resume is not None and step == first_step): + start_eval = time.perf_counter() + metrics, arrays = evaluate(model, data, world) + for anchor, known in anchors.items(): + metrics[f"forgetting_since_{anchor}"] = ( + float((~arrays["correct"][known]).mean()) if known.any() else None + ) + if step in (2640, 5280): + anchors[step] = arrays["correct"].copy() + np.savez_compressed(out / f"predictions-{step}.npz", **arrays, exposure=counts) + # CPU state for portability; all predefined checkpoints retained. + torch.save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + record = { + "step": step, + **metrics, + "train_seconds": train_seconds, + "train_matmul_flops_estimate": step * matmul_flops(model.config, 128), + "presentations": int(counts.sum()), + "coverage_base": float((counts[:N_BASE] > 0).mean()), + "coverage_derived": float((counts[N_BASE:] > 0).mean()), + "world_tokens": int((counts * (world.lengths + 2)).sum()), + "input_tokens_including_padding": step * 128 * 6, + "supervised_tokens": step * 128 * 2, + "lr_weighted_exposure_by_relation": dict( + zip((*RELATIONS, "derived"), weighted_exposure.tolist(), strict=True) + ), + "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "eval_and_checkpoint_seconds": time.perf_counter() - start_eval, + "mean_training_loss_since_previous": float(np.mean(losses)) if losses else None, + } + timeline.append(record) + write_json(out / "learning.json", timeline) + print( + json.dumps( + { + "event": "checkpoint", + "step": step, + "base": metrics["base_accuracy"], + "derived": metrics["derived_accuracy"], + "train_seconds": train_seconds, + } + ), + flush=True, + ) + losses = [] + steps_since_checkpoint = 0 + state = { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "timeline": timeline, + "anchors": anchors, + "counts": counts, + "weighted_exposure": weighted_exposure, + "train_seconds": train_seconds, + "step": step, + } + torch.save(state, out / "resume.pt.tmp") + os.replace(out / "resume.pt.tmp", out / "resume.pt") + if step == args.steps: + break + model.train() + lr = args.lr * min((step + 1) / 2000, 1.0) + for group in optimizer.param_groups: + group["lr"] = lr + ids_np = schedule[step] + ids = torch.as_tensor(ids_np, device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(data["tokens"][ids], data["positions"][ids]) + loss = F.cross_entropy( + logits.float().reshape(-1, world.vocab_size), data["labels"][ids].reshape(-1) + ) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(loss) or not torch.isfinite(norm): + write_json( + out / "failure.json", + { + "step": step, + "reason": "nonfinite loss or gradient", + "train_seconds": train_seconds, + }, + ) + raise FloatingPointError("Nonfinite loss or gradient") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - started + losses.append(loss.item()) + np.add.at(counts, ids_np, 1) + weighted_exposure += np.bincount(world.relation[ids_np], minlength=8) * lr + steps_since_checkpoint += 1 + if (step + 1) % 100 == 0: + print( + json.dumps( + { + "event": "progress", + "step": step + 1, + "loss": float(np.mean(losses[-100:])), + "train_seconds": train_seconds, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "step": args.steps, + "status": "complete", + "final": timeline[-1], + "exposure_sha256": array_hash(counts), + }, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--order", choices=["SA", "AS"], required=True) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--steps", type=int, default=13280) + parser.add_argument("--lr", type=float, default=1e-4) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--resume", action="store_true") + train(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bridge_reencoding.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bridge_reencoding.py new file mode 100644 index 0000000000000000000000000000000000000000..1dbbe769879cff4d2b00a6c39164102b50d035e3 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bridge_reencoding.py @@ -0,0 +1,438 @@ +"""Fixed-weight, self-decoded bridge re-encoding in existing small GPTs. + +The intervention uses the original tied readout over the complete vocabulary. +Only the explicitly named oracle condition accesses graph answers at inference. +The wrong_entity control is an alternative to the model's decoded token, not a +guaranteed incorrect answer: its accidental agreement with truth is reported. +""" + +from __future__ import annotations + +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import build_world, model_digest +from .representation_alignment import RepresentationGPT, new_model +from .storage_composition import data_digest, evaluate, file_hash, generate_rows +from .text_pretrain import WORDS, composite_sentence + +CONDITIONS = ("baseline", "self_decode", "wrong_entity", "oracle") + + +def reencode_state(state, embedding, alpha, variant="norm_matched"): + """Interpolate residual and normalized embedding, without renormalizing the sum. + + norm_matched gives the replacement embedding the original state's norm. + paper_unit uses a unit embedding directly. Neither preserves the mixture's + norm in general; alpha=0 returns the original tensor exactly. + """ + if not 0 <= alpha <= 1: + raise ValueError("alpha must be between zero and one") + if variant not in ("norm_matched", "paper_unit"): + raise ValueError("Unknown re-encoding variant") + if alpha == 0: + return state + replacement = F.normalize(embedding, dim=-1) + if variant == "norm_matched": + replacement = state.norm(dim=-1, keepdim=True) * replacement + return (1 - alpha) * state + alpha * replacement + + +def alternative_entity(decoded, bridge_start, bridge_count): + """A non-self bridge-entity choice, independent of the true bridge identity.""" + if bridge_count < 2: + raise ValueError("At least two bridge entity tokens are required") + return bridge_start + torch.remainder(decoded - bridge_start + 1, bridge_count) + + +class ReencodingGPT(RepresentationGPT): + """Original computation with a single intervention at block 0, position 3.""" + + def configure(self, condition, alpha, oracle_table=None, variant="norm_matched"): + if condition not in CONDITIONS: + raise ValueError(f"Unknown condition: {condition}") + if not 0 <= alpha <= 1: + raise ValueError("alpha must be between zero and one") + if variant not in ("norm_matched", "paper_unit"): + raise ValueError("Unknown re-encoding variant") + if condition == "oracle" and oracle_table is None: + raise ValueError("Oracle condition requires an explicit diagnostic truth table") + self.condition, self.alpha, self.variant = condition, float(alpha), variant + # Deliberately outside state_dict: neither weights nor model hashes change. + self.oracle_table = oracle_table if condition == "oracle" else None + + def _choice(self, state, tokens): + decoded = F.linear(self.ln_final(state), self.token.weight).argmax(-1) + selected = decoded + oracle_available = torch.zeros_like(decoded, dtype=torch.bool) + if self.condition == "wrong_entity": + selected = alternative_entity(decoded, self.bridge_start, self.bridge_count) + elif self.condition == "oracle": + oracle = self.oracle_table[tokens[:, 1], tokens[:, 3]] + oracle_available = oracle >= 0 + # Invalid autonomously generated heads have no graph truth. Do not + # fabricate an oracle answer; retain the model's decoded token. + selected = torch.where(oracle_available, oracle, decoded) + return decoded, selected, oracle_available + + def forward(self, tokens, positions=None, repeats=None, return_bridge=False): + if not return_bridge and (self.condition == "baseline" or self.alpha == 0): + return super().forward(tokens, positions=positions, repeats=repeats) + if tokens.shape[1] < 4: + raise ValueError("The intervention requires the causal first-relation prefix") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + info = None + for index, block in enumerate(self.iter_blocks(repeats)): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + if index == 0: + state = x[:, 3] + decoded, selected, oracle_available = self._choice(state, tokens) + replacement = ( + state + if self.condition == "baseline" + else reencode_state(state, self.token(selected), self.alpha, self.variant) + ) + if self.condition != "baseline" and self.alpha: + x = x.clone() + x[:, 3] = replacement + info = { + "state": state, + "replacement": replacement, + "decoded": decoded, + "selected": selected, + "oracle_available": oracle_available, + } + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, self.token.weight) + return (logits, info) if return_bridge else logits + + +def _device_settings(device): + device = torch.device(device) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + return device + + +def _load(spec, device): + parent = Path(spec["parent_dir"]).resolve() + checkpoint = parent / "model.pt" + payload = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = new_model(payload["spec"], device) + model.load_state_dict(payload["model"]) + model.__class__ = ReencodingGPT + model.bridge_start = len(WORDS) + payload["spec"]["heads_n"] + model.bridge_count = payload["spec"]["bridges_n"] + model.configure("baseline", 0) + model.eval().requires_grad_(False) + world = dict(np.load(parent / "world.npz")) + rebuilt = build_world(payload["spec"]) + if data_digest(world) != data_digest(rebuilt): + raise AssertionError("Saved world differs from the parent specification") + oracle = torch.full( + (model.config.vocab_size, model.config.vocab_size), -1, device=device, dtype=torch.long + ) + for h, r, target in np.concatenate((world["common_atomic"], world["extra_atomic"])): + oracle[h, r] = int(target) + return model, world, oracle, payload["spec"], checkpoint + + +@torch.no_grad() +def _diagnostics(model, rows, device, batch_size): + prompts = np.asarray([composite_sentence(row)[:7] for row in rows]) + collected = {} + model.eval() + for start in range(0, len(rows), batch_size): + tokens = torch.as_tensor(prompts[start : start + batch_size], device=device) + _, info = model(tokens, return_bridge=True) + values = { + "decoded_bridge": info["decoded"], + "selected_bridge": info["selected"], + "oracle_available": info["oracle_available"], + "state_norm": info["state"].norm(dim=-1), + "replacement_norm": info["replacement"].norm(dim=-1), + } + for key, value in values.items(): + collected.setdefault(key, []).append(value.cpu().numpy()) + result = {key: np.concatenate(value) for key, value in collected.items()} + result["decoded_bridge_correct"] = result["decoded_bridge"] == rows[:, 2] + result["selected_bridge_correct"] = result["selected_bridge"] == rows[:, 2] + result["decoded_is_entity"] = result["decoded_bridge"] >= len(WORDS) + return result + + +def _subset_metric(correct, mask): + return { + "n": int(mask.sum()), + "coverage": float(mask.mean()), + "accuracy": float(correct[mask].mean()) if mask.any() else None, + } + + +@torch.no_grad() +def _evaluate_condition(model, world, device, batch_size): + # Reuse the established complete answer/period/EOS scorer unchanged. Its + # canonical batch is 512; diagnostics use the same shapes for exact decoding. + if batch_size != 512: + raise ValueError("Use batch_size=512 to preserve established evaluation arithmetic") + metrics, predictions = evaluate(model, world, "low", device) + model.eval() + for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): + generated = predictions[name + "_generated"] + metrics[name]["period_accuracy"] = float((generated[:, 1] == 5).mean()) + metrics[name]["eos_accuracy"] = float((generated[:, 2] == 1).mean()) + metrics[name]["format_accuracy"] = float( + ((generated[:, 1] == 5) & (generated[:, 2] == 1)).mean() + ) + for name in ("familiar_test", "strict_test"): + rows = world[name] + info = _diagnostics(model, rows, device, batch_size) + predictions.update({name + "_" + key: value for key, value in info.items()}) + for key in ("decoded_bridge_correct", "selected_bridge_correct", "decoded_is_entity"): + metrics[name][key + "_coverage"] = float(info[key].mean()) + if model.condition == "wrong_entity": + metrics[name]["alternative_accidental_gold_match"] = float( + info["selected_bridge_correct"].mean() + ) + correct = predictions[name + "_correct"] + metrics[name]["self_bridge_correct_subset"] = _subset_metric( + correct, info["decoded_bridge_correct"] + ) + first = rows[:, [0, 1, 2]] + second = rows[:, [2, 3, 4]] + for role, atoms in (("first", first), ("second", second)): + _, raw = generate_rows(model, atoms, device, batch_size=batch_size) + predictions.update({f"{name}_{role}_{key}": value for key, value in raw.items()}) + autonomous_second = second.copy() + autonomous_second[:, 0] = predictions[name + "_first_generated"][:, 0] + _, raw = generate_rows(model, autonomous_second, device, batch_size=batch_size) + predictions.update({f"{name}_autonomous_{key}": value for key, value in raw.items()}) + return metrics, predictions + + +def cases(spec): + """One baseline and the frozen alpha/variant/condition matrix.""" + conditions = list(spec.get("conditions", CONDITIONS)) + if len(conditions) != len(set(conditions)) or any(c not in CONDITIONS for c in conditions): + raise ValueError("Conditions must be distinct known names") + alphas = spec.get("alphas", [spec.get("alpha", 0)]) + variants = spec.get("variants", ["norm_matched"]) + if len(alphas) != len(set(alphas)) or not alphas or any(not 0 <= a <= 1 for a in alphas): + raise ValueError("alphas must contain distinct values in [0,1]") + if len(variants) != len(set(variants)) or not variants: + raise ValueError("variants must be distinct and nonempty") + if any(v not in ("norm_matched", "paper_unit") for v in variants): + raise ValueError("Unknown re-encoding variant") + matrix = {"baseline": {"condition": "baseline", "alpha": 0, "variant": "norm_matched"}} + for variant in variants: + for alpha in alphas: + for condition in conditions: + if condition == "baseline": + continue + name = f"{variant}-a{float(alpha):g}-{condition}" + matrix[name] = {"condition": condition, "alpha": float(alpha), "variant": variant} + return matrix + + +def _evaluate_all(model, world, oracle, spec, callback=None): + matrix = cases(spec) + metrics, arrays = {}, {} + for name, case in matrix.items(): + model.configure( + case["condition"], + case["alpha"], + oracle if case["condition"] == "oracle" else None, + case["variant"], + ) + metrics[name], predictions = _evaluate_condition( + model, world, next(model.parameters()).device, spec.get("batch_size", 512) + ) + arrays.update({name + "__" + key: value for key, value in predictions.items()}) + if callback is not None: + callback(name, case, metrics[name], predictions) + for name in ("familiar_test", "strict_test"): + baseline = arrays[f"baseline__{name}_coverage"] + # This is the fixed pre-intervention prerequisite pool for every case. + # In particular, the destructive alternative-entity control cannot + # determine which chains enter the main conditional comparison. + arrays[f"common__{name}_atomic_correct"] = baseline + for condition in matrix: + correct = arrays[f"{condition}__{name}_correct"] + arrays[f"{condition}__{name}_baseline_common_atoms"] = baseline + metrics[condition][name]["fixed_baseline_atoms_subset"] = _subset_metric( + correct, baseline + ) + self_ok = arrays[f"{condition}__{name}_decoded_bridge_correct"] + joint = baseline & self_ok + arrays[f"{condition}__{name}_common_atoms_and_self_bridge"] = joint + metrics[condition][name]["common_atoms_and_self_bridge_subset"] = _subset_metric( + correct, joint + ) + model.configure("baseline", 0) + return metrics, arrays + + +def run(spec, out, device="cuda:2"): + """Evaluate one existing checkpoint; never train or overwrite an attempt.""" + out = Path(out) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + out.mkdir(parents=True, exist_ok=True) + device = _device_settings(device) + started = time.perf_counter() + model, world, oracle, parent_spec, checkpoint = _load(spec, device) + digest = model_digest(model) + source = { + str(Path(__file__).resolve()): file_hash(__file__), + "parent_checkpoint": file_hash(checkpoint), + } + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "source": source, + "world_sha256": data_digest(world), + "model_sha256": digest, + "pid": os.getpid(), + "device": str(device), + "started_utc": utc(), + "new_training_updates": 0, + "optimizer_updates": 0, + "cases": cases(spec), + "formula_norm_matched": "(1-alpha)*h + alpha*||h||*normalize(E_decoded)", + "formula_paper_unit": "(1-alpha)*h + alpha*normalize(E_decoded)", + "decoder": "original ln_final and tied output, argmax over the full vocabulary", + "wrong_entity_scope": "non-self bridge entity, independent of gold; may equal true bridge", + "bridge_token_start": model.bridge_start, + "bridge_token_count": model.bridge_count, + "main_prerequisite_subset": "both necessary atoms correct under the fixed baseline", + "alpha_zero_exact_bypass": True, + "allow_tf32": True, + } + write_json(out / "run.json", manifest) + np.savez_compressed(out / "world.npz", **world) + history = [] + + def record(name, case, metrics, predictions): + history.append( + { + "step": len(history) + 1, + "case": name, + **case, + "metrics": metrics, + "optimizer_updates": 0, + "wall_seconds": time.perf_counter() - started, + "created_utc": utc(), + } + ) + # Each condition is durable before the next one starts. + np.savez_compressed(out / f"predictions-{name}.npz", **predictions) + write_json(out / "learning.json", history) + write_json( + out / "status.json", + { + "state": "running", + "step": len(history), + "budget": len(manifest["cases"]), + "optimizer_updates": 0, + }, + ) + + metrics, predictions = _evaluate_all(model, world, oracle, spec, record) + assert model_digest(model) == digest, "Evaluation changed model parameters" + # Final common-prerequisite subsets are known only after the full matrix. + write_json(out / "learning.json", history) + # At zero weight all conditions must recover complete baseline generation. + for key, value in predictions.items(): + if key.endswith(("_generated", "_answer_nll")): + case, suffix = key.split("__", 1) + if manifest["cases"][case]["alpha"] == 0: + np.testing.assert_array_equal(value, predictions["baseline__" + suffix]) + np.savez_compressed(out / "predictions.npz", **predictions) + write_json(out / "metrics.json", metrics) + result = { + "state": "evaluation-complete-awaiting-independent-audit", + "finished_utc": utc(), + "wall_seconds": time.perf_counter() - started, + "model_sha256": digest, + "new_training_updates": 0, + "optimizer_updates": 0, + "conditions": list(metrics), + "prediction_arrays": len(predictions), + "step": len(history), + } + write_json(out / "evaluation-complete.json", result) + write_json(out / "status.json", {**result, "step": len(history)}) + return result + + +def audit(out, device="cuda:2"): + """Reload weights and independently recompute every saved prediction array.""" + out = Path(out) + device = _device_settings(device) + manifest = json.loads((out / "run.json").read_text()) + model, world, oracle, _, checkpoint = _load(manifest["spec"], device) + assert file_hash(checkpoint) == manifest["source"]["parent_checkpoint"] + assert model_digest(model) == manifest["model_sha256"] + assert data_digest(world) == manifest["world_sha256"] + metrics, actual = _evaluate_all(model, world, oracle, manifest["spec"]) + saved = dict(np.load(out / "predictions.npz")) + assert set(saved) == set(actual), "Prediction array set changed" + max_error = 0.0 + for key, value in actual.items(): + if value.dtype.kind == "f": + max_error = max(max_error, float(np.max(np.abs(value - saved[key])))) + np.testing.assert_allclose(value, saved[key], atol=1e-5, rtol=1e-5) + else: + np.testing.assert_array_equal(value, saved[key]) + # Recount complete-answer accuracy independently of the established scorer. + for condition, groups in metrics.items(): + for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): + pred = actual[f"{condition}__{name}_generated"] + correct = (pred[:, 0] == world[name][:, -1]) & (pred[:, 1] == 5) & (pred[:, 2] == 1) + np.testing.assert_array_equal(correct, actual[f"{condition}__{name}_correct"]) + assert float(correct.mean()) == groups[name]["accuracy"] + assert model_digest(model) == manifest["model_sha256"] + result = { + "passed": True, + "independently_reloaded": True, + "raw_predictions_recounted": True, + "prediction_arrays": len(actual), + "max_float_error": max_error, + "audit_pid": os.getpid(), + "independent_process": os.getpid() != manifest["pid"], + "finished_utc": utc(), + "metrics": metrics, + } + write_json(out / "audit.json", result) + complete = json.loads((out / "evaluation-complete.json").read_text()) + complete.update(state="complete", independently_reloaded=True, audit_finished_utc=utc()) + write_json(out / "complete.json", complete) + write_json(out / "status.json", {**complete, "step": len(metrics), "optimizer_updates": 0}) + return result diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bridge_workspace.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bridge_workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3ee68821631607b4922cfce3654cd2784d82ba --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/bridge_workspace.py @@ -0,0 +1,1112 @@ +"""Causal entity-coordinate interventions using an averaged prefix Jacobian. + +This is a restricted adaptation of Anthropic's Jacobian lens: calibration and +donors contain only the first fact's query prefix. No relation suffix or answer +gradient is used to construct a direction. Execution layers count shared block +occurrences separately. All model parameters remain frozen. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import time +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import file_hash + +SWAPS = ("swap", "swap_x2", "random_swap", "full_prefix", "swap_back") +ERASURES = ( + "erase_state", + "erase_mlp", + "erase_attention", + "random_state", + "random_mlp", + "random_attention", + "restore_mlp", + "fixed_entity_mlp", + "fixed_entity_random_mlp", +) + + +class ModelView: + """Expose native attention/MLP increments without replacing trained modules.""" + + def __init__(self, model): + if model.training: + raise ValueError("Interventions require eval mode") + self.model = model + self.large = hasattr(model, "transformer") + if self.large: + t = model.transformer + self.embedding, self.position, self.norm = t.wte, t.wpe, t.ln_f + self.blocks = list(t.h) * model.repeats + self.heads = model.config.n_head + else: + self.embedding, self.position, self.norm = model.token, model.position, model.ln_final + self.blocks = list(model.iter_blocks()) + self.heads = model.config.heads + self.width = self.embedding.weight.shape[1] + self.device = self.embedding.weight.device + + def embed(self, tokens): + return self.embedding(tokens) + self.position( + torch.arange(tokens.shape[1], device=self.device) + ) + + def parts(self, x, block, *, math_attention=False): + if self.large: + z = block.ln_1(x) + q, k, v = block.attn.c_attn(z).split(self.width, dim=-1) + project, ln2 = block.attn.c_proj, block.ln_2 + else: + z = block.ln1(x) + q, k, v = block.attention.qkv(z).chunk(3, dim=-1) + project, ln2 = block.attention.proj, block.ln2 + shape = (len(x), x.shape[1], self.heads, self.width // self.heads) + q, k, v = (a.reshape(shape).transpose(1, 2) for a in (q, k, v)) + if math_attention: + # The explicit FP32 expression permits batched VJPs on torch 2.6. + scores = q @ k.transpose(-1, -2) / (self.width // self.heads) ** 0.5 + mask = torch.ones(x.shape[1], x.shape[1], device=self.device, dtype=torch.bool).tril() + y = scores.masked_fill(~mask, -torch.inf).softmax(-1) @ v + else: + y = F.scaled_dot_product_attention(q, k, v, is_causal=True) + attention = project(y.transpose(1, 2).reshape(len(x), x.shape[1], self.width)) + after_attention = x + attention + mlp = block.mlp(ln2(after_attention)) + return after_attention + mlp, attention, mlp + + def hidden( + self, tokens, *, layer=None, sender=None, delta=None, capture=False, math_attention=False + ): + x, states, attentions, mlps = self.embed(tokens), [], [], [] + for index, block in enumerate(self.blocks): + x, attention, mlp = self.parts(x, block, math_attention=math_attention) + if capture: + states.append(x[:, sender].detach()) + attentions.append(attention[:, sender].detach()) + mlps.append(mlp[:, sender].detach()) + if index == layer: + if sender is None or delta is None or delta.shape != x[:, sender].shape: + raise ValueError("A patch requires one delta per example at a fixed sender") + mask = F.one_hot(torch.tensor(sender, device=self.device), x.shape[1]).to(x.dtype) + x = x + mask[None, :, None] * delta[:, None, :] + if capture: + return x, tuple(torch.stack(a) for a in (states, attentions, mlps)) + return x + + def logits(self, tokens, **patch): + return F.linear(self.norm(self.hidden(tokens, **patch)[:, -1]), self.embedding.weight) + + +def average_prefix_jacobian(view, prefixes, sender, *, chunk=32): + """E[d h_final,sender / d h_layer,sender], with labels absent from the graph. + + A shared shift applied to all independent calibration prompts differentiates + their mean output, exactly averaging their Jacobians. Parameters need no + gradients. The endpoint is the residual before the final LayerNorm. + """ + if any(p.requires_grad for p in view.model.parameters()): + raise ValueError("Freeze model parameters before constructing the lens") + with torch.no_grad(): + x, boundaries = view.embed(prefixes), [] + for block in view.blocks: + x, _, _ = view.parts(x, block, math_attention=True) + boundaries.append(x.detach()) + jacobians = [] + identity = torch.eye(view.width, device=view.device) + for layer, boundary in enumerate(boundaries): + shift = torch.zeros(view.width, device=view.device, requires_grad=True) + mask = F.one_hot(torch.tensor(sender, device=view.device), prefixes.shape[1]).float() + x = boundary + mask[None, :, None] * shift[None, None, :] + for block in view.blocks[layer + 1 :]: + x, _, _ = view.parts(x, block, math_attention=True) + endpoint = x[:, sender].mean(0) + rows = [] + for start in range(0, view.width, chunk): + rows.append( + torch.autograd.grad( + endpoint, + shift, + grad_outputs=identity[start : start + chunk], + is_grads_batched=True, + retain_graph=start + chunk < view.width, + )[0].detach() + ) + jacobians.append(torch.cat(rows)) + return torch.stack(jacobians) + + +def swap_coordinates(state, basis): + """Swap two coefficients in a nonorthogonal frame, preserving its complement.""" + if basis.shape != (*state.shape, 2): + raise ValueError("Expected [example, width, two semantic axes]") + coefficients = (torch.linalg.pinv(basis.double()) @ state.double()[..., None]).squeeze(-1) + difference = coefficients.flip(-1) - coefficients + return state + (basis.double() @ difference[..., None]).squeeze(-1).to(state.dtype) + + +def projection(state, direction): + direction = F.normalize(direction, dim=-1) + return (state * direction).sum(-1, keepdim=True) * direction + + +def match_norm(delta, reference): + norm = delta.norm(dim=-1, keepdim=True) + if bool(((norm < 1e-12) & (reference.norm(dim=-1, keepdim=True) > 1e-6)).any()): + raise ValueError("Degenerate random control") + return delta * reference.norm(dim=-1, keepdim=True) / norm.clamp_min(1e-12) + + +def control_observation(changed, baseline): + """Record numerical control outcomes without silently dropping sensitive cases.""" + mask = np.any(changed != baseline, axis=1) + return { + "n_queries": len(baseline), + "generated_rows_changed": int(mask.sum()), + "answer_rows_changed": int((changed[:, 0] != baseline[:, 0]).sum()), + "changed_query_indices": np.flatnonzero(mask).tolist(), + "changed_fraction": float(mask.mean()), + "exact": bool(not mask.any()), + } + + +def _rank(seed, *values): + return hashlib.sha256(json.dumps([seed, *map(int, values)]).encode()).digest() + + +def select_pairs(atoms, first_families, seed, per_family, *, ood=None): + """Choose prefixes/donors and all shared continuations using graph truth only. + + Donors use the same r1 and first-fact family. Every pair has at least two + distinct shared r2 with different original/counterfactual tails. A pair is + selected before scoring; its exact same prefix intervention serves every r2. + """ + atoms = np.asarray(atoms, dtype=np.int64) + outgoing, relation = defaultdict(dict), defaultdict(list) + for index, (head, r, tail) in enumerate(atoms): + if int(r) in outgoing[int(head)]: + raise ValueError("Ambiguous atomic truth") + outgoing[int(head)][int(r)] = (int(tail), index) + relation[int(r)].append(index) + groups, queries, coverage = [], [], {} + for name, indices in first_families.items(): + allowed = set(map(int, indices)) + eligible = [] + for first in sorted(allowed): + head, r1, bridge = map(int, atoms[first]) + candidates = [] + for donor in relation[r1]: + dh, _, db = map(int, atoms[donor]) + if donor not in allowed or dh == head or db == bridge: + continue + common = sorted(set(outgoing[bridge]) & set(outgoing[db])) + common = [ + r + for r in common + if outgoing[bridge][r][0] != outgoing[db][r][0] + and not {outgoing[bridge][r][0], outgoing[db][r][0]} & {head, dh, bridge, db} + ] + if len(common) >= 2: + candidates.append((donor, common)) + if candidates: + donor, common = min(candidates, key=lambda v: _rank(seed, first, v[0])) + eligible.append((first, donor, common)) + eligible.sort(key=lambda v: _rank(seed, v[0])) + coverage[name] = {"candidate_first_facts": len(allowed), "eligible": len(eligible)} + for first, donor, common in eligible[:per_family]: + head, r1, bridge = map(int, atoms[first]) + dh, _, db = map(int, atoms[donor]) + group = len(groups) + groups.append([head, r1, bridge, dh, db, first, donor]) + for r2 in common: + tail, second = outgoing[bridge][r2] + ct, cf_second = outgoing[db][r2] + kind = ( + name + if ood is None + else ("ood" if ood[first] else "id") + ("_ood" if ood[second] else "_id") + ) + queries.append((group, r2, tail, ct, second, cf_second, kind)) + coverage[name]["selected"] = min(len(eligible), per_family) + if not groups: + raise ValueError("No graph-eligible cross-relation pairs; do not reroll") + return { + "groups": np.asarray(groups, dtype=np.int64), + "queries": np.asarray([r[:6] for r in queries], dtype=np.int64), + "strata": np.asarray([r[6] for r in queries]), + "counterfactual_strata": np.asarray( + [ + r[6] + if ood is None + else ("ood" if ood[groups[r[0]][6]] else "id") + ("_ood" if ood[r[5]] else "_id") + for r in queries + ] + ), + "coverage": coverage, + } + + +def prefixes(facts, large, metadata): + facts = np.asarray(facts) + if large: + return np.column_stack( + (facts[:, 0] + metadata["entity_offset"], facts[:, 1] + metadata["relation_offset"]) + ) + return np.column_stack( + (np.full(len(facts), 2), facts[:, 0], np.full(len(facts), 3), facts[:, 1]) + ) + + +def prompts(rows, large, metadata): + if large: + from .grokking_reproduction import encode_rows + + return encode_rows(rows, metadata)[0][:, : rows.shape[1] - 1] + from .text_pretrain import atomic_sentence, composite_sentence + + render = atomic_sentence if rows.shape[1] == 3 else composite_sentence + length = 5 if rows.shape[1] == 3 else 7 + return np.asarray([render(row)[:length] for row in rows]) + + +def query_training_masks(world, payload, groups, queries, large): + """Count composition exposure without using scores or answer correctness.""" + if large: + support = round(payload["spec"]["phi"] * (~world["ood"]).sum()) + trained = world["chains"][world["train_order"][:support]][:, :3] + else: + trained = world["train_composite"][:, [0, 1, 3]] + trained = set(map(tuple, trained)) + recipient = np.asarray([(groups[g, 0], groups[g, 1], r2) in trained for g, r2, *_ in queries]) + donor = np.asarray([(groups[g, 3], groups[g, 1], r2) in trained for g, r2, *_ in queries]) + return { + "recipient_query_trained": recipient, + "counterfactual_query_trained": donor, + "both_queries_untrained": ~recipient & ~donor, + } + + +def load_task(spec, device): + payload = torch.load(spec["checkpoint"], map_location="cpu", weights_only=False) + if "checkpoint_step" in spec: + saved_step = payload.get("step", payload["spec"].get("steps")) + assert saved_step == spec["checkpoint_step"], "Wrong checkpoint training step" + if spec["family"] == "reproduction": + from .grokking_reproduction import construct + + data = Path(spec["data"]) + metadata = json.loads((data / "complete.json").read_text()) + model = construct(payload["spec"], metadata, device) + world = dict(np.load(data / "world.npz")) + panels = dict(np.load(data / "panels.npz")) + atoms = world["atoms"].astype(np.int64) + families = {"id": np.flatnonzero(~world["ood"]), "ood": np.flatnonzero(world["ood"])} + ood = world["ood"] + entities = np.arange( + metadata["entity_offset"], metadata["entity_offset"] + metadata["entities"] + ) + else: + from .representation_alignment import new_model + + model = new_model(payload["spec"], device) + world = dict(np.load(Path(spec["checkpoint"]).parent / "world.npz")) + metadata = {"entity_offset": 0} + atoms = np.concatenate((world["common_atomic"], world["anchor_atomic"])) + families = {} + for name in ("familiar_test", "strict_test"): + firsts = set(map(tuple, world[name][:, :3])) + families[name] = np.asarray([i for i, a in enumerate(atoms) if tuple(a) in firsts]) + ood = None + entities = np.arange(21, model.config.vocab_size) + panels = {k: world[k] for k in ("familiar_test", "strict_test")} + model.load_state_dict(payload["model"]) + model.eval().requires_grad_(False) + return ModelView(model), payload, metadata, world, atoms, families, ood, entities, panels + + +@torch.no_grad() +def trace_in_batches(view, tokens, sender, batch_size, amp): + collected = [] + for start in range(0, len(tokens), batch_size): + batch = torch.as_tensor(tokens[start : start + batch_size], device=view.device) + with torch.autocast("cuda", dtype=torch.bfloat16, enabled=amp): + _, trace = view.hidden(batch, sender=sender, capture=True) + collected.append(tuple(a.float() for a in trace)) + return tuple(torch.cat([a[j] for a in collected], dim=1) for j in range(3)) + + +@torch.no_grad() +def generate( + view, + tokens, + targets, + counterfactual, + metadata, + batch_size, + *, + layer=None, + sender=None, + delta=None, +): + """Greedy generation with feedback; scoring retains both target probabilities.""" + offset = metadata["entity_offset"] + targets, counterfactual = targets + offset, counterfactual + offset + generated, original_logp, cf_logp, top_ids, top_scores = [], [], [], [], [] + for start in range(0, len(tokens), batch_size): + x = torch.as_tensor(tokens[start : start + batch_size], device=view.device) + patch = ( + {} + if layer is None + else {"layer": layer, "sender": sender, "delta": delta[start : start + batch_size]} + ) + draws = [] + for index in range(2 if view.large else 3): + with torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): + logits = view.logits(x, **patch).float() + if index == 0: + logs = logits.log_softmax(-1) + arange = torch.arange(len(x), device=view.device) + original_logp.append( + logs[ + arange, + torch.as_tensor(targets[start : start + batch_size], device=view.device), + ] + .cpu() + .numpy() + ) + cf_logp.append( + logs[ + arange, + torch.as_tensor( + counterfactual[start : start + batch_size], device=view.device + ), + ] + .cpu() + .numpy() + ) + scores, ids = logs.topk(min(10, logs.shape[-1]), dim=-1) + top_ids.append(ids.cpu().numpy()) + top_scores.append(scores.cpu().numpy()) + answer = logits.argmax(-1) + draws.append(answer.cpu().numpy()) + x = torch.cat((x, answer[:, None]), dim=1) + generated.append(np.stack(draws, axis=1)) + return { + "generated": np.concatenate(generated), + "original_logp": np.concatenate(original_logp), + "cf_logp": np.concatenate(cf_logp), + "top_ids": np.concatenate(top_ids), + "top_logp": np.concatenate(top_scores), + } + + +def summarize(result, targets, counterfactual, metadata, strata, groups=None): + generated = result["generated"] + original = generated[:, 0] == targets + metadata["entity_offset"] + cf = generated[:, 0] == counterfactual + metadata["entity_offset"] + format_ok = ( + generated[:, 1] == metadata["end_marker"] + if "end_marker" in metadata + else (generated[:, 1] == 5) & (generated[:, 2] == 1) + ) + output = {} + for name in ("all", *sorted(set(strata))): + mask = np.ones(len(strata), dtype=bool) if name == "all" else strata == name + row = { + "n_queries": int(mask.sum()), + "answer_accuracy": float(original[mask].mean()), + "accuracy": float((original & format_ok)[mask].mean()), + "cf_answer_accuracy": float(cf[mask].mean()), + "cf_accuracy": float((cf & format_ok)[mask].mean()), + "format_accuracy": float(format_ok[mask].mean()), + "answer_nll": float(-result["original_logp"][mask].mean()), + "cf_nll": float(-result["cf_logp"][mask].mean()), + } + if groups is not None: + unique = np.unique(groups[mask]) + row["n_first_facts"] = len(unique) + row["all_relations_cf_accuracy"] = float( + np.mean([cf[mask & (groups == g)].all() for g in unique]) + ) + row["mean_first_fact_cf_accuracy"] = float( + np.mean([cf[mask & (groups == g)].mean() for g in unique]) + ) + output[name] = row + return output + + +def run(spec, settings, out, gpu): + """Run one checkpoint with all execution layers, including failed interventions.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device(f"cuda:{gpu}") + began = time.perf_counter() + view, payload, metadata, world, atoms, families, ood, entities, panels = load_task(spec, device) + digest_before = model_digest(view.model) + write_json( + out / "run.json", + { + "spec": { + **spec, + "settings": settings, + "checkpoint_step": payload.get("step", payload["spec"].get("steps")), + }, + "checkpoint_sha256": file_hash(spec["checkpoint"]), + "initial_model_sha256": digest_before, + "world_sha256": file_hash(Path(spec["data"]) / "world.npz") + if view.large + else file_hash(Path(spec["checkpoint"]).parent / "world.npz"), + "job_type": "causal-intervention", + "pid": os.getpid(), + "gpu": gpu, + "gpu_name": torch.cuda.get_device_name(gpu), + "dtype": "BF16 native / FP32 Jacobian" if view.large else "FP32", + "parameters": sum(p.numel() for p in view.model.parameters()), + "vocab_size": len(view.embedding.weight), + "tags": ["bridge-workspace", spec["phase"], "no-training"], + "created_utc": utc(), + }, + ) + history, cursor = [], 0 + + def log(stage, metrics): + nonlocal cursor + history.append( + { + "step": cursor, + "metrics": metrics, + "wall_seconds": time.perf_counter() - began, + "checkpoint_training_step": payload.get("step", payload["spec"].get("steps", 0)), + } + ) + write_json(out / "learning.json", history) + write_json(out / "status.json", {"state": "running", "stage": stage, "step": cursor}) + print( + json.dumps( + { + "run": spec["name"], + "stage": stage, + "index": cursor, + "wall_seconds": history[-1]["wall_seconds"], + } + ), + flush=True, + ) + cursor += 1 + + log("loaded", {}) + pairs = select_pairs( + atoms, families, settings["selection_seed"], settings["prefixes_per_family"], ood=ood + ) + groups, q = pairs["groups"], pairs["queries"] + used_first = set(groups[:, 5]) | set(groups[:, 6]) + calibration = np.asarray([i for i in range(len(atoms)) if i not in used_first]) + calibration = sorted(calibration, key=lambda i: _rank(settings["calibration_seed"], i))[ + : settings["calibration_prompts"] + ] + sender = 1 if view.large else 3 + cp = prefixes(atoms[calibration], view.large, metadata) + tensors = torch.as_tensor(cp, device=device) + jacobians = average_prefix_jacobian(view, tensors, sender, chunk=settings["jacobian_chunk"]) + torch.save( + {"jacobians": jacobians.cpu(), "calibration_atomic_indices": calibration, "prefixes": cp}, + out / "lens.pt", + ) + log("jacobian_lens", {"calibration_prompts": len(cp), "executed_layers": len(view.blocks)}) + trace = trace_in_batches( + view, + prefixes(groups[:, :3], view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + donor_facts = np.column_stack((groups[:, 3], groups[:, 1], groups[:, 4])) + donor_states = trace_in_batches( + view, + prefixes(donor_facts, view.large, metadata), + sender, + settings["batch_size"], + view.large, + )[0] + rows = ( + np.column_stack((groups[q[:, 0], 0], groups[q[:, 0], 1], q[:, 1], q[:, 2])) + if view.large + else np.column_stack( + (groups[q[:, 0], 0], groups[q[:, 0], 1], groups[q[:, 0], 2], q[:, 1], q[:, 2]) + ) + ) + tokens = prompts(rows, view.large, metadata) + training_masks = query_training_masks(world, payload, groups, q, view.large) + # Fix a native panel per stratum without consulting any predictions. + native_rows, native_strata = [], [] + for name in ( + ("test_ii", "test_io", "test_oi", "test_oo") + if view.large + else ("familiar_test", "strict_test") + ): + selected = panels[name][: settings["native_per_stratum"]] + native_rows.append(selected) + native_strata.extend([name] * len(selected)) + native_rows, native_strata = np.concatenate(native_rows), np.asarray(native_strata) + lookup = {(int(h), int(r)): (int(t), i) for i, (h, r, t) in enumerate(atoms)} + native_facts = np.asarray([(h, r, lookup[int(h), int(r)][0]) for h, r in native_rows[:, :2]]) + unique_bridges, bridge_counts = np.unique(native_facts[:, 2], return_counts=True) + fixed_entity = int(unique_bridges[bridge_counts.argmax()]) + fixed_target = native_facts[:, 2] == fixed_entity + ntokens = prompts(native_rows, view.large, metadata) + ntrace = trace_in_batches( + view, + prefixes(native_facts, view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + all_needed = set(groups[:, 5]) | set(groups[:, 6]) | set(q[:, 4]) | set(q[:, 5]) + for row, fact in zip(native_rows, native_facts, strict=True): + r2 = row[2] if view.large else row[3] + all_needed.add(lookup[int(fact[0]), int(fact[1])][1]) + all_needed.add(lookup[int(fact[2]), int(r2)][1]) + needed_ids = np.asarray(sorted(all_needed)) + needed = atoms[needed_ids] + atrace = trace_in_batches( + view, prefixes(needed, view.large, metadata), sender, settings["batch_size"], view.large + ) + torch.save( + { + "recipient": tuple(a.cpu() for a in trace), + "donor_states": donor_states.cpu(), + "native": tuple(a.cpu() for a in ntrace), + "atomic": tuple(a.cpu() for a in atrace), + }, + out / "prefix-traces.pt", + ) + atomic = generate( + view, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + metadata, + settings["batch_size"], + ) + atomic_ok = atomic["generated"][:, 0] == needed[:, -1] + metadata["entity_offset"] + atomic_correct = dict(zip(needed_ids, atomic_ok, strict=True)) + prereq = np.asarray( + [ + all(atomic_correct[int(i)] for i in (groups[g, 5], groups[g, 6], second, cf_second)) + for g, _, _, _, second, cf_second in q + ] + ) + np.savez_compressed( + out / "selection.npz", + **{k: v for k, v in pairs.items() if k != "coverage"}, + rows=rows, + native_rows=native_rows, + native_strata=native_strata, + fixed_entity=np.asarray(fixed_entity), + fixed_entity_target=fixed_target, + **training_masks, + prerequisite_correct=prereq, + needed_atomic_indices=needed_ids, + **{"atomic_" + k: v for k, v in atomic.items()}, + ) + write_json(out / "coverage.json", pairs["coverage"]) + # Independent native implementation equivalence and prefix-causality audit. + audit_tokens = torch.as_tensor(tokens[: min(8, len(tokens))], device=device) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): + native = view.model( + audit_tokens, + positions=torch.full((len(audit_tokens), 1), audit_tokens.shape[1] - 1, device=device), + )[:, 0].float() + traced = view.logits(audit_tokens).float() + _, full_trace = view.hidden(audit_tokens, sender=sender, capture=True) + causal_error = float( + (full_trace[0].float() - trace[0][:, q[: len(audit_tokens), 0]]).abs().max() + ) + torch.testing.assert_close( + full_trace[0].float(), + trace[0][:, q[: len(audit_tokens), 0]], + atol=0.05 if view.large else 2e-5, + rtol=0.005 if view.large else 2e-5, + ) + torch.testing.assert_close( + native, traced, atol=0.05 if view.large else 1e-5, rtol=0.005 if view.large else 1e-5 + ) + if not torch.equal(native.argmax(-1), traced.argmax(-1)): + raise AssertionError("Native/traced greedy answers differ") + summary = {} + + def measure( + family, + condition, + layer, + input_tokens, + target, + cf_target, + strata, + delta=None, + query_groups=None, + ): + result = generate( + view, + input_tokens, + target, + cf_target, + metadata, + settings["batch_size"], + layer=layer if delta is not None else None, + sender=sender, + delta=delta, + ) + np.savez_compressed(out / f"{family}-{condition}-l{layer:02d}.npz", **result) + metrics = summarize(result, target, cf_target, metadata, strata, query_groups) + if family == "swap" and prereq.any(): + metrics["prerequisites_correct"] = summarize( + {k: a[prereq] for k, a in result.items()}, + target[prereq], + cf_target[prereq], + metadata, + strata[prereq], + query_groups[prereq], + )["all"] + if family == "swap" and training_masks["both_queries_untrained"].any(): + mask = training_masks["both_queries_untrained"] + metrics["both_queries_untrained"] = summarize( + {k: a[mask] for k, a in result.items()}, + target[mask], + cf_target[mask], + metadata, + strata[mask], + query_groups[mask], + )["all"] + if family == "native" and (condition.startswith("fixed_entity") or condition == "baseline"): + for label, mask in ( + ("fixed_entity_target", fixed_target), + ("fixed_entity_unrelated", ~fixed_target), + ): + if mask.any(): + metrics[label] = summarize( + {k: a[mask] for k, a in result.items()}, + target[mask], + cf_target[mask], + metadata, + strata[mask], + )["all"] + summary[f"{family}/{condition}/{layer}"] = metrics + write_json(out / "summary.json", summary) + log(f"{family}-{condition}-l{layer}", {family: {condition: {f"layer_{layer}": metrics}}}) + + measure("swap", "baseline", -1, tokens, q[:, 2], q[:, 3], pairs["strata"], query_groups=q[:, 0]) + measure( + "native", "baseline", -1, ntokens, native_rows[:, -1], native_rows[:, -1], native_strata + ) + measure( + "atomic", + "baseline", + -1, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + np.full(len(needed), "needed_atoms"), + ) + states, attentions, mlps = trace + rng = torch.Generator(device=device).manual_seed(settings["rotation_seed"]) + rotation, _ = torch.linalg.qr(torch.randn(view.width, view.width, device=device, generator=rng)) + swap_errors, restore_errors = [], [] + diagnostics = [] + axis_families = settings.get("axis_families", ["prefix_jacobian"]) + if not set(axis_families) <= {"prefix_jacobian", "input_embedding"}: + raise ValueError("Unknown direction family") + for layer, jacobian, axis_family in ( + (layer, j, family) for layer, j in enumerate(jacobians) for family in axis_families + ): + suffix = "_embedding" if axis_family == "input_embedding" else "" + directions = F.normalize( + view.embedding.weight[torch.as_tensor(entities, device=device)].float() + @ (torch.eye(view.width, device=device) if suffix else jacobian), + dim=-1, + ) + index = {int(e): i for i, e in enumerate(entities)} + source = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 2]]] + dest = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 4]]] + basis = torch.stack((source, dest), dim=-1) + swapped = swap_coordinates(states[layer], basis) + restored = swap_coordinates(swapped, basis) + swap_errors.append(float((restored - states[layer]).abs().max())) + random_basis = rotation[None] @ basis + swap_delta = swapped - states[layer] + torch.save( + { + "basis": basis.cpu(), + "rotation": rotation.cpu(), + "swap_delta": swap_delta.cpu(), + "axis_family": axis_family, + }, + out / f"patch-{axis_family}-l{layer:02d}.pt", + ) + deltas = { + "swap": swap_delta, + "swap_x2": 2 * swap_delta, + "random_swap": match_norm( + swap_coordinates(states[layer], random_basis) - states[layer], swap_delta + ), + "full_prefix": donor_states[layer] - states[layer], + "swap_back": restored - states[layer], + } + for condition in SWAPS: + measure( + "swap", + condition + suffix, + layer, + tokens, + q[:, 2], + q[:, 3], + pairs["strata"], + deltas[condition][q[:, 0]], + q[:, 0], + ) + native_direction = directions[ + [index[int(b + metadata["entity_offset"])] for b in native_facts[:, 2]] + ] + native_state, native_attention, native_mlp = (a[layer] for a in ntrace) + fixed_direction = directions[index[fixed_entity + metadata["entity_offset"]]][ + None + ].expand_as(native_direction) + fixed_mlp = projection(native_mlp, fixed_direction) + removed_mlp = projection(native_mlp, native_direction) + # All sublayers still execute. Only the selected sender's semantic component + # is subtracted from the actual local update at the boundary. + local_restore = native_state - removed_mlp + removed_mlp + restore_errors.append(float((local_restore - native_state).abs().max())) + erasures = { + "erase_state": -projection(native_state, native_direction), + "erase_mlp": -removed_mlp, + "erase_attention": -projection(native_attention, native_direction), + "random_state": match_norm( + -projection(native_state, native_direction @ rotation.T), + -projection(native_state, native_direction), + ), + "random_mlp": match_norm( + -projection(native_mlp, native_direction @ rotation.T), -removed_mlp + ), + "random_attention": match_norm( + -projection(native_attention, native_direction @ rotation.T), + -projection(native_attention, native_direction), + ), + "restore_mlp": local_restore - native_state, + "fixed_entity_mlp": -fixed_mlp, + "fixed_entity_random_mlp": match_norm( + -projection(native_mlp, fixed_direction @ rotation.T), + -fixed_mlp, + ), + } + for condition in ERASURES: + measure( + "native", + condition + suffix, + layer, + ntokens, + native_rows[:, -1], + native_rows[:, -1], + native_strata, + erasures[condition], + ) + # Relevant single-hop facts are scored under exactly the same local deletion. + adirection = directions[[index[int(b + metadata["entity_offset"])] for b in needed[:, 2]]] + atomic_delta = -projection(atrace[2][layer], adirection) + measure( + "atomic", + "erase_mlp" + suffix, + layer, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + np.full(len(needed), "needed_atoms"), + atomic_delta, + ) + with torch.no_grad(): + raw = F.linear(view.norm(states[layer]), view.embedding.weight).argmax(-1) + lens = F.linear(view.norm(states[layer] @ jacobian.T), view.embedding.weight).argmax(-1) + diagnostics.append( + { + "layer": layer, + "axis_family": axis_family, + "native_bridge_readout_accuracy": float( + ( + raw + == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) + ) + .float() + .mean() + ), + "prefix_jacobian_bridge_readout_accuracy": float( + ( + lens + == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) + ) + .float() + .mean() + ), + "swap_norm_mean": float(swap_delta.norm(dim=-1).mean()), + "native_mlp_removed_norm_mean": float(removed_mlp.norm(dim=-1).mean()), + } + ) + digest_after = model_digest(view.model) + if digest_before != digest_after or any(p.grad is not None for p in view.model.parameters()): + raise AssertionError("Intervention changed model parameters or accumulated gradients") + write_json( + out / "implementation-audit.json", + { + "parameters_unchanged": True, + "native_tracer_max_logit_error": float((native - traced).abs().max()), + "prefix_causal_state_max_error": causal_error, + "swap_inverse_max_errors": swap_errors, + "mlp_restore_max_errors": restore_errors, + "n_needed_atomic_facts": len(needed), + "needed_atomic_answer_accuracy": float(atomic_ok.mean()), + "swap_prerequisite_query_coverage": float(prereq.mean()), + "scoring": ( + "greedy feedback, original/counterfactual answer plus termination; " + "query and first-fact denominators separate" + ), + }, + ) + write_json(out / "diagnostics.json", diagnostics) + log("complete", {"complete": {"evaluations": len(summary)}}) + write_json( + out / "interventions-complete.json", + { + "finished_utc": utc(), + "evaluations": len(summary), + "model_sha256": digest_after, + "wall_seconds": time.perf_counter() - began, + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device), + "new_training_updates": 0, + }, + ) + write_json(out / "status.json", {"state": "awaiting_reload_audit", "step": cursor - 1}) + + +def audit_run(out, gpu): + """Reload in an independent process and reproduce fixed raw prediction subsets.""" + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + metadata_run = json.loads((out / "run.json").read_text()) + spec = metadata_run["spec"] + settings = spec["settings"] + view, _, metadata, _, atoms, _, _, entities, _ = load_task(spec, f"cuda:{gpu}") + assert model_digest(view.model) == metadata_run["initial_model_sha256"] + assert os.getpid() != metadata_run["pid"], "Reload must use a separate process" + selection = dict(np.load(out / "selection.npz")) + groups, queries = selection["groups"], selection["queries"] + jacobians = torch.load(out / "lens.pt", map_location=view.device, weights_only=False)[ + "jacobians" + ] + sender = 1 if view.large else 3 + trace = trace_in_batches( + view, + prefixes(groups[:, :3], view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + states = trace[0] + native_rows = selection["native_rows"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + facts = np.asarray([(h, r, lookup[int(h), int(r)]) for h, r in native_rows[:, :2]]) + ntrace = trace_in_batches( + view, prefixes(facts, view.large, metadata), sender, settings["batch_size"], view.large + ) + swap_indices = np.unique(np.linspace(0, len(queries) - 1, min(32, len(queries)), dtype=int)) + native_indices = np.unique( + np.linspace(0, len(native_rows) - 1, min(32, len(native_rows)), dtype=int) + ) + summary = json.loads((out / "summary.json").read_text()) + comparisons, max_logp_error, identity_controls = [], 0.0, [] + + def check(family, condition, layer, indices, rows, target, cf, delta=None): + nonlocal max_logp_error + + # Baseline is independently executed through the model's own forward. + class NativeView(ModelView): + def logits(self, tokens, **_): + positions = torch.full((len(tokens), 1), tokens.shape[1] - 1, device=self.device) + return self.model(tokens, positions=positions)[:, 0] + + actual = generate( + NativeView(view.model) if condition == "baseline" else view, + prompts(rows, view.large, metadata), + target, + cf, + metadata, + settings["batch_size"], + layer=layer if delta is not None else None, + sender=sender, + delta=delta, + ) + # Preserve original batch shapes: compacting selected rows changes BF16 + # GEMM rounding. Select the audit subset only after the full generation. + actual = {key: value[indices] for key, value in actual.items()} + expected = dict(np.load(out / f"{family}-{condition}-l{layer:02d}.npz")) + if not np.array_equal(actual["generated"], expected["generated"][indices]): + raise AssertionError(f"Reload generation mismatch: {family}/{condition}/{layer}") + for key in ("original_logp", "cf_logp"): + error = float(np.max(np.abs(actual[key] - expected[key][indices]))) + max_logp_error = max(max_logp_error, error) + np.testing.assert_allclose( + actual[key], + expected[key][indices], + atol=0.04 if view.large else 3e-5, + rtol=0.002 if view.large else 2e-5, + ) + comparisons.append( + {"family": family, "condition": condition, "layer": layer, "queries": len(indices)} + ) + + check("swap", "baseline", -1, swap_indices, selection["rows"], queries[:, 2], queries[:, 3]) + check( + "native", + "baseline", + -1, + native_indices, + native_rows, + native_rows[:, -1], + native_rows[:, -1], + ) + entity_index = {int(e): i for i, e in enumerate(entities)} + for layer, jacobian in enumerate(jacobians): + for axis_family in settings.get("axis_families", ["prefix_jacobian"]): + suffix = "_embedding" if axis_family == "input_embedding" else "" + directions = F.normalize( + view.embedding.weight[torch.as_tensor(entities, device=view.device)].float() + @ (torch.eye(view.width, device=view.device) if suffix else jacobian), + dim=-1, + ) + source = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 2]] + ] + dest = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 4]] + ] + delta = ( + swap_coordinates(states[layer], torch.stack((source, dest), dim=-1)) - states[layer] + ) + check( + "swap", + "swap" + suffix, + layer, + swap_indices, + selection["rows"], + queries[:, 2], + queries[:, 3], + delta[queries[:, 0]], + ) + native_direction = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in facts[:, 2]] + ] + native_delta = -projection(ntrace[2][layer], native_direction) + check( + "native", + "erase_mlp" + suffix, + layer, + native_indices, + native_rows, + native_rows[:, -1], + native_rows[:, -1], + native_delta, + ) + # Structural and numerical controls must retain native generation. + for family, condition in ( + ("swap", "swap_back" + suffix), + ("native", "restore_mlp" + suffix), + ): + raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] + baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] + identity_controls.append( + { + "family": family, + "condition": condition, + "layer": layer, + **control_observation(raw, baseline), + } + ) + if layer == len(view.blocks) - 1: + for key in summary: + family, condition, occurrence = key.split("/") + if int(occurrence) != layer or family == "atomic": + continue + raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] + baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] + assert np.array_equal(raw, baseline), ( + key, + "final sender must not affect later positions", + ) + assert model_digest(view.model) == metadata_run["initial_model_sha256"] + previous = out / "implementation-audit.json" + if not previous.exists() and (out / "audit.json").exists(): + previous.write_bytes((out / "audit.json").read_bytes()) + write_json( + out / "audit.json", + { + "independent_process": True, + "pid": os.getpid(), + "gpu": gpu, + "finished_utc": utc(), + "parameters_unchanged": True, + "generations_exact": True, + "identity_controls_exact": all(c["exact"] for c in identity_controls), + "identity_control_observations": identity_controls, + "scope": ( + "Fixed subset reload predictions exact; numerical inverse/restore " + "outcomes recorded separately" + ), + "max_log_probability_error": max_logp_error, + "evaluations": comparisons, + "implementation_audit_sha256": file_hash(previous), + "audit_source_sha256": file_hash(__file__), + }, + ) + if (out / "interventions-complete.json").exists(): + complete = json.loads((out / "interventions-complete.json").read_text()) + complete["independently_reloaded"] = True + complete["audit_finished_utc"] = utc() + write_json(out / "complete.json", complete) + write_json( + out / "status.json", + { + "state": "complete", + "independently_reloaded": True, + "step": json.loads((out / "learning.json").read_text())[-1]["step"], + }, + ) + print( + json.dumps( + { + "run": out.name, + "independent_reload": "passed", + "evaluations": len(comparisons), + "max_log_probability_error": max_logp_error, + } + ), + flush=True, + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/capacity_controls.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/capacity_controls.py new file mode 100644 index 0000000000000000000000000000000000000000..3806e6b81fda1ae9bc25fd74e38f846ddd3a456d --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/capacity_controls.py @@ -0,0 +1,64 @@ +"""Controls separating knowledge load, derived supervision, and serial recall.""" + +from __future__ import annotations + +import numpy as np + +from .capacity_scaling import DIGIT, EOS, TYPE_B + + +def training_indices(world, spec, epoch): + """Keep the historical mixed stream exactly, or replace derived examples. + + Replay preserves the mixed stream's batch sizes/updates and each original + atomic slot. Extra slots carry balanced atomic replay, never held-out labels. + """ + atoms = len(world["atomic"]) + mixed = atoms + len(world["train_composition"]) + mode = spec.get("training_mode", "mixed") + if mode not in {"mixed", "atomic", "atomic_replay"}: + raise ValueError(mode) + n = atoms if mode == "atomic" else mixed + rng = np.random.default_rng(np.random.SeedSequence([spec["stream_seed"], epoch])) + order = rng.permutation(n) + if mode == "atomic_replay": + replay_rng = np.random.default_rng( + np.random.SeedSequence([spec["stream_seed"], epoch, 771]) + ) + replacements = np.resize(replay_rng.permutation(atoms), mixed - atoms) + source = np.concatenate((np.arange(atoms), replacements)) + return source[order] + return order + + +def decode_bridge(predictions): + """Reject malformed/out-of-domain predictions instead of oracle repairing.""" + p = np.asarray(predictions) + d = p[:, 1:5] - DIGIT + valid = ( + (p[:, 0] == TYPE_B) + & (p[:, 5] == EOS) + & ((d >= 0) & (d < 16)).all(1) + & (d[:, :2] == 0).all(1) + ) + values = (np.clip(d, 0, 15) * np.array([4096, 256, 16, 1])).sum(1) + return np.where(valid, values, 0), valid + + +def first_queries(compositions): + rows = np.zeros_like(compositions) + rows[:, 0] = 0 + rows[:, 1:3] = compositions[:, 1:3] + rows[:, 3] = -1 + rows[:, 5:] = -1 + return rows + + +def second_queries(compositions, bridges): + rows = np.zeros_like(compositions) + rows[:, 0] = 1 + rows[:, 1] = bridges + rows[:, 2] = compositions[:, 3] + rows[:, 3] = -1 + rows[:, 5:] = -1 + return rows diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/capacity_scaling.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/capacity_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c152e8710de107c8fb2f4ba2275cdea5cbdcf3 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/capacity_scaling.py @@ -0,0 +1,193 @@ +"""Fixed-vocabulary random worlds for the capacity development experiment. + +Knowledge is in independent A->B and B->C maps. Composition labels are derived, +never counted as independent information. This is a QA adaptation, not bioS. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +PAD, BOS, EOS, ANSWER = 0, 1, 2, 3 +TYPE_A, TYPE_B, TYPE_C = 4, 5, 6 +DIGIT, REL_A, REL_B = 7, 23, 27 +VOCAB, CONTEXT, ANSWER_LENGTH = 31, 14, 6 + + +def digest_arrays(arrays): + h = hashlib.sha256() + for key, value in sorted(arrays.items()): + value = np.ascontiguousarray(value) + h.update(key.encode()) + h.update(str(value.shape).encode()) + h.update(str(value.dtype).encode()) + h.update(value.tobytes()) + return h.hexdigest() + + +def generate_world(spec): + """Rows: kind, subject, r1, r2, answer, necessary_atom_1, necessary_atom_2. + + The maximum address universe and all maps are generated before choosing a + load. Prefix worlds are nested. Background controls keep the entire low-load + composition training/evaluation sets, including necessary facts, unchanged. + """ + seed, heads = spec["world_seed"], spec["heads_n"] + maximum, values, relations = spec["max_heads"], spec["values_n"], spec["relations"] + if not (1 <= heads <= maximum <= 65536 and values == 256 and relations == 4): + raise ValueError("This version requires 256 values, four relations, <=65536 heads") + support_heads = spec.get("support_heads_n", heads) + if not 1 <= support_heads <= heads: + raise ValueError("Invalid support prefix") + + def rng(part): + return np.random.default_rng(np.random.SeedSequence([seed, part])) + + first = rng(0).integers(values, size=(maximum, relations), dtype=np.int64)[:heads] + second = rng(1).integers(values, size=(values, relations), dtype=np.int64) + eligible_first = rng(2).random((maximum, relations))[:support_heads] < 0.75 + eligible_second = rng(3).random((values, relations)) < 0.75 + first_n = heads * relations + h, r = np.indices(first.shape).reshape(2, -1) + atoms_a = np.column_stack( + ( + np.zeros(first_n, dtype=int), + h, + r, + -np.ones(first_n, dtype=int), + first.ravel(), + np.arange(first_n), + -np.ones(first_n, dtype=int), + ) + ) + b, r2 = np.indices(second.shape).reshape(2, -1) + second_n = second.size + atoms_b = np.column_stack( + ( + np.ones(second_n, dtype=int), + b, + r2, + -np.ones(second_n, dtype=int), + second.ravel(), + first_n + np.arange(second_n), + -np.ones(second_n, dtype=int), + ) + ) + atoms = np.concatenate((atoms_a, atoms_b)).astype(np.int64) + h, r1, r2 = np.indices((support_heads, relations, relations)).reshape(3, -1) + bridge = first[h, r1] + a_id, b_id = h * relations + r1, first_n + bridge * relations + r2 + comps = np.column_stack((np.full(len(h), 2), h, r1, r2, second[bridge, r2], a_id, b_id)).astype( + np.int64 + ) + train_mask = ( + eligible_first[h, r1] & eligible_second[bridge, r2] & (((r2 - h - r1) % relations) < 2) + ) + trained = np.zeros(len(atoms), dtype=bool) + trained[comps[train_mask, 5:].ravel()] = True + seen1, seen2 = trained[a_id], trained[b_id] + world = { + "first": first, + "second": second, + "atomic": atoms, + "train_composition": comps[train_mask], + } + for name, mask in { + "II": seen1 & seen2, + "IO": seen1 & ~seen2, + "OI": ~seen1 & seen2, + "OO": ~seen1 & ~seen2, + }.items(): + ids = np.flatnonzero(mask & ~train_mask) + # Selection stream does not depend on load in fixed-target controls. + take = rng(20 + ["II", "IO", "OI", "OO"].index(name)).permutation(ids) + world[name] = comps[take[: spec["evaluation_per_pool"]]] + world[name + "_population"] = np.array([len(ids)], dtype=np.int64) + panel_rng = rng(30) + for name in ("atomic", "train_composition"): + ids = panel_rng.permutation(len(world[name]))[: spec["evaluation_per_pool"]] + world[name + "_panel"] = world[name][ids] + world["role_counts"] = np.stack( + [np.bincount(world["train_composition"][:, col], minlength=len(atoms)) for col in (5, 6)] + ) + return world + + +def digits(values): + values = np.asarray(values, dtype=np.int64) + return DIGIT + ((values[:, None] >> np.array([12, 8, 4, 0])) & 15) + + +def pack(rows): + """Right padding is causally downstream; only answer+EOS is supervised.""" + rows = np.asarray(rows, dtype=np.int64) + x = np.zeros((len(rows), CONTEXT), dtype=np.int64) + composition = rows[:, 0] == 2 + prefix_length = np.where(composition, 9, 8) + x[:, 0] = BOS + x[:, 1] = np.where(rows[:, 0] == 1, TYPE_B, TYPE_A) + x[:, 2:6] = digits(rows[:, 1]) + x[:, 6] = np.where(rows[:, 0] == 1, REL_B, REL_A) + rows[:, 2] + x[:, 7] = np.where(composition, REL_B + rows[:, 3], ANSWER) + x[composition, 8] = ANSWER + labels = np.column_stack( + (np.where(rows[:, 0] == 0, TYPE_B, TYPE_C), digits(rows[:, 4]), np.full(len(rows), EOS)) + ) + positions = prefix_length[:, None] - 1 + np.arange(ANSWER_LENGTH) + x[np.arange(len(rows))[:, None], positions[:, 1:]] = labels[:, :-1] + return x, positions, labels + + +def information_ledger(world, parameters, knowledge_nll=None): + facts = len(world["atomic"]) + bits = facts * math.log2(world["second"].shape[0]) + result = { + "independent_facts": facts, + "world_bits": bits, + "parameters": parameters, + "adjusted_parameters": parameters, + "data_bits_per_parameter": bits / parameters, + "composition_independent_bits": 0, + } + if knowledge_nll is not None: + learned = bits - facts * knowledge_nll / math.log(2) + result.update(learned_bits_raw=learned, learned_bits_per_parameter=learned / parameters) + return result + + +def model_parameter_count(width, layers=2): + # Tied token/output weights, learned positions, two biased projections each + # in attention/MLP, per-block and final LayerNorms. + return (VOCAB + CONTEXT) * width + layers * (12 * width**2 + 13 * width) + 2 * width + + +def prerequisite_pass(metrics, thresholds): + return all( + metrics[key]["accuracy"] >= thresholds[key] for key in ("atomic", "train_composition", "II") + ) + + +def grid_capacity(points, metric, threshold, atomic_threshold): + """Report sampled successes and censoring, never silently assume monotonicity.""" + points = sorted(points, key=lambda p: p["bits"]) + passed = [p["atomic"] >= atomic_threshold and p[metric] >= threshold for p in points] + reversals = any(passed[i] and not passed[i - 1] for i in range(1, len(passed))) + successes = [p["bits"] for p, ok in zip(points, passed, strict=True) if ok] + lower = max(successes) if successes else None + failures_above = [ + p["bits"] + for p, ok in zip(points, passed, strict=True) + if not ok and (lower is None or p["bits"] > lower) + ] + return { + "largest_observed_passing_bits": lower, + "next_observed_failing_bits": min(failures_above) if failures_above else None, + "nonmonotonic_grid": reversals, + "interpretation": "sampled_grid_only; bracket requires monotone interpolation", + "censoring": "below_grid" + if lower is None + else ("above_grid" if not failures_above else "bracketed_on_grid"), + } diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/cli.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..1aec4627fdf91a196893b3a6d47c8188da55d55b --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/cli.py @@ -0,0 +1,32 @@ +"""Command-line interface for the deterministic matrix illustration.""" + +import argparse +import json +from pathlib import Path + +from .experiments import run_minimal_example + + +def main(argv: list[str] | None = None) -> int: + """Print the analytical report as JSON and optionally save a copy.""" + parser = argparse.ArgumentParser(description="Run the analytical low-rank editability example.") + parser.add_argument( + "--rank", type=int, default=1, help="total rank budget: 0, 1 (default), or 2" + ) + parser.add_argument( + "--atol", type=float, default=1e-10, help="positive absolute singular-value tolerance" + ) + parser.add_argument( + "--output", type=Path, help="also save JSON to this path (creates parent directories)" + ) + args = parser.parse_args(argv) + try: + report = run_minimal_example(rank=args.rank, atol=args.atol) + serialized = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(serialized + "\n", encoding="utf-8") + except (ValueError, OSError) as exc: + parser.error(str(exc)) + print(serialized) + return 0 diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/composition_curves.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/composition_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..13009dcfa856d01722da32842dcc3a7fe078a635 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/composition_curves.py @@ -0,0 +1,477 @@ +"""Distinct composition support and knowledge-load curves on random relation graphs. + +The graph, answer/EOS objective, GPT blocks and optimizer reuse the previously +successful Wang et al. adaptation. A fixed maximum entity vocabulary keeps +parameters identical across loads. Development and confirmation worlds differ. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import ( + EpochStream, + GraphStep, + SmallGPT, + evaluate_rows, + make_optimizer, + pack_rows, + two_calls, + utc, + write_json, +) +from .grok_depth_data import audit_world, build_world + + +def sha256(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def array_hash(arrays): + digest = hashlib.sha256() + for name, value in sorted(arrays.items()): + digest.update(name.encode()) + digest.update(np.asarray(value.shape, dtype=" len(order): + raise ValueError("Distinct support request exceeds the reserved training pool") + arrays = { + key: base[key].copy() + for key in ("atomic", "id_atomic", "ood_atomic", "test_composite", "ood_composite") + } + eligible = base["unused_composite"][order].copy() + for rows in [*arrays.values(), eligible]: + rows[:, 1:-1] += maximum - n + identity = array_hash({**arrays, "eligible": eligible}) + arrays["train_composite"] = eligible[:requested].copy() + lookup = np.full((maximum, spec["relations"]), -1, dtype=np.int64) + atomic = arrays["atomic"] + lookup[atomic[:, 0] - 2, atomic[:, 1] - maximum - 2] = np.arange(len(atomic)) + first, second = constituent_indices(arrays["train_composite"], atomic, lookup, maximum) + first_counts = np.bincount(first, minlength=len(atomic)) + second_counts = np.bincount(second, minlength=len(atomic)) + role = {} + for name in ("test_composite", "ood_composite"): + one, two = constituent_indices(arrays[name], atomic, lookup, maximum) + role[name] = { + "n": len(one), + "both_facts_seen_in_required_roles": ( + float(((first_counts[one] > 0) & (second_counts[two] > 0)).mean()) + if len(one) + else None + ), + } + panel_rng = np.random.default_rng(np.random.SeedSequence([spec["world_seed"], n, 960602])) + panels = {} + for key, name in [ + ("atomic", "atomic"), + ("id_atomic", "atomic_id"), + ("ood_atomic", "atomic_ood"), + ("test_composite", "II"), + ("ood_composite", "OO"), + ]: + rows = arrays[key] + ids = panel_rng.choice(len(rows), min(spec["evaluation_size"], len(rows)), replace=False) + panels[name] = rows[ids].copy() + panels["train_composition"] = arrays["train_composite"][: spec["evaluation_size"]].copy() + metadata = { + "world_seed": spec["world_seed"], + "entities": n, + "max_entities": maximum, + "relations": spec["relations"], + "degree": spec["degree"], + "vocab_size": maximum + spec["relations"] + 2, + "atomic_examples": len(atomic), + "id_atomic_examples": len(arrays["id_atomic"]), + "composition_examples": requested, + "eligible_compositions": len(eligible), + "phi_actual": requested / len(arrays["id_atomic"]), + "world_sha256": identity, + "dataset_sha256": array_hash(arrays), + "knowledge_bits": len(atomic) * math.log2(n), + "entropy_condition": "independent uniform tails, conditional on head/relation keys", + "composition_additional_independent_bits": 0, + "role_coverage": role, + "panel_counts": {key: len(value) for key, value in panels.items()}, + "full_counts": {key: len(value) for key, value in arrays.items()}, + "graph_source": base["metadata"]["source_url"], + "graph_source_commit": base["metadata"]["source_commit"], + "graph_audit": base["metadata"]["dataset_sha256"], + } + return arrays, panels, metadata + + +def constituent_indices(rows, atomic, lookup, maximum): + first = lookup[rows[:, 0] - 2, rows[:, 1] - maximum - 2] + if np.any(first < 0): + raise ValueError("Unknown first-hop fact") + second = lookup[atomic[first, 2] - 2, rows[:, 2] - maximum - 2] + if np.any(second < 0) or not np.array_equal(atomic[second, 2], rows[:, -1]): + raise ValueError("Composition truth differs from graph traversal") + return first, second + + +def budget_nodes(spec, total): + matched = math.ceil(spec["target_exposures"] * total / spec["batch_size"]) + compute = spec["compute_steps"] + end = spec.get("fixed_steps", max(compute, matched)) + nodes = {0, end, *range(2000, min(end, 128000) + 1, 2000)} + nodes.update(s for s in (256, 512, 1000, compute, matched) if s <= end) + nodes.update(range(192000, end, 64000)) + return sorted(nodes), {"compute": compute, "exposure": matched, "end": end} + + +def construct(spec, device): + torch.manual_seed(spec["initialization"]) + cfg = ModelConfig( + vocab_size=spec["max_entities"] + spec["relations"] + 2, + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + return SmallGPT(cfg, dropout=spec["dropout"]).to(device), cfg + + +def model_hash(model): + digest = hashlib.sha256() + for name, tensor in model.state_dict().items(): + digest.update(name.encode()) + digest.update(tensor.detach().cpu().contiguous().numpy().tobytes()) + return digest.hexdigest() + + +def measure(model, panels, device): + metrics, predictions = {}, {} + for name, rows in panels.items(): + metrics[name], values = evaluate_rows(model, rows, device, batch_size=512) + if len(rows): + metrics[name]["answer_nll"] = float(values["nll"][:, 0].mean()) + predictions.update({name + "_" + key: value for key, value in values.items()}) + return metrics, predictions + + +def train(spec, out, resume=False): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device("cuda:0") + torch.cuda.set_device(device) + arrays, panels, data = prepare_world(spec) + model, cfg = construct(spec, device) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + packed = [pack_rows(arrays[key]) for key in ("atomic", "train_composite")] + table = tuple( + torch.as_tensor(np.concatenate([a, b]), device=device) for a, b in zip(*packed, strict=True) + ) + atomic_n, composition_n = data["atomic_examples"], data["composition_examples"] + total = atomic_n + composition_n + stream = EpochStream(total, spec["stream_seed"]) + nodes, budgets = budget_nodes(spec, total) + start, seconds = 0, 0.0 + counts = {"atomic": 0, "composition": 0} + initial_hash = model_hash(model) + if resume: + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if saved["spec"] != spec or saved["world_sha256"] != data["world_sha256"]: + raise ValueError("Resume identity mismatch") + model.load_state_dict(saved["model"]) + optimizer.load_state_dict(saved["optimizer"]) + lr = optimizer.param_groups[0]["lr"] + for group in optimizer.param_groups: + group["lr"] = lr + stream.load_state_dict(saved["stream"]) + counts, seconds, start = saved["counts"], saved["seconds"], saved["step"] + torch.set_rng_state(saved["cpu_rng"].cpu()) + torch.cuda.set_rng_state(saved["cuda_rng"].cpu()) + initial_hash = json.loads((out / "run.json").read_text())["initial_model_sha256"] + out.mkdir(parents=True, exist_ok=True) + metadata = { + "spec": spec, + "phase": spec["phase"], + "pid": os.getpid(), + "gpu": int(os.environ.get("PHYSICAL_GPU", 0)), + "gpu_name": torch.cuda.get_device_name(), + "parameters": sum(p.numel() for p in model.parameters()), + "initial_model_sha256": initial_hash, + "world_sha256": data["world_sha256"], + "dtype": "FP32 parameters/optimizer/forward; TF32 matmul", + "torch": torch.__version__, + "numpy": np.__version__, + "budgets": budgets, + "evaluation_nodes": nodes, + **data, + } + write_json(out / "run.json", metadata) + write_json(out / "data-audit.json", data) + np.savez_compressed(out / "world.npz", **arrays) + np.savez_compressed(out / "panels.npz", **panels) + t0 = time.perf_counter() + graph = GraphStep(model, optimizer, table, spec["batch_size"]) + capture = time.perf_counter() - t0 + per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) + history = json.loads((out / "learning.json").read_text()) if resume else [] + history = [record for record in history if record["step"] <= start] + begun = time.perf_counter() + + def checkpoint(step, loss=None): + metrics, predictions = measure(model, panels, device) + record = { + "step": step, + "utc": utc(), + "metrics": metrics, + "training_seconds": seconds, + "wall_seconds": time.perf_counter() - begun, + "capture_seconds": capture, + "examples": step * spec["batch_size"], + "atomic_examples_seen": counts["atomic"], + "composition_examples_seen": counts["composition"], + "atomic_epochs": counts["atomic"] / atomic_n, + "composition_epochs": counts["composition"] / composition_n if composition_n else 0, + "minimum_record_exposures": (step * spec["batch_size"]) // total, + "maximum_record_exposures": math.ceil(step * spec["batch_size"] / total), + "supervised_tokens": step * spec["batch_size"] * 2, + "executed_input_tokens": step * spec["batch_size"] * 4, + "estimated_matmul_training_flops": step * per_step, + "loss": loss, + "learning_rate": float(lr.detach()), + } + history.append(record) + write_json(out / "learning.json", history) + payload = { + "spec": spec, + "world_sha256": data["world_sha256"], + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "seconds": seconds, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(), + } + torch.save(payload, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in budgets.values(): + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step}.pt", + ) + np.savez_compressed(out / f"predictions-{step}.npz", **predictions) + status = { + "state": "trained" if step == budgets["end"] else "running", + "step": step, + "budget": budgets["end"], + "atomic": metrics["atomic"]["accuracy"], + "II": metrics["II"]["accuracy"], + "updated_utc": utc(), + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + + if not resume: + checkpoint(0) + for end in (node for node in nodes if node > start): + torch.cuda.synchronize() + t0 = time.perf_counter() + loss = None + step = start + while step < end: + length = min(256, end - step) + indices = stream.take(length * spec["batch_size"]).reshape(length, -1) + atom_count = int((indices < atomic_n).sum()) + counts["atomic"] += atom_count + counts["composition"] += indices.size - atom_count + gpu_indices = torch.as_tensor(indices, device=device) + for j in range(length): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + loss = graph(gpu_indices[j]) + step += length + torch.cuda.synchronize() + seconds += time.perf_counter() - t0 + value = float(loss.detach()) + if not math.isfinite(value): + raise FloatingPointError(f"Nonfinite loss at {end}") + checkpoint(end, value) + start = end + full_panels = { + "atomic": arrays["atomic"], + "atomic_id": arrays["id_atomic"], + "atomic_ood": arrays["ood_atomic"], + "II": arrays["test_composite"], + "OO": arrays["ood_composite"], + } + full, predictions = measure(model, full_panels, device) + full["external_two_calls"] = two_calls(model, panels["II"], device) + np.savez_compressed(out / "full-predictions.npz", **predictions) + write_json( + out / "complete.json", + { + "step": start, + "spec": spec, + "parameters": metadata["parameters"], + "training_seconds": seconds, + "wall_seconds": time.perf_counter() - begun, + "endpoint": history[-1], + "full_metrics": full, + "finished_utc": utc(), + }, + ) + + +def audit(spec, out): + """Reload both predeclared comparison checkpoints and independently recount.""" + out = Path(out) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + arrays, panels, data = prepare_world(spec) + recorded = dict(np.load(out / "world.npz")) + if array_hash(recorded) != data["dataset_sha256"]: + raise ValueError("Saved world differs from deterministic reconstruction") + meta = json.loads((out / "run.json").read_text()) + if meta["world_sha256"] != data["world_sha256"]: + raise ValueError("World identity mismatch") + history = json.loads((out / "learning.json").read_text()) + nodes, budgets = budget_nodes(spec, data["atomic_examples"] + data["composition_examples"]) + if [record["step"] for record in history] != nodes: + raise ValueError("Missing or reordered evaluation nodes") + model, cfg = construct(spec, "cuda:0") + if sum(p.numel() for p in model.parameters()) != meta["parameters"]: + raise ValueError("Parameter count mismatch") + per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) + for record in history: + examples = record["step"] * spec["batch_size"] + if record["examples"] != examples or examples != ( + record["atomic_examples_seen"] + record["composition_examples_seen"] + ): + raise ValueError("Exposure arithmetic mismatch") + if record["estimated_matmul_training_flops"] != record["step"] * per_step: + raise ValueError("Executed-shape FLOP mismatch") + reloaded = [] + for step in sorted(set(budgets.values()) & set(nodes)): + saved = torch.load(out / f"weights-{step}.pt", weights_only=False, map_location="cuda:0") + if saved["spec"] != spec or saved["step"] != step: + raise ValueError("Checkpoint identity mismatch") + model.load_state_dict(saved["model"]) + metrics, predictions = measure(model, panels, "cuda:0") + original = dict(np.load(out / f"predictions-{step}.npz")) + for key, values in predictions.items(): + if key.endswith("_nll"): + np.testing.assert_allclose(values, original[key], rtol=1e-5, atol=1e-6) + elif not np.array_equal(values, original[key]): + raise ValueError(f"Reloaded predictions changed: {step} {key}") + prior = next(record for record in history if record["step"] == step)["metrics"] + for name, metric in metrics.items(): + if metric["accuracy"] != prior[name]["accuracy"]: + raise ValueError("Metric recount mismatch") + reloaded.append(step) + full_panels = { + "atomic": arrays["atomic"], + "atomic_id": arrays["id_atomic"], + "atomic_ood": arrays["ood_atomic"], + "II": arrays["test_composite"], + "OO": arrays["ood_composite"], + } + full, predictions = measure(model, full_panels, "cuda:0") + original = dict(np.load(out / "full-predictions.npz")) + for key, value in predictions.items(): + np.testing.assert_allclose(value, original[key], rtol=1e-5, atol=1e-6) + full["external_two_calls"] = two_calls(model, panels["II"], "cuda:0") + write_json( + out / "audit.json", + {"passed": True, "reloaded_steps": reloaded, "full_metrics": full, "utc": utc()}, + ) + write_json(out / "status.json", {"state": "complete", "step": budgets["end"], "utc": utc()}) + + +def calibrated_choice(records, thresholds): + """Development-only success gate; prefer smaller registered model when both pass.""" + candidates = [] + for spec, metrics in records: + passed = all(metrics[key]["accuracy"] >= value for key, value in thresholds.items()) + if passed: + candidates.append(spec) + return min(candidates, key=lambda spec: spec["layers"]) if candidates else None + + +def confirmation_specs(config, selected): + specs = [] + for index, seed in enumerate(config["confirmation_worlds"]): + for phi in config["support_phi"]: + specs.append( + { + **selected, + "phase": "confirmation", + "world_seed": seed, + "initialization": config["initialization"] + index, + "stream_seed": config["stream_seed"] + index, + "name": f"support-w{index + 1}-phi{phi:g}", + "phi": phi, + "entities": config["base_spec"]["entities"], + } + ) + return specs + + +def anchors_pass(records, worlds, thresholds): + """Require exactly the registered independent worlds; no cherry-picked anchors.""" + observed = [spec["world_seed"] for spec, _ in records] + if len(observed) != len(worlds) or set(observed) != set(worlds): + return False + return all( + all(metrics[key]["accuracy"] >= threshold for key, threshold in thresholds.items()) + for _, metrics in records + ) + + +def load_specs(config, selected): + specs = [] + for index, seed in enumerate(config["confirmation_worlds"]): + for n in config["load_entities"][1:]: + specs.append( + { + **selected, + "phase": "confirmation", + "world_seed": seed, + "initialization": config["initialization"] + index, + "stream_seed": config["stream_seed"] + index, + "name": f"load-w{index + 1}-n{n}", + "phi": config["anchor_phi"], + "entities": n, + } + ) + return specs diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/curve_tracking.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/curve_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..526a40aecb32ed282e9de766f3162546d80403ac --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/curve_tracking.py @@ -0,0 +1,36 @@ +"""Retry transient W&B connection failures without changing scientific trajectories.""" + +import json +import time +import traceback +from datetime import datetime, timezone +from pathlib import Path + +from . import interface_tracking +from .experiment_tracking import write_json + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def main(): + import sys + + root = Path(sys.argv[sys.argv.index("--root") + 1]) + for attempt in range(1, 145): + try: + interface_tracking.main() + return + except Exception: + path = root / "tracking-retries.json" + history = json.loads(path.read_text()) if path.exists() else [] + history.append({"attempt": attempt, "utc": utc(), "error": traceback.format_exc()}) + write_json(path, history) + print(json.dumps({"tracking_retry": attempt, "utc": utc()}), flush=True) + time.sleep(min(60, 5 * attempt)) + raise RuntimeError("W&B retry budget exhausted; scientific artifacts remain intact") + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/depth_step.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/depth_step.py new file mode 100644 index 0000000000000000000000000000000000000000..8f828c9ccea5c225dd4fc257587afe3c0ff7c6bf --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/depth_step.py @@ -0,0 +1,669 @@ +"""Ordinary end-to-end GPT depth and optimization-time development experiment. + +The frozen random graph is shared across two-, three- and four-hop training. +Only terminal entities enter composition text; intermediate truth is used for +evaluation and audit. Existing experimental implementations remain unchanged. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_data import build_world as single_length_world +from .grok_loop_model import LoopGPT, flops +from .latent_scaling import model_digest +from .storage_composition import FullTokenStep, file_hash +from .storage_frontier import learning_rate + +BOS, EOS, PAD, ENTITY_OFFSET = 2, 1, 0, 3 +HOPS = (2, 3, 4) +TRAIN_SPLITS = ("atomic", "train_2", "train_3", "train_4") +EVALUATION_SPLITS = ("atomic",) + tuple( + f"{split}_{hop}" for hop in HOPS for split in ("train", "familiar", "strict") +) +DATA_DEFAULTS = { + "entities": 64, + "relations": 4, + "degree": 4, + "phi": 4.0, + "id_fraction": 0.75, + "id_test_fraction": 0.2, + "evaluation_size": 512, +} +SOURCE_FILES = [ + "src/llm_memory_editability/bios_model.py", + "src/llm_memory_editability/grok_depth.py", + "src/llm_memory_editability/grok_depth_data.py", + "src/llm_memory_editability/grok_loop_data.py", + "src/llm_memory_editability/grok_multihop_data.py", + "src/llm_memory_editability/grok_loop_model.py", + "src/llm_memory_editability/latent_scaling.py", + "src/llm_memory_editability/storage_composition.py", + "src/llm_memory_editability/storage_frontier.py", + "src/llm_memory_editability/text_pretrain.py", + "src/llm_memory_editability/depth_step.py", + "scripts/run_depth_step.py", + "tests/test_depth_step.py", +] + + +def data_digest(world): + digest = hashlib.sha256() + for name in EVALUATION_SPLITS: + rows = world[name] + digest.update(name.encode()) + digest.update(np.asarray(rows.shape, dtype="= relation_offset)): + raise ValueError("Invalid entity token: " + name) + if np.any( + (rows[:, 1:-1] < relation_offset) | (rows[:, 1:-1] >= relation_offset + relations) + ): + raise ValueError("Invalid relation token: " + name) + if len(set(map(tuple, rows[:, :-1]))) != len(rows): + raise ValueError("Duplicate complete query: " + name) + _, edges = truth_path_details(world, rows) + if name.startswith(("train_", "familiar_")) and not id_mask[edges].all(): + raise ValueError("Non-ID fact in familiar training/test: " + name) + if name.startswith("strict_") and id_mask[edges].any(): + raise ValueError("ID fact in strict composition: " + name) + counts[name] = len(rows) + if len(world["atomic"]) != entities * meta["degree"]: + raise ValueError("Atomic graph degree does not match the contract") + for hop in HOPS: + query_sets = [ + set(map(tuple, world[f"{split}_{hop}"][:, :-1])) + for split in ("train", "familiar", "strict") + ] + if any(query_sets[i] & query_sets[j] for i in range(3) for j in range(i)): + raise ValueError("Complete query leakage between length-specific splits") + trained_edges = set() + for hop in HOPS: + trained_edges.update(truth_path_details(world, world[f"train_{hop}"])[1].ravel()) + for hop in HOPS: + strict_edges = set(truth_path_details(world, world[f"strict_{hop}"])[1].ravel()) + if strict_edges & trained_edges: + raise ValueError("Strict facts participated in another length's composition training") + digest = data_digest(world) + if "dataset_sha256" in meta and meta["dataset_sha256"] != digest: + raise ValueError("Frozen dataset digest differs from actual arrays") + return { + "passed": True, + "counts": counts, + "dataset_sha256": digest, + "truth_edges_independently_traversed": True, + "complete_query_overlap": 0, + "all_strict_facts_absent_from_composition_training": True, + "cross_length_subpath_holdout": False, + } + + +def build_world(spec): + seed = spec.get("world_seed", spec.get("world")) + if seed is None: + raise ValueError("A fixed world_seed is required") + settings = {key: spec.get(key, value) for key, value in DATA_DEFAULTS.items()} + world, shared_atoms, shared_ids = {}, None, None + source_metadata = {} + for hop in HOPS: + original = single_length_world({"world_seed": seed, "hops": hop, **settings}) + # The historical graph reserves only PAD/EOS and uses entity offset 2. + # Shift every entity/relation token once to reserve the explicit BOS=2. + atoms = original["atomic"] + 1 + id_set = set(map(tuple, original["id_atomic"])) + id_mask = np.asarray([tuple(row) in id_set for row in original["atomic"]], dtype=bool) + if shared_atoms is None: + shared_atoms, shared_ids = atoms.copy(), id_mask.copy() + elif not np.array_equal(shared_atoms, atoms) or not np.array_equal(shared_ids, id_mask): + raise ValueError("Path lengths do not share identical graph and ID mask") + world[f"train_{hop}"] = original["train_composite"] + 1 + world[f"familiar_{hop}"] = original["test_full_composite"] + 1 + world[f"strict_{hop}"] = original["ood_composite"] + 1 + source_metadata[str(hop)] = original["metadata"] + world["atomic"] = shared_atoms + world["metadata"] = { + "world_seed": int(seed), + **settings, + "id_mask": shared_ids.tolist(), + "source_worlds": source_metadata, + "same_atomic_and_id_mask_all_lengths": True, + "source_entity_offset": 2, + "entity_offset": ENTITY_OFFSET, + "source_token_shift": 1, + "separator_token": ENTITY_OFFSET + settings["entities"] + settings["relations"], + "vocab_size": ENTITY_OFFSET + settings["entities"] + settings["relations"] + 1, + "evaluation_pools": "Complete test_full_composite and ood_composite", + "composition_supervision": "Terminal entity only; no intermediate entity", + "training_objective": "All nonpadding next tokens including EOS", + "holdout": "Complete queries held out within each length; not subpaths across lengths", + } + report = audit_world(world) + world["metadata"]["dataset_sha256"] = report["dataset_sha256"] + world["metadata"]["independent_audit"] = report + expected = spec.get("frozen_data_sha256") + if expected is not None and expected != report["dataset_sha256"]: + raise ValueError("Rebuilt data differ from the frozen specification") + return world + + +def construct(spec, device): + if spec.get("context", 9) < 9: + raise ValueError("Context must support four-hop answer and EOS") + config = ModelConfig( + vocab_size=ENTITY_OFFSET + spec.get("entities", 64) + spec.get("relations", 4) + 1, + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=spec.get("context", 9), + ) + if config.layers > 6: + raise ValueError("Canonical paired initialization is limited to six unique blocks") + torch.manual_seed(spec["initialization"]) + canonical = LoopGPT( + replace(config, layers=6), + repeats=1, + dropout=spec.get("dropout", 0.0), + initialization="scaled_effective", + ) + model = LoopGPT( + config, + repeats=spec["repeats"], + dropout=spec.get("dropout", 0.0), + initialization="scaled_effective", + ) + initial = canonical.state_dict() + state = {} + factor = math.sqrt(6 / (config.layers * spec["repeats"])) + for key in model.state_dict(): + value = initial[key].clone() + if key.endswith(("attention.proj.weight", "mlp.down.weight")): + value.mul_(factor) + state[key] = value + model.load_state_dict(state) + return model.to(device) + + +def prompt_rows(rows, separator=71): + rows = np.asarray(rows, dtype=np.int64) + return np.c_[ + np.full(len(rows), BOS, dtype=np.int64), + rows[:, :-1], + np.full(len(rows), separator, dtype=np.int64), + ] + + +def pack_rows(rows, sequence=8, separator=71): + """All nonpadding next-token labels; compact rows contain no intermediate nodes.""" + rows = np.asarray(rows, dtype=np.int64) + sentence = np.c_[ + prompt_rows(rows, separator), rows[:, -1], np.full(len(rows), EOS, dtype=np.int64) + ] + length = sentence.shape[1] - 1 + if length > sequence: + raise ValueError("Packed sequence is too short") + tokens = np.zeros((len(rows), sequence), dtype=np.int64) + labels = np.full_like(tokens, -100) + tokens[:, :length], labels[:, :length] = sentence[:, :-1], sentence[:, 1:] + return tokens, labels + + +def run_name(spec): + seed = spec.get("world_seed", spec.get("world")) + return ( + f"w{seed}-i{spec['initialization']}-d{spec['width']}" + f"-l{spec['layers']}-r{spec['repeats']}-s{spec['steps']}" + ) + + +def _mean(values): + return float(np.asarray(values).mean()) if len(values) else None + + +@torch.no_grad() +def generate_rows(model, rows, device, separator=71, batch_size=512): + """Ordinary full forward, then free tail/EOS generation with answer feedback.""" + rows = np.asarray(rows, dtype=np.int64) + generated, nll = [], [] + for start in range(0, len(rows), batch_size): + batch = rows[start : start + batch_size] + tokens = torch.as_tensor(prompt_rows(batch, separator), device=device) + first = model(tokens)[:, -1] + target = torch.as_tensor(batch[:, -1], device=device) + nll.append(F.cross_entropy(first, target, reduction="none").cpu().numpy()) + answer = first.argmax(-1) + tokens = torch.cat([tokens, answer[:, None]], dim=1) + stop = model(tokens)[:, -1].argmax(-1) + generated.append(torch.stack([answer, stop], dim=1).cpu().numpy()) + pred = np.concatenate(generated) if generated else np.empty((0, 2), dtype=np.int64) + nll = np.concatenate(nll) if nll else np.empty(0, dtype=np.float32) + answer_correct = pred[:, 0] == rows[:, -1] + correct = answer_correct & (pred[:, 1] == EOS) + return { + "n": len(rows), + "accuracy": _mean(correct), + "answer_accuracy": _mean(answer_correct), + "answer_nll": _mean(nll), + }, {"generated": pred, "correct": correct, "answer_nll": nll} + + +@torch.no_grad() +def evaluate(model, world, device): + before = model.training + model.eval() + metrics, predictions = {}, {} + separator = world["metadata"]["separator_token"] + try: + atomic_metrics, atomic_pred = generate_rows(model, world["atomic"], device, separator) + metrics["atomic"] = atomic_metrics + predictions.update({"atomic_" + key: value for key, value in atomic_pred.items()}) + for name in EVALUATION_SPLITS[1:]: + rows = world[name] + task_metrics, direct = generate_rows(model, rows, device, separator) + nodes, edges = truth_path_details(world, rows) + coverage = atomic_pred["correct"][edges].all(axis=1) + current = rows[:, 0].copy() + hops = rows.shape[1] - 2 + calls = np.empty((len(rows), hops, 2), dtype=np.int64) + for hop in range(hops): + query = np.c_[current, rows[:, hop + 1], nodes[:, hop + 1]] + _, result = generate_rows(model, query, device, separator) + calls[:, hop] = result["generated"] + current = result["generated"][:, 0] + formats = (calls[:, :, 1] == EOS).all(axis=1) + autonomous_correct = formats & (current == rows[:, -1]) + path_correct = formats & (calls[:, :, 0] == nodes[:, 1:]).all(axis=1) + task_metrics.update( + { + "atomic_correct_coverage": _mean(coverage), + "conditional_accuracy": _mean(direct["correct"][coverage]), + "autonomous_two_calls": _mean(autonomous_correct), + "autonomous_path_accuracy": _mean(path_correct), + "hop_count": hops, + } + ) + metrics[name] = task_metrics + direct.update( + { + "coverage": coverage, + "autonomous_generated": calls, + "autonomous_correct": autonomous_correct, + "autonomous_path_correct": path_correct, + } + ) + predictions.update({name + "_" + key: value for key, value in direct.items()}) + finally: + model.train(before) + return metrics, predictions + + +def _validate_spec(spec): + nodes = spec["nodes"] + if nodes != sorted(set(nodes)) or nodes[0] != 0 or nodes[-1] != spec["steps"]: + raise ValueError("Nodes must increase from initialization to the fixed endpoint") + if not set(spec["checkpoint_nodes"]) <= set(nodes) or not {0, spec["steps"]} <= set( + spec["checkpoint_nodes"] + ): + raise ValueError("Checkpoint nodes must include initialization and endpoint") + if spec["batch_size"] != 128 or spec.get("dropout", 0.0) != 0.0: + raise ValueError("The fixed design requires four 32-example streams and dropout zero") + if spec.get("model_initialization", "scaled_effective") != "scaled_effective": + raise ValueError("The batch uses scaled_effective residual initialization") + + +def _save_world(out, world): + np.savez_compressed(out / "world.npz", **{key: world[key] for key in EVALUATION_SPLITS}) + write_json(out / "world-metadata.json", world["metadata"]) + + +def _check_source(source): + if not source or any(file_hash(path) != digest for path, digest in source.items()): + raise RuntimeError("Actual source differs from the required frozen source hashes") + + +def _validate_output(out): + """Permit scheduler control files while preserving every existing experiment artifact.""" + out = Path(out) + if out.exists(): + for path in out.iterdir(): + allowed = path.is_file() and ( + path.name == "input-spec.json" or path.name.endswith("-process.log") + ) + if not allowed: + raise FileExistsError( + "Do not overwrite an existing experiment artifact: " + str(path) + ) + + +def train(spec, out, source, device="cuda:0"): + _validate_spec(spec) + _check_source(source) + if "frozen_data_sha256" not in spec: + raise ValueError("Training requires frozen_data_sha256") + out = Path(out) + _validate_output(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(torch.device(device)) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + started_process = time.perf_counter() + world = build_world(spec) + digest = data_digest(world) + _save_world(out, world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_digest = model_digest(model) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + strata = [world[name] for name in TRAIN_SPLITS] + sizes = [len(rows) for rows in strata] + if any(size == 0 for size in sizes): + raise ValueError("Do not reroll a world with an empty sampled training stratum") + packed = [pack_rows(rows, separator=world["metadata"]["separator_token"]) for rows in strata] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True) + ) + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + graph = FullTokenStep(model, optimizer, table, spec["batch_size"], clip=spec.get("clip", 1.0)) + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 8, output_positions=8) + token_step = 32 * sum(int((labels[0] >= 0).sum()) for _, labels in packed) + history, step, training_seconds = [], 0, 0.0 + + def measure(loss=None): + metrics, predictions = evaluate(model, world, device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0.0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + np.savez_compressed( + out / f"exposures-{step:06d}.npz", + **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, + ) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["checkpoint_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"model-{step:06d}.pt", + ) + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["atomic"]["accuracy"], + "familiar": {str(hop): metrics[f"familiar_{hop}"]["accuracy"] for hop in HOPS}, + } + ), + flush=True, + ) + return row + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize() + started = time.perf_counter() + while step < end: + updates = min(128, end - step) + indices = [] + for i, stream in enumerate(streams): + draws = stream.take(updates * 32).reshape(updates, 32) + counts[i] += np.bincount(draws.ravel(), minlength=sizes[i]) + indices.append(draws + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(updates): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += updates + torch.cuda.synchronize() + training_seconds += time.perf_counter() - started + loss_value = float(loss) + if not np.isfinite(loss_value): + raise FloatingPointError("Nonfinite loss at step " + str(step)) + endpoint = measure(loss_value) + np.savez_compressed( + out / "exposures.npz", + **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, + ) + result = { + "spec": spec, + "source": source, + "data_sha256": digest, + "initial_model_sha256": initial_digest, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "strata_counts": dict(zip(TRAIN_SPLITS, sizes, strict=True)), + "endpoint": endpoint, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + "estimated_training_flops": step * flop_step, + "training_seconds": training_seconds, + "process_seconds": time.perf_counter() - started_process, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device), + "tf32": True, + }, + } + write_json(out / "complete.json", result) + return result + + +def compare_metrics(actual, expected): + if set(actual) != set(expected): + raise AssertionError("Metric task keys differ") + for task, values in actual.items(): + if set(values) != set(expected[task]): + raise AssertionError("Metric field keys differ") + for key, value in values.items(): + if key == "answer_nll" and value is not None: + np.testing.assert_allclose(value, expected[task][key], rtol=1e-5, atol=1e-5) + elif value != expected[task][key]: + raise AssertionError(f"Saved metric differs: {task}.{key}") + + +def compare_predictions(actual, path): + maximum = 0.0 + with np.load(path) as saved: + if set(actual) != set(saved.files): + raise AssertionError("Prediction keys differ") + for key, value in actual.items(): + if key.endswith("answer_nll"): + np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) + if value.size: + maximum = max(maximum, float(np.abs(value - saved[key]).max())) + else: + np.testing.assert_array_equal(value, saved[key]) + return maximum + + +def audit(out, device="cuda:0"): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(torch.device(device)) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + result = json.loads((out / "complete.json").read_text()) + recorded = json.loads((out / "spec.json").read_text()) + source, spec = result["source"], result["spec"] + _check_source(source) + _validate_spec(spec) + if recorded["spec"] != spec or recorded["source"] != source: + raise AssertionError("Recorded specification/source differ") + if file_hash(out / "latest.pt") != result["checkpoint_sha256"]: + raise AssertionError("Latest checkpoint hash differs") + world = build_world(spec) + digest = data_digest(world) + if digest != result["data_sha256"] or digest != recorded["data_sha256"]: + raise AssertionError("Rebuilt data differ from records") + if json.loads((out / "world-metadata.json").read_text()) != world["metadata"]: + raise AssertionError("Archived world metadata differ") + with np.load(out / "world.npz") as archived: + if set(archived.files) != set(EVALUATION_SPLITS): + raise AssertionError("Archived world keys differ") + for name in EVALUATION_SPLITS: + np.testing.assert_array_equal(archived[name], world[name]) + model = construct(spec, device) + if model_digest(model) != result["initial_model_sha256"]: + raise AssertionError("Paired initialization differs") + history = json.loads((out / "learning.json").read_text()) + if [row["step"] for row in history] != spec["nodes"]: + raise AssertionError("Recorded learning nodes differ") + by_node = {row["step"]: row for row in history} + if by_node[spec["steps"]] != result["endpoint"]: + raise AssertionError("Endpoint differs from the learning curve") + maximum = 0.0 + for node in spec["checkpoint_nodes"]: + checkpoint = torch.load( + out / f"model-{node:06d}.pt", map_location=device, weights_only=False + ) + if checkpoint["spec"] != spec or checkpoint["step"] != node: + raise AssertionError("Checkpoint specification/node differ") + model.load_state_dict(checkpoint["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, by_node[node]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{node:06d}.npz") + ) + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if ( + saved["spec"] != spec + or saved["source"] != source + or saved["step"] != spec["steps"] + or saved["data_sha256"] != digest + ): + raise AssertionError("Latest state identity differs") + sizes = [len(world[name]) for name in TRAIN_SPLITS] + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + previous = 0 + for node in spec["nodes"]: + for i, stream in enumerate(streams): + draws = ( + stream.take((node - previous) * 32) + if node > previous + else np.empty(0, dtype=np.int64) + ) + counts[i] += np.bincount(draws, minlength=sizes[i]) + with np.load(out / f"exposures-{node:06d}.npz") as actual: + for name, count in zip(TRAIN_SPLITS, counts, strict=True): + np.testing.assert_array_equal(actual[name], count) + previous = node + with np.load(out / "exposures.npz") as actual: + for i, (name, count) in enumerate(zip(TRAIN_SPLITS, counts, strict=True)): + np.testing.assert_array_equal(actual[name], count) + np.testing.assert_array_equal(saved["counts"][i], count) + if count.sum() != spec["steps"] * 32 or np.ptp(count) > 1: + raise AssertionError("EpochStream actual exposures are unbalanced") + stream = EpochStream(sizes[i], spec["stream_seed"] + i) + stream.load_state_dict(saved["streams"][i]) + np.testing.assert_array_equal(stream.take(32), streams[i].take(32)) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, result["endpoint"]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{spec['steps']:06d}.npz") + ) + checked = { + "passed": True, + "dataset_rebuilt_and_archived_exact": True, + "initial_model_exact": True, + "checkpoint_nodes": spec["checkpoint_nodes"], + "endpoint_tokens_exact": True, + "all_nodes_exposure_counters_exact": True, + "stream_state_continuation_exact": True, + "max_nll_difference": maximum, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "utc": utc(), + } + write_json(out / "audit.json", checked) + return checked diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..fc14c085184dc030670f1eea92655b73d0eec7c8 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py @@ -0,0 +1,371 @@ +"""Answer-only MLP editing calibration with frozen parent-logit regularization. + +This development grid changes the editor objective and learning rate, preserving +the completed v1 experiment. KL on a finite replay set is a regularizer, not an +exact preservation constraint. Kdev checks the operation; U never selects it. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import EOS, pack_rows +from .depth_step import SOURCE_FILES as TRAIN_SOURCES +from .depth_step_mechanism import edit_cases, generate +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import file_hash + +SOURCE_FILES = list( + dict.fromkeys( + [ + *TRAIN_SOURCES, + "src/llm_memory_editability/depth_step_mechanism.py", + "src/llm_memory_editability/depth_step_edit_calibration.py", + "scripts/calibrate_depth_step_edit.py", + "tests/test_depth_step_edit_calibration.py", + ] + ) +) +PARAMETER = "blocks.0.mlp.down.weight" +NODES = (0, 20, 100, 200) +LEARNING_RATES = (0.0001, 0.001, 0.003) + + +def _array_hash(array): + array = np.asarray(array) + digest = hashlib.sha256(str(array.dtype).encode()) + digest.update(np.asarray(array.shape, dtype="answer and teacher-forced answer->EOS supervision.""" + rows = np.asarray(rows, dtype=np.int64) + tokens, labels = pack_rows(rows, separator=world["metadata"]["separator_token"]) + positions = np.tile([rows.shape[1], rows.shape[1] + 1], (len(rows), 1)) + batch_indices = np.arange(len(rows))[:, None] + selected = labels[batch_indices, positions] + if not np.array_equal(selected, np.c_[rows[:, -1], np.full(len(rows), EOS)]): + raise ValueError("Answer/EOS positions disagree with the packed sequence") + return tuple(torch.as_tensor(value, device=device) for value in (tokens, positions, selected)) + + +def answer_eos_logits(model, batch): + tokens, positions, _labels = batch + return model(tokens, positions=positions) + + +def target_and_replay_loss(model, target_batch, replay_batch, parent_log_probabilities): + """CE only on two factual-output tokens; KL(parent || edited), equally weighted.""" + if parent_log_probabilities.requires_grad: + raise ValueError("Parent logits must be detached") + target_logits = answer_eos_logits(model, target_batch) + ce = F.cross_entropy(target_logits.flatten(0, 1), target_batch[2].flatten()) + replay_log = answer_eos_logits(model, replay_batch).log_softmax(-1) + kl = F.kl_div( + replay_log.flatten(0, 1), + parent_log_probabilities.flatten(0, 1), + reduction="batchmean", + log_target=True, + ) + return ce + kl, ce, kl + + +def _measure(model, case, world, device, step): + metrics, raw = {}, {} + for name, rows in case["tasks"].items(): + values, predictions = generate(model, rows, world, device) + if name in case["original_d_rows"]: + original = case["original_d_rows"][name] + changed = rows[:, -1] != original[:, -1] + predicted = predictions["predictions"] + correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) + old_correct = (predicted[:, 0] == original[:, -1]) & (predicted[:, 1] == EOS) + values.update( + { + "changed_answer_n": int(changed.sum()), + "changed_answer_coverage": float(changed.mean()) if len(rows) else None, + "changed_answer_accuracy": float(correct[changed].mean()) + if changed.any() + else None, + "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None, + } + ) + metrics[name] = values + raw.update({f"step{step}_{name}_{key}": value for key, value in predictions.items()}) + return metrics, raw + + +def calibrated_edit_one(model, case, world, device, arm, lr, nodes=NODES): + """One independently initialized branch, with fixed parent KL reference.""" + if arm not in {"edit", "review"}: + raise ValueError("Arm must be edit or review") + if tuple(nodes) != tuple(sorted(set(nodes))) or not nodes or nodes[0] != 0: + raise ValueError("Nodes must increase from zero") + parent_hash = model_digest(model) + edited = copy.deepcopy(model).eval() + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == PARAMETER) + parameter.grad = None + before = {name: value.detach().clone() for name, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[PARAMETER] + optimizer = torch.optim.Adam([parameter], lr=lr) + target_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) + target_batch = answer_eos_batch(target_rows, world, device) + replay_batch = answer_eos_batch(case["tasks"]["R_atomic"], world, device) + with torch.no_grad(): + parent_log = answer_eos_logits(model, replay_batch).log_softmax(-1).detach() + raw = { + "parent_replay_log_probabilities": parent_log.cpu().numpy(), + "replay_teacherforced_labels": replay_batch[2].cpu().numpy(), + } + for name, old_rows in case["original_d_rows"].items(): + raw[name + "_original_rows"] = old_rows + raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] + step, history, loss_values = 0, [], None + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, ce, kl = target_and_replay_loss(edited, target_batch, replay_batch, parent_log) + loss.backward() + optimizer.step() + step += 1 + loss_values = { + "total": float(loss.detach()), + "target_ce": float(ce.detach()), + "replay_kl": float(kl.detach()), + } + metrics, predictions = _measure(edited, case, world, device, step) + raw.update(predictions) + target_name = "E_new" if arm == "edit" else "E_old" + keep_pass = metrics["Kdev_atomic"]["accuracy"] >= 0.95 + target_pass = metrics[target_name]["accuracy"] == 1.0 + history.append( + { + "step": step, + "loss": loss_values, + "metrics": metrics, + "Kdev_at_least_95_percent": keep_pass, + "target_atomic_success": target_pass, + "calibration_operation_pass": keep_pass and target_pass, + } + ) + changed = [ + name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) + ] + if set(changed) - {PARAMETER}: + raise ValueError("A frozen state tensor changed") + if model_digest(model) != parent_hash: + raise ValueError("Original checkpoint model changed") + delta = parameter.detach() - before[PARAMETER] + raw["mlp_down_weight_delta"] = delta.cpu().numpy() + record = { + "arm": arm, + "lr": lr, + "atomic_index": case["atomic_index"], + "old_fact": case["old_fact"], + "new_fact": case["new_fact"], + "replay_indices": case["replay_indices"], + "keep_dev_indices": case["keep_dev_indices"], + "unused_atomic_indices": case["unused_atomic_indices"], + "parent_model_sha256": parent_hash, + "final_model_sha256": model_digest(edited), + "initial_down_weight_sha256": _array_hash(before[PARAMETER].cpu().numpy()), + "final_down_weight_sha256": _array_hash(parameter.detach().cpu().numpy()), + "updated_parameter": PARAMETER, + "changed_state_tensors": changed, + "weight_delta_l2": float(delta.norm()), + "history": history, + } + return record, raw + + +def prepare_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): + """Freeze data, all arms, sources, and initial weights before any model inference.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + if any(lr <= 0 or not np.isfinite(lr) for lr in learning_rates): + raise ValueError("Invalid learning rate") + cases, remaining = calibration_cases(world, n_cases=n_cases) + serialized = [] + for case in cases: + entry = { + key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"} + } + entry["task_rows"] = {key: value.tolist() for key, value in case["tasks"].items()} + entry["task_sha256"] = {key: _array_hash(value) for key, value in case["tasks"].items()} + entry["original_d_rows"] = { + key: value.tolist() for key, value in case["original_d_rows"].items() + } + serialized.append(entry) + config = { + "phase": "development_calibration", + "created_utc": utc(), + "source_checkpoint": source, + "source": {path: file_hash(path) for path in SOURCE_FILES}, + "parent_model_sha256": model_digest(model), + "initial_down_weight_sha256": _array_hash( + model.blocks[0].mlp.down.weight.detach().cpu().numpy() + ), + "learning_rates": list(learning_rates), + "nodes": list(NODES), + "cases": serialized, + "n_cases": n_cases, + "matrix": [ + {"case": i, "lr": lr, "arm": arm} + for i in range(n_cases) + for lr in learning_rates + for arm in ("edit", "review") + ], + "reserved_original_case_indices": remaining, + "reserved_cases_are_independent_world_confirmation": False, + "optimizer": "Adam, no weight decay", + "parameter": PARAMETER, + "objective": "target answer/EOS CE + KL(parent || edited) on 32 replay answer/EOS logits", + "replay_kl_weight": 1.0, + "supervised_prefix_tokens": 0, + "trained_compositions": 0, + "Kdev_selection": "First 32 lexicographic atoms excluding E, R, necessary successors", + "Kdev_threshold": 0.95, + "U_selection": "All remaining atomic facts, including unused necessary successors", + "U_or_D_select_editor": False, + "all_grid_failures_retained": True, + "executions_affected_by_shared_edit": model.repeats, + "limits": [ + "Finite replay KL is not strict output preservation", + "A successful Kdev check does not establish unobserved U preservation", + "Cases share one development world and original checkpoints", + ], + } + write_json(out / "calibration-config.json", config) + return config, cases + + +def load_prepared_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): + """Validate an existing prepared configuration, without rewriting it.""" + out = Path(out) + config_file = out / "calibration-config.json" + config = json.loads(config_file.read_text()) + if any(path.name != config_file.name for path in out.iterdir()): + raise FileExistsError("Existing branch artifacts prevent a repeated execution") + if config["learning_rates"] != list(learning_rates) or config["n_cases"] != n_cases: + raise ValueError("Requested grid differs from prepared calibration") + expected_source = config["source_checkpoint"] + for key in ("checkpoint_sha256", "dataset_sha256", "step", "spec"): + if source[key] != expected_source[key]: + raise ValueError("Checkpoint or data differ from prepared calibration: " + key) + if model_digest(model) != config["parent_model_sha256"]: + raise ValueError("Parent parameter hash differs from prepared calibration") + expected_matrix = [ + {"case": i, "lr": lr, "arm": arm} + for i in range(n_cases) + for lr in learning_rates + for arm in ("edit", "review") + ] + if config["matrix"] != expected_matrix or config["nodes"] != list(NODES): + raise ValueError("Prepared update matrix or nodes changed") + if ( + config["parameter"] != PARAMETER + or config["replay_kl_weight"] != 1.0 + or config["Kdev_threshold"] != 0.95 + or config["U_or_D_select_editor"] + ): + raise ValueError("Prepared operation contract changed") + cases, remaining = calibration_cases(world, n_cases=n_cases) + if remaining != config["reserved_original_case_indices"]: + raise ValueError("Reserved cases changed") + for case, frozen in zip(cases, config["cases"], strict=True): + for key in ( + "atomic_index", + "old_fact", + "new_fact", + "replay_indices", + "keep_dev_indices", + "unused_atomic_indices", + "propagation_scope", + ): + if case[key] != frozen[key]: + raise ValueError("Case selection changed: " + key) + if set(case["tasks"]) != set(frozen["task_rows"]): + raise ValueError("Prepared task set changed") + for name, rows in case["tasks"].items(): + if ( + rows.tolist() != frozen["task_rows"][name] + or _array_hash(rows) != frozen["task_sha256"][name] + ): + raise ValueError("Prepared task rows changed: " + name) + for name, rows in case["original_d_rows"].items(): + if rows.tolist() != frozen["original_d_rows"][name]: + raise ValueError("Prepared original D labels changed") + for path, expected in config["source"].items(): + if file_hash(path) != expected: + raise ValueError("Source changed after calibration freeze: " + path) + return config, cases + + +def execute_calibration(model, world, config, cases, out, device): + out = Path(out) + if model_digest(model) != config["parent_model_sha256"]: + raise ValueError("Parent parameter hash differs from frozen configuration") + for path, expected in config["source"].items(): + if file_hash(path) != expected: + raise ValueError("Source changed after calibration freeze: " + path) + for case, expected in zip(cases, config["cases"], strict=True): + for name, rows in case["tasks"].items(): + if _array_hash(rows) != expected["task_sha256"][name]: + raise ValueError("Task rows changed after freeze: " + name) + started = time.perf_counter() + records = [] + for item in config["matrix"]: + number, lr, arm = item["case"], item["lr"], item["arm"] + record, raw = calibrated_edit_one( + model, cases[number], world, device, arm, lr, nodes=tuple(config["nodes"]) + ) + label = f"case{number:02d}-lr{lr:.4f}-{arm}" + np.savez_compressed(out / (label + "-raw.npz"), **raw) + write_json(out / (label + ".json"), record) + records.append(record) + print(f"Calibration branch completed: {label}", flush=True) + report = { + "phase": "development_calibration", + "records": records, + "config_sha256": file_hash(out / "calibration-config.json"), + "completed_branches": len(records), + "wall_seconds": time.perf_counter() - started, + "model_selection_by_U_or_D": False, + } + write_json(out / "calibration-summary.json", report) + return report diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/depth_step_mechanism.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/depth_step_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb78cafec65ea5b0a4031d27502f7d0c4b00e16 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/depth_step_mechanism.py @@ -0,0 +1,589 @@ +"""Descriptive entity readouts, pure-first-hop interventions and MLP edits. + +No fitted probe or performance predictor is used. Residual readouts and raw MLP +cosines are descriptions; only interventions test a causal contribution. The +truth graph chooses queries, donors and edits before any model is evaluated. +""" + +from __future__ import annotations + +import copy +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import ENTITY_OFFSET, EOS, construct, pack_rows, prompt_rows, truth_path_details +from .grok_depth import utc, write_json +from .storage_composition import file_hash + + +def traced_forward(model, tokens, patches=None): + """Use the real SDPA computation and record every executed block/position. + + Patches map (zero-based execution, 'mlp_delta' or 'postresidual', position) + to a batch of replacement vectors. Repeated executions of a shared block + remain separately indexed. Attention maps are descriptive manual softmax; + the forward uses the same SDPA primitive as LoopGPT. + """ + if model.training: + raise ValueError("Tracing requires evaluation mode") + patches = patches or {} + length = tokens.shape[1] + x = model.token(tokens) + model.position(torch.arange(length, device=tokens.device)) + cache = {key: [] for key in ("attention_map", "attention_delta", "mlp_delta", "postresidual")} + consumed = set() + for index, block in enumerate(model.iter_blocks()): + z = block.ln1(x) + batch, _, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + q, k, v = (part.transpose(1, 2) for part in (q, k, v)) + scores = (q @ k.transpose(-1, -2)) / math.sqrt(width // a.heads) + causal = torch.ones(length, length, device=tokens.device, dtype=torch.bool).tril() + attention_map = scores.masked_fill(~causal, -torch.inf).softmax(-1) + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0.0) + attention_delta = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + attention_delta + mlp_delta = block.mlp(block.ln2(x)) + for key, replacement in patches.items(): + layer, component, position = key + if layer == index and component == "mlp_delta": + if replacement.shape != mlp_delta[:, position].shape: + raise ValueError("Patch shape differs from selected MLP position") + mlp_delta = mlp_delta.clone() + mlp_delta[:, position] = replacement + consumed.add(key) + x = x + mlp_delta + for key, replacement in patches.items(): + layer, component, position = key + if layer == index and component == "postresidual": + if replacement.shape != x[:, position].shape: + raise ValueError("Patch shape differs from selected residual position") + x = x.clone() + x[:, position] = replacement + consumed.add(key) + for key, value in ( + ("attention_map", attention_map), + ("attention_delta", attention_delta), + ("mlp_delta", mlp_delta), + ("postresidual", x), + ): + cache[key].append(value.detach()) + if consumed != set(patches): + raise ValueError("Unknown execution/component in patch") + logits = F.linear(model.ln_final(x), model.token.weight) + return logits, {key: torch.stack(values) for key, values in cache.items()} + + +def _separator(world): + return int(world["metadata"]["separator_token"]) + + +def _mean(values): + return float(np.mean(values)) if len(values) else None + + +@torch.no_grad() +def generate(model, rows, world, device, batch_size=256): + """Free answer then free EOS, retaining full-vocabulary probabilities.""" + rows = np.asarray(rows, dtype=np.int64) + predictions, probabilities, gold_probabilities = [], [], [] + for begin in range(0, len(rows), batch_size): + selected = rows[begin : begin + batch_size] + tokens = torch.as_tensor(prompt_rows(selected, _separator(world)), device=device) + probability = model(tokens)[:, -1].softmax(-1) + answer = probability.argmax(-1) + eos = model(torch.cat((tokens, answer[:, None]), dim=1))[:, -1].argmax(-1) + predictions.append(torch.stack((answer, eos), 1).cpu().numpy()) + probabilities.append(probability.cpu().numpy()) + gold_probabilities.append( + probability[ + torch.arange(len(selected), device=device), + torch.as_tensor(selected[:, -1], device=device), + ] + .cpu() + .numpy() + ) + vocab = model.config.vocab_size + predicted = np.concatenate(predictions) if predictions else np.empty((0, 2), dtype=np.int64) + prob = ( + np.concatenate(probabilities) if probabilities else np.empty((0, vocab), dtype=np.float32) + ) + gold_prob = np.concatenate(gold_probabilities) if gold_probabilities else np.empty(0) + correct = predicted[:, 0] == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": _mean(correct), + "accuracy": _mean(correct & (predicted[:, 1] == EOS)), + "gold_probability": _mean(gold_prob), + }, {"rows": rows, "predictions": predicted, "answer_probabilities": prob} + + +def select_donors(world, rows): + """Lexicographic donors know exactly one fact and no target second relation.""" + atoms = world["atomic"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + nodes, _ = truth_path_details(world, rows) + same, changed, changed_tail = [], [], [] + for row, path in zip(rows, nodes, strict=True): + h, r1, r2, old_tail = map(int, row) + bridge = int(path[1]) + identical = next( + (i for i in order if int(atoms[i, 2]) == bridge and tuple(atoms[i, :2]) != (h, r1)), -1 + ) + different = next( + ( + i + for i in order + if int(atoms[i, 2]) != bridge + and (int(atoms[i, 2]), r2) in lookup + and lookup[(int(atoms[i, 2]), r2)] != old_tail + ), + -1, + ) + same.append(identical) + changed.append(different) + changed_tail.append(lookup[(int(atoms[different, 2]), r2)] if different >= 0 else -1) + return { + "same_bridge_atomic_indices": np.asarray(same, dtype=np.int64), + "different_bridge_atomic_indices": np.asarray(changed, dtype=np.int64), + "different_bridge_tail": np.asarray(changed_tail, dtype=np.int64), + } + + +@torch.no_grad() +def entity_readouts(model, cache, targets, entities): + """Apply the unmodified final norm/tied readout; raw MLP cosine is separate.""" + residual = cache["postresidual"] + logits = F.linear(model.ln_final(residual), model.token.weight) + entity_logits = logits[..., ENTITY_OFFSET : ENTITY_OFFSET + entities] + probabilities = logits.softmax(-1) + entity_probabilities = entity_logits.softmax(-1) + embedding = F.normalize(model.token.weight[ENTITY_OFFSET : ENTITY_OFFSET + entities], dim=-1) + cosine = F.normalize(cache["mlp_delta"], dim=-1) @ embedding.T + arrays = {} + for name, token_ids in targets.items(): + ids = torch.as_tensor(token_ids, device=residual.device) + full_ids = ids[None, :, None, None].expand(*residual.shape[:-1], 1) + entity_ids = full_ids - ENTITY_OFFSET + gold_logit = entity_logits.gather(-1, entity_ids).squeeze(-1) + gold_cosine = cosine.gather(-1, entity_ids).squeeze(-1) + arrays[name + "_residual_entity_rank"] = 1 + (entity_logits > gold_logit[..., None]).sum(-1) + arrays[name + "_residual_vocab_probability"] = probabilities.gather(-1, full_ids).squeeze( + -1 + ) + arrays[name + "_residual_entity_probability"] = entity_probabilities.gather( + -1, entity_ids + ).squeeze(-1) + arrays[name + "_mlp_embedding_cosine"] = gold_cosine + arrays[name + "_mlp_embedding_cosine_rank"] = 1 + (cosine > gold_cosine[..., None]).sum(-1) + return {name: value.cpu().numpy() for name, value in arrays.items()} + + +@torch.no_grad() +def _patched_generation(model, tokens, patch): + logits, _ = traced_forward(model, tokens, patch) + probability = logits[:, -1].softmax(-1) + answer = probability.argmax(-1) + # Reapply the same intervention while freely generating the EOS token. + extended = torch.cat((tokens, answer[:, None]), dim=1) + eos_logits, _ = traced_forward(model, extended, patch) + eos = eos_logits[:, -1].argmax(-1) + return torch.stack((answer, eos), 1).cpu().numpy(), probability.cpu().numpy() + + +def trace_analysis(model, world, out, device, max_queries=128): + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + model.eval() + started = time.perf_counter() + raw, baseline = {}, {} + for split in ("atomic", "familiar_2", "strict_2"): + metrics, prediction = generate(model, world[split], world, device) + baseline[split] = metrics + raw.update({f"baseline_{split}_{key}": value for key, value in prediction.items()}) + indices = np.arange(min(max_queries, len(world["familiar_2"]))) + rows = world["familiar_2"][indices] + nodes, edges = truth_path_details(world, rows) + tokens = torch.as_tensor(prompt_rows(rows, _separator(world)), device=device) + with torch.no_grad(): + reference = model(tokens) + actual, cache = traced_forward(model, tokens) + difference = float((actual - reference).abs().max()) + torch.testing.assert_close(actual, reference, rtol=1e-5, atol=2e-6) + if not torch.equal(actual.argmax(-1), reference.argmax(-1)): + raise ValueError("Traced forward changes full-vocabulary argmax") + raw.update( + { + "query_indices": indices, + "query_rows": rows, + "truth_nodes": nodes, + "truth_atomic_indices": edges, + } + ) + raw.update({"cache_" + key: value.cpu().numpy() for key, value in cache.items()}) + raw.update( + entity_readouts( + model, + cache, + {"bridge": nodes[:, 1], "tail": nodes[:, -1]}, + world["metadata"]["entities"], + ) + ) + donors = select_donors(world, rows) + raw.update(donors) + atom_predictions = raw["baseline_atomic_predictions"] + atoms = world["atomic"] + atom_correct = (atom_predictions[:, 0] == atoms[:, -1]) & (atom_predictions[:, 1] == EOS) + atomic_key_indices = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)} + raw["original_constituent_atoms_correct"] = atom_correct[edges].all(1) + records = [] + for style in ("self", "same_bridge", "different_bridge"): + donor_ids = edges[:, 0] if style == "self" else donors[style + "_atomic_indices"] + valid = donor_ids >= 0 + selected = np.flatnonzero(valid) + if not len(selected): + continue + donor_rows = world["atomic"][donor_ids[valid]] + donor_tokens = torch.as_tensor(prompt_rows(donor_rows, _separator(world)), device=device) + with torch.no_grad(): + _, donor_cache = traced_forward(model, donor_tokens) + expected = ( + donors["different_bridge_tail"][valid] + if style == "different_bridge" + else rows[valid, -1] + ) + new_second_indices = np.asarray( + [ + atomic_key_indices[(int(donor[2]), int(query[2]))] + for donor, query in zip(donor_rows, rows[valid], strict=True) + ] + ) + premises = ( + atom_correct[edges[valid]].all(1) + & atom_correct[donor_ids[valid]] + & atom_correct[new_second_indices] + ) + raw[style + "_premises_correct"] = premises + for layer in range(model.effective_depth): + for component in ("mlp_delta", "postresidual"): + for position in (2, 1): + key = f"{style}_layer{layer}_{component}_pos{position}" + patch = { + (layer, component, position): donor_cache[component][layer, :, position] + } + prediction, probability = _patched_generation(model, tokens[valid], patch) + raw[key + "_selected_query_indices"] = selected + raw[key + "_predictions"] = prediction + raw[key + "_answer_probabilities"] = probability + following = prediction[:, 0] == expected + correct = prediction[:, 0] == rows[valid, -1] + base_pred = raw["baseline_familiar_2_predictions"][indices[valid]] + base_correct = (base_pred[:, 0] == rows[valid, -1]) & (base_pred[:, 1] == EOS) + if style == "self" and not np.array_equal(prediction, base_pred): + raise ValueError("Pure-first-hop self patch changes generation") + record = { + "donor": style, + "execution": layer, + "component": component, + "position": position, + "n": len(selected), + "selected_query_coverage": len(selected) / len(rows), + "full_pool_coverage": len(selected) / len(world["familiar_2"]), + "new_route_answer_accuracy": _mean(following), + "new_route_accuracy": _mean(following & (prediction[:, 1] == EOS)), + "original_accuracy": _mean(correct & (prediction[:, 1] == EOS)), + "baseline_correct_coverage": _mean(base_correct), + "all_required_atomic_correct_coverage": _mean(premises), + "new_route_conditional_on_required_atomics": _mean( + (following & (prediction[:, 1] == EOS))[premises] + ), + "new_route_conditional_on_baseline_correct": _mean( + (following & (prediction[:, 1] == EOS))[base_correct] + ), + } + records.append(record) + with torch.no_grad(): + entity_embedding = model.token.weight[ + ENTITY_OFFSET : ENTITY_OFFSET + world["metadata"]["entities"] + ] + normalized = F.normalize(entity_embedding, dim=-1) + raw["entity_embedding_cosine_matrix"] = (normalized @ normalized.T).cpu().numpy() + raw["entity_embedding_singular_values"] = ( + torch.linalg.svdvals(entity_embedding).cpu().numpy() + ) + np.savez_compressed(out / "trace-raw.npz", **raw) + report = { + "phase": "development", + "created_utc": utc(), + "baseline": baseline, + "query_selection": ( + "First 128 familiar_2 rows in frozen data order, independent of predictions" + ), + "selected_queries": len(rows), + "full_pool_queries": len(world["familiar_2"]), + "selection_coverage": len(rows) / len(world["familiar_2"]), + "forward_max_absolute_difference": difference, + "forward_all_argmax_identical": True, + "donor_information": ( + "Only BOS, head, first relation, SEP; no second relation or final answer" + ), + "patch_position_roles": {"1": "head control", "2": "first relation"}, + "interventions": records, + "wall_seconds": time.perf_counter() - started, + "limits": [ + "Unfitted final-norm tied readout and raw cosine are descriptive", + "Attention maps are descriptive; patch tests entire state or MLP contribution", + "Layers, positions and queries are dependent measurements in one world", + ], + } + write_json(out / "trace-summary.json", report) + return report + + +def edit_cases(world, n_facts=8, replay_n=32): + """Choose graph-based first-hop edits before observing any model behavior.""" + atoms = world["atomic"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + candidate_first = {(int(row[0]), int(row[1])) for row in world["familiar_2"]} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + cases = [] + for index in order: + h, relation, old_bridge = map(int, atoms[index]) + if (h, relation) not in candidate_first: + continue + first_rows = world["familiar_2"][ + (world["familiar_2"][:, 0] == h) & (world["familiar_2"][:, 1] == relation) + ] + bridges = sorted({int(t) for _, _, t in atoms}) + new_bridge = next( + ( + b + for b in bridges + if b != old_bridge + and all( + (b, int(row[2])) in lookup and lookup[(b, int(row[2]))] != int(row[-1]) + for row in first_rows + ) + ), + None, + ) + if new_bridge is None: + continue + replay_indices = np.asarray([i for i in order if i != index][:replay_n]) + if len(replay_indices) != replay_n: + raise ValueError("Insufficient nonedited replay atoms") + new_fact = np.asarray([[h, relation, new_bridge]], dtype=np.int64) + old_fact = atoms[index : index + 1].copy() + edited_lookup = {**lookup, (h, relation): new_bridge} + tasks = {"E_new": new_fact, "E_old": old_fact, "R_atomic": atoms[replay_indices].copy()} + original_d_rows = {} + unreplayed = [i for i in range(len(atoms)) if i != index and i not in replay_indices] + tasks["U_atomic"] = atoms[unreplayed].copy() + successor_keys = set() + for split in ("familiar_2", "strict_2"): + rows = world[split] + nodes, path_indices = truth_path_details(world, rows) + first = path_indices[:, 0] == index + second = (path_indices[:, 1] == index) & ~first + unaffected = ~(first | second) + for role, mask in (("first", first), ("second", second)): + changed = rows[mask].copy() + for i, row in enumerate(changed): + bridge = edited_lookup[(int(row[0]), int(row[1]))] + changed[i, -1] = edited_lookup[(bridge, int(row[2]))] + if role == "first" and (bridge, int(row[2])) != (h, relation): + successor_keys.add((bridge, int(row[2]))) + tasks[f"D_{role}_{split}"] = changed + original_d_rows[f"D_{role}_{split}"] = rows[mask].copy() + tasks["U_" + split] = rows[unaffected].copy() + # All facts occurring as either hop in U retain their graph labels. + if index in path_indices[unaffected]: + raise ValueError("Edited fact leaked into the unaffected holdout") + del nodes + successor_indices = [i for i, row in enumerate(atoms) if tuple(row[:2]) in successor_keys] + tasks["necessary_successor_atomic"] = atoms[successor_indices].copy() + cases.append( + { + "atomic_index": index, + "old_fact": old_fact[0].tolist(), + "new_fact": new_fact[0].tolist(), + "replay_indices": replay_indices.tolist(), + "tasks": tasks, + "original_d_rows": original_d_rows, + "propagation_scope": { + name: { + "n": len(old_rows), + "changed_answer_n": int( + np.count_nonzero(tasks[name][:, -1] != old_rows[:, -1]) + ), + "source_pool_n": len(world[name.split("_", 2)[2]]), + } + for name, old_rows in original_d_rows.items() + }, + } + ) + if len(cases) == n_facts: + break + if len(cases) != n_facts: + raise ValueError("Fewer graph-valid fixed edit cases than requested") + return cases + + +def _atomic_loss(model, rows, world, device): + tokens, labels = pack_rows(rows, separator=_separator(world)) + tokens = torch.as_tensor(tokens, device=device) + labels = torch.as_tensor(labels, device=device) + logits = model(tokens) + return F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + + +def edit_one(model, case, world, device, arm, nodes=(0, 20, 100, 200), lr=0.01): + """Independently edit one checkpoint; only unique block-0 MLP down changes.""" + if arm not in {"edit", "review"}: + raise ValueError("Arm must be edit or review") + if tuple(nodes) != tuple(sorted(set(nodes))) or nodes[0] != 0: + raise ValueError("Nodes must be increasing with initial measurement") + edited = copy.deepcopy(model).eval() + target_name = "blocks.0.mlp.down.weight" + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == target_name) + parameter.grad = None + before = {name: value.detach().clone() for name, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[target_name] + optimizer = torch.optim.Adam([parameter], lr=lr) + objective_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) + history, raw = [], {} + for name, old_rows in case["original_d_rows"].items(): + raw[name + "_original_rows"] = old_rows + raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] + step = 0 + final_loss = None + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + loss = 0.5 * _atomic_loss(edited, objective_rows, world, device) + loss = loss + 0.5 * _atomic_loss(edited, case["tasks"]["R_atomic"], world, device) + loss.backward() + optimizer.step() + step += 1 + final_loss = float(loss.detach()) + measures = {} + for name, rows in case["tasks"].items(): + metrics, prediction = generate(edited, rows, world, device) + if name in case["original_d_rows"]: + old_rows = case["original_d_rows"][name] + changed_mask = rows[:, -1] != old_rows[:, -1] + predicted = prediction["predictions"] + correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) + old_correct = (predicted[:, 0] == old_rows[:, -1]) & (predicted[:, 1] == EOS) + metrics.update( + { + "changed_answer_n": int(changed_mask.sum()), + "changed_answer_coverage": _mean(changed_mask), + "changed_answer_accuracy": _mean(correct[changed_mask]), + "old_answer_accuracy": _mean(old_correct), + } + ) + measures[name] = metrics + raw.update({f"step{step}_{name}_{key}": value for key, value in prediction.items()}) + history.append({"step": step, "loss": final_loss, "metrics": measures}) + changed = [ + name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) + ] + if set(changed) - {target_name}: + raise ValueError("Parameters outside the frozen MLP projection changed") + delta = parameter.detach() - before[target_name] + raw["mlp_down_weight_delta"] = delta.cpu().numpy() + return { + "arm": arm, + "atomic_index": case["atomic_index"], + "old_fact": case["old_fact"], + "new_fact": case["new_fact"], + "replay_indices": case["replay_indices"], + "propagation_scope": case["propagation_scope"], + "updated_parameter": target_name, + "changed_state_tensors": changed, + "weight_delta_l2": float(delta.norm()), + "history": history, + }, raw + + +def edit_analysis(model, world, out, device, n_facts=8, nodes=(0, 20, 100, 200), lr=0.01): + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + started = time.perf_counter() + cases = edit_cases(world, n_facts=n_facts) + serializable_cases = [ + {key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"}} + | {"task_sizes": {key: len(rows) for key, rows in case["tasks"].items()}} + for case in cases + ] + # This is written before evaluating or updating any case. + write_json(out / "data-selected-edit-cases.json", serializable_cases) + records = [] + for number, case in enumerate(cases): + for arm in ("edit", "review"): + record, raw = edit_one(model, case, world, device, arm, nodes=nodes, lr=lr) + np.savez_compressed(out / f"case{number:02d}-{arm}-raw.npz", **raw) + write_json(out / f"case{number:02d}-{arm}.json", record) + records.append(record) + report = { + "phase": "development", + "created_utc": utc(), + "n_facts": n_facts, + "nodes": list(nodes), + "lr": lr, + "optimizer": "Adam, no weight decay", + "objective": "0.5 target atomic full-token CE + 0.5 fixed 32-atomic replay full-token CE", + "trained_compositions": 0, + "unique_block_edited": 0, + "executions_affected_by_shared_edit": model.repeats, + "independent_layers": len(model.blocks), + "execution_depth": model.effective_depth, + "scope_difference": ( + "Loop block-0 update applies at every repeat; ordinary block-0 applies once" + ), + "records": records, + "wall_seconds": time.perf_counter() - started, + "limits": [ + "Edits use the same fixed budget; failed target changes remain in results", + "MLP-only parameter fine-tuning is not a constrained-preservation theorem", + "Each case independently starts from the same checkpoint", + "A single development world is not independent confirmation", + ], + } + write_json(out / "edit-summary.json", report) + return report + + +def load_run(run_dir, checkpoint, device): + run_dir, checkpoint = Path(run_dir), Path(checkpoint) + saved = torch.load(checkpoint, map_location=device, weights_only=False) + model = construct(saved["spec"], device).eval() + model.load_state_dict(saved["model"], strict=True) + arrays = np.load(run_dir / "world.npz", allow_pickle=False) + world = {key: arrays[key] for key in arrays.files} + world["metadata"] = json.loads((run_dir / "world-metadata.json").read_text()) + from .depth_step import audit_world + + audit = audit_world(world) + if audit["dataset_sha256"] != saved["spec"].get("frozen_data_sha256", audit["dataset_sha256"]): + raise ValueError("Checkpoint and archived data digest disagree") + return ( + model, + world, + { + "checkpoint": str(checkpoint), + "checkpoint_sha256": file_hash(checkpoint), + "step": saved["step"], + "spec": saved["spec"], + "dataset_sha256": audit["dataset_sha256"], + }, + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/experiment_tracking.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/experiment_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..167c8e1a359008fa8b7c89642273e85c9699643e --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/experiment_tracking.py @@ -0,0 +1,298 @@ +"""W&B sidecar for future experiments; reads trainer artifacts without changing training.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import importlib +import json +import math +import os +import subprocess +import sys +import time +from pathlib import Path + +DEFAULTS = Path(__file__).resolve().parents[2] / "configs/experiment-tracking-defaults.json" +PRIVATE_KEYS = { + "api_key", + "wandb_api_key", + "access_token", + "auth_token", + "password", + "credentials", + "secret", +} + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temp.replace(path) + + +def public_config(value): + if isinstance(value, dict): + return {k: public_config(v) for k, v in value.items() if k.lower() not in PRIVATE_KEYS} + if isinstance(value, list): + return [public_config(v) for v in value] + return value + + +def numeric_fields(value, prefix): + result = {} + for key, item in value.items(): + name = f"{prefix}/{key}" + if isinstance(item, dict): + result.update(numeric_fields(item, name)) + elif isinstance(item, int | float) and not isinstance(item, bool) and math.isfinite(item): + result[name] = item + return result + + +def learning_metrics(record, previous=None): + """Keep the actual optimizer step and task denominators; derive interval throughput.""" + result = {"training/step": int(record["step"])} + result.update(numeric_fields(record.get("metrics", {}), "eval")) + groups = { + "training_seconds": "perf/training_seconds", + "wall_seconds": "perf/wall_seconds", + "examples": "exposure/examples", + "supervised_tokens": "exposure/supervised_tokens", + "executed_input_tokens": "compute/executed_input_tokens", + "estimated_matmul_training_flops": "compute/estimated_matmul_training_flops", + "atomic_epochs": "exposure/atomic_epochs", + "composition_epochs": "exposure/composition_epochs", + } + for key, value in record.items(): + if key in {"step", "metrics"}: + continue + if isinstance(value, int | float) and not isinstance(value, bool) and math.isfinite(value): + result[groups.get(key, f"training/{key}")] = value + if previous is not None and record["step"] > previous["step"]: + steps = record["step"] - previous["step"] + if "training_seconds" in record and "training_seconds" in previous: + seconds = record["training_seconds"] - previous["training_seconds"] + if seconds > 0: + result["perf/training_ms_per_update"] = 1000 * seconds / steps + result["perf/updates_per_second"] = steps / seconds + if "examples" in record and "examples" in previous: + result["perf/examples_per_second"] = ( + record["examples"] - previous["examples"] + ) / seconds + return result + + +class ArtifactRunTracker: + def __init__(self, sdk, batch, path, settings): + self.path = Path(path) + self.state_path = Path(batch) / "tracking-wandb" / self.path.name / "state.json" + self.metadata = read_json(self.path / "run.json") + self.settings = settings + identity = { + "batch": Path(batch).name, + "name": self.path.name, + "spec": public_config(self.metadata.get("spec", {})), + "world_sha256": self.metadata.get("world_sha256"), + "initial_model_sha256": self.metadata.get("initial_model_sha256"), + } + fingerprint = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest() + saved = read_json(self.state_path) if self.state_path.exists() else {} + if saved: + assert saved["fingerprint"] == fingerprint, "Source trajectory identity changed" + assert saved["entity"] == settings["entity"] and saved["project"] == settings["project"] + self.state = { + "run_id": fingerprint[:16], + "fingerprint": fingerprint, + "entity": settings["entity"], + "project": settings["project"], + "last_logged_step": -1, + **saved, + } + options = {"disable_git": True} + if not settings["system_metrics"]: + options["x_disable_stats"] = True + else: + if "gpu" in self.metadata: + options["x_stats_gpu_device_ids"] = (self.metadata["gpu"],) + if "pid" in self.metadata: + options["x_stats_pid"] = self.metadata["pid"] + mode = settings["mode"] + run_id = self.state["run_id"] + if mode == "offline" and saved: + segment = saved.get("offline_segment", 0) + 1 + self.state["offline_segment"] = segment + run_id = f"{run_id[:12]}{segment:04x}" + self.state_path.parent.mkdir(parents=True, exist_ok=True) + config = { + **identity, + "scientific_run_id": self.state["run_id"], + **{ + k: self.metadata[k] + for k in [ + "model", + "phase", + "evaluation_nodes", + "execution_lock_sha256", + "parameters", + "vocab_size", + "atomic_examples", + "composition_examples", + "dtype", + "gpu_name", + ] + if k in self.metadata + }, + } + self.run = sdk.init( + entity=settings["entity"], + project=settings["project"], + group=self.metadata.get("tracking_group", Path(batch).name), + name=self.path.name, + id=run_id, + config=config, + mode=mode, + resume="allow" if mode == "online" else None, + job_type=self.metadata.get("job_type", "training"), + tags=self.metadata.get("tags", []), + dir=str(self.state_path.parent), + save_code=False, + reinit="create_new", + settings=sdk.Settings(**options), + ) + self.run.define_metric("training/step") + self.run.define_metric("*", step_metric="training/step") + if mode == "online": + # The public history is authoritative: an SDK restart can briefly report step 0, + # and a local cursor can include points queued before a network interruption. + remote = sdk.Api(timeout=30).run(f"{settings['entity']}/{settings['project']}/{run_id}") + self.cursor = remote.lastHistoryStep + else: + self.cursor = self.state["last_logged_step"] + self.state.update(url=self.run.url, mode=mode, wandb_run_id=run_id) + write_json(self.state_path, self.state) + + def poll(self): + history = read_json(self.path / "learning.json") + previous = None + for record in history: + step = int(record["step"]) + if step > self.cursor: + self.run.log(learning_metrics(record, previous), step=step) + self.cursor = step + self.state["last_logged_step"] = step + write_json(self.state_path, self.state) + previous = record + status_path = self.path / "status.json" + if status_path.exists(): + status = read_json(status_path) + self.run.summary["training_state"] = status.get("state", "unknown") + complete = (self.path / "complete.json").exists() + failure_record = (self.path / "failure.json").exists() or ( + self.path / "failure-detail.json" + ).exists() + failed = failure_record and not complete + self.run.summary["has_failure_record"] = failure_record + self.run.summary["independently_reloaded"] = (self.path / "audit.json").exists() + if complete or failed: + self.run.summary["scientific_final_step"] = self.cursor + self.run.finish(exit_code=1 if failed else 0) + return True + return False + + def close(self): + self.run.finish() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--runs-dir", type=Path) + parser.add_argument("--defaults", type=Path, default=DEFAULTS) + parser.add_argument("--entity") + parser.add_argument("--project") + parser.add_argument("--mode", choices=["online", "offline"]) + parser.add_argument("--once", action="store_true") + parser.add_argument("--detach", action="store_true") + args = parser.parse_args() + settings = read_json(args.defaults) + for name in ["entity", "project", "mode"]: + settings[name] = ( + getattr(args, name) or os.environ.get(f"WANDB_{name.upper()}") or settings[name] + ) + if not settings["enabled"]: + raise SystemExit("Experiment tracking is disabled in the selected defaults") + local = args.root / "tracking-wandb" + local.mkdir(parents=True, exist_ok=True) + if args.detach: + metadata_path = local / "process.json" + if metadata_path.exists(): + pid = read_json(metadata_path)["pid"] + try: + os.kill(pid, 0) + except ProcessLookupError: + pass + else: + raise SystemExit(f"Tracking process already running: {pid}") + arguments = [a for a in sys.argv[1:] if a != "--detach"] + command = [ + sys.executable, + "-u", + "-m", + "llm_memory_editability.experiment_tracking", + *arguments, + ] + with (local / "tracker.log").open("a") as log: + process = subprocess.Popen( + command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True + ) + write_json(metadata_path, {"pid": process.pid, "command": command}) + print(json.dumps({"tracker_pid": process.pid, "log": str(local / "tracker.log")})) + return + try: + sdk = importlib.import_module("wandb") + except ImportError as error: + raise SystemExit("Install the tracking extra, or use .venv-wandb/bin/python") from error + with (local / "tracker.lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + active, finished = {}, set() + runs_dir = args.runs_dir or args.root / "development" + try: + while True: + for path in sorted(runs_dir.glob("*")): + if path in active or path in finished: + continue + if not (path / "run.json").exists() or not (path / "learning.json").exists(): + continue + active[path] = ArtifactRunTracker(sdk, args.root, path, settings) + print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True) + for path, tracker in list(active.items()): + current = read_json(path / "run.json") + if current.get("pid") != tracker.metadata.get("pid"): + tracker.close() + tracker = ArtifactRunTracker(sdk, args.root, path, settings) + active[path] = tracker + if tracker.poll(): + finished.add(path) + del active[path] + if args.once: + break + manifest = args.root / "controller-state.json" + if manifest.exists() and not active: + if read_json(manifest).get("state") in {"complete", "finished_with_failures"}: + break + time.sleep(settings["poll_seconds"]) + finally: + for tracker in active.values(): + tracker.close() + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/experiments.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/experiments.py new file mode 100644 index 0000000000000000000000000000000000000000..21513c79efc2f2e137213ca20f5444209e6d313d --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/experiments.py @@ -0,0 +1,39 @@ +"""Deterministic analytical illustration from the supplied research memo.""" + +import platform +from typing import Any + +import numpy as np + +from .low_rank import evaluate_update + + +def run_minimal_example(rank: int = 1, atol: float = 1e-10) -> dict[str, Any]: + """Compare a shared-rule update with a one-entry exception. + + At rank budget one, both changes have rank-one deltas but only the rule's + target is representable. At budget two, both targets are representable. + This is a classical matrix fact, not evidence of LLM editing difficulty. + """ + original = np.ones((2, 2), dtype=float) + cases = { + "original": evaluate_update(original, original, rank, atol), + "rule": evaluate_update(original, 2 * original, rank, atol), + "exception": evaluate_update(original, [[2, 1], [1, 1]], rank, atol), + } + return { + "experiment": "minimal_low_rank", + "scope": ( + "Analytical SVD illustration for fully observed real matrices with a " + "fixed total rank budget and unweighted Frobenius error. No training, " + "optimization path, or Transformer editing is evaluated. Numerical " + "rank counts singular values greater than an absolute tolerance; " + "this example does not validate the broader research hypothesis." + ), + "parameters": { + "rank_budget": cases["original"]["rank_budget"], + "atol": cases["original"]["atol"], + }, + "versions": {"python": platform.python_version(), "numpy": np.__version__}, + "cases": cases, + } diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_depth.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb93ea353cb12f972942a3cf658bc6593f81bb7 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_depth.py @@ -0,0 +1,431 @@ +"""Small GPT-2 composition learning, adapted from Wang et al. (NeurIPS 2024). + +Data/target conventions follow GrokkedTransformer commit 734ca654ec7a71dd6737d640407fac14491d538c. +The compact vocabulary, widths and data sizes are explicit experimental adaptations. +CUDA Graph capture is an execution optimization, not a change to the training objective. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import math +import time +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import CausalLM, ModelConfig, matmul_flops + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + tmp.replace(path) + + +class SmallGPT(CausalLM): + """GPT-2 pre-LN, tied output, learned positions, GELU, standard dropout.""" + + def __init__(self, config, dropout=0.1): + super().__init__(config) + self.dropout = dropout + + def forward(self, tokens, positions=None): + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + for block in self.blocks: + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + +def pack_rows(rows): + """Right-pad; supervise tail and EOS only. No BOS or answer delimiter.""" + rows = np.asarray(rows, dtype=np.int64) + x = np.zeros((len(rows), 4), dtype=np.int64) + x[:, : rows.shape[1]] = rows + positions = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) + labels = np.c_[rows[:, -1], np.ones(len(rows), dtype=np.int64)] + return x, positions, labels + + +def make_optimizer(model, lr, weight_decay): + decay = [p for p in model.parameters() if p.ndim >= 2] + no_decay = [p for p in model.parameters() if p.ndim < 2] + return torch.optim.AdamW( + [ + {"params": decay, "weight_decay": weight_decay}, + {"params": no_decay, "weight_decay": 0.0}, + ], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + fused=True, + capturable=True, + ) + + +class GraphStep: + """Capture complete AdamW step and undo warmup without rebinding state tensors.""" + + def __init__(self, model, optimizer, table, batch_size, clip=1.0): + self.index = torch.zeros(batch_size, dtype=torch.long, device=table[0].device) + self.model, self.optimizer, self.table, self.clip = model, optimizer, table, clip + weights = {k: v.detach().clone() for k, v in model.state_dict().items()} + state = { + p: { + k: v.detach().clone() if torch.is_tensor(v) else copy.deepcopy(v) + for k, v in s.items() + } + for p, s in optimizer.state.items() + } + cpu_rng = torch.get_rng_state() + cuda_rng = torch.cuda.get_rng_state(table[0].device) + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(3): + self.eager() + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + self.graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(self.graph): + self.loss, self.grad_norm = self.eager() + torch.cuda.synchronize() + with torch.no_grad(): + for k, v in model.state_dict().items(): + v.copy_(weights[k]) + for param, values in optimizer.state.items(): + before = state.get(param, {}) + for k, v in values.items(): + if torch.is_tensor(v): + if k in before: + v.copy_(before[k]) + else: + v.zero_() + for p in model.parameters(): + if p.grad is not None: + p.grad.zero_() + torch.set_rng_state(cpu_rng) + torch.cuda.set_rng_state(cuda_rng, table[0].device) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, pos, labels = (t[self.index] for t in self.table) + logits = self.model(x, positions=pos) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten()) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + def __call__(self, indices): + self.index.copy_(indices) + self.graph.replay() + return self.loss + + +class EpochStream: + """Uniform shuffled epochs of the combined atomic/composite training set.""" + + def __init__(self, size, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def take(self, n): + parts = [] + while n: + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(n, len(self.remaining)) + parts.append(self.remaining[:count]) + self.remaining = self.remaining[count:] + n -= count + return np.concatenate(parts) + + def state_dict(self): + return { + "size": self.size, + "rng": self.rng.bit_generator.state, + "remaining": self.remaining.copy(), + } + + def load_state_dict(self, state): + assert state["size"] == self.size + self.rng.bit_generator.state = state["rng"] + self.remaining = state["remaining"].copy() + + +@torch.no_grad() +def evaluate_rows(model, rows, device, batch_size=1024): + model.eval() + packed = pack_rows(rows) + answers, stops, losses = [], [], [] + for start in range(0, len(rows), batch_size): + x, pos, labels = ( + torch.as_tensor(t[start : start + batch_size], device=device) for t in packed + ) + logits = model(x, pos) + losses.append( + F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + .view(-1, 2) + .cpu() + .numpy() + ) + answer = logits[:, 0].argmax(-1) + # Actual generated answer is fed back when producing EOS. + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + stop = model(x, pos)[:, 1].argmax(-1) + answers.append(answer.cpu().numpy()) + stops.append(stop.cpu().numpy()) + model.train() + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}, {} + answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) + correct = answer == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": float(correct.mean()), + "accuracy": float((correct & (stop == 1)).mean()), + "nll": float(nll.mean()), + }, {"answer": answer, "stop": stop, "nll": nll, "target": rows[:, -1]} + + +@torch.no_grad() +def two_calls(model, rows, device): + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None} + first = np.c_[rows[:, :2], np.zeros(len(rows), dtype=np.int64)] + _, first_pred = evaluate_rows(model, first, device) + second = np.c_[first_pred["answer"], rows[:, 2], rows[:, 3]] + result, second_pred = evaluate_rows(model, second, device) + result["accuracy"] = float( + ( + (second_pred["answer"] == rows[:, -1]) + & (second_pred["stop"] == 1) + & (first_pred["stop"] == 1) + ).mean() + ) + return result + + +def source_hash(paths): + return {str(p): hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths} + + +def run(spec, world, out, device="cuda:0", resume=False): + """Run a fixed scientific budget. Intermediate evaluations never change training.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + device = torch.device(device) + torch.cuda.set_device(device) + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = SmallGPT(cfg, spec["dropout"]).to(device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + atoms, comps = pack_rows(world["atomic"]), pack_rows(world["train_composite"]) + table = tuple( + torch.as_tensor(np.concatenate([a, c]), device=device) + for a, c in zip(atoms, comps, strict=True) + ) + stream = EpochStream(len(table[0]), spec["stream_seed"]) + counts = {"atomic": 0, "composite": 0} + elapsed_training, elapsed_eval = 0.0, 0.0 + start_step = 0 + checkpoint = out / "latest.pt" + if resume: + state = torch.load(checkpoint, map_location=device, weights_only=False) + assert state["spec"] == spec + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + # load_state_dict replaces the LR tensor; retain the optimizer's live tensor. + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + counts = state["counts"] + elapsed_training = state["elapsed_training"] + elapsed_eval = state["elapsed_eval"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + started = time.perf_counter() + graph = GraphStep(model, opt, table, spec["batch_size"]) + capture_seconds = time.perf_counter() - started + names = ("atomic", "train_composite", "test_composite", "ood_composite") + nparams = sum(p.numel() for p in model.parameters()) + flop_step = matmul_flops(cfg, spec["batch_size"], sequence=4, output_positions=2) + rows_log = [] + if (out / "learning.json").exists(): + rows_log = json.loads((out / "learning.json").read_text()) + if resume: + # A crash can leave a log newer than the atomically replaced checkpoint. + rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) + rows_log.sort(key=lambda r: r["step"]) + if start_step == spec["steps"]: + endpoint = rows_log[-1] + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": endpoint, + "completion_recovered_from_final_checkpoint": True, + }, + ) + write_json( + out / "status.json", + { + "state": "complete", + "step": start_step, + "budget": spec["steps"], + "updated_utc": utc(), + "atomic": endpoint["atomic"]["accuracy"], + "train": endpoint["train_composite"]["accuracy"], + "test": endpoint["test_composite"]["accuracy"], + }, + ) + return rows_log[-1] + + def measure(step, last_loss=None): + nonlocal elapsed_eval + torch.cuda.synchronize() + t0 = time.perf_counter() + row = { + "step": step, + "utc": utc(), + "parameters": nparams, + "training_seconds": elapsed_training, + "capture_seconds": capture_seconds, + "examples": step * spec["batch_size"], + "counts": counts.copy(), + "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * 4, + "supervised_tokens": step * spec["batch_size"] * 2, + "estimated_training_flops": step * flop_step, + "last_batch_loss": last_loss, + } + predictions = {} + for name in names: + row[name], pred = evaluate_rows(model, world[name], device) + predictions.update({name + "_" + k: v for k, v in pred.items()}) + row["two_calls"] = two_calls(model, world["test_composite"], device) + torch.cuda.synchronize() + elapsed_eval += time.perf_counter() - t0 + row["evaluation_seconds"] = elapsed_eval + rows_log.append(row) + write_json(out / "learning.json", rows_log) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + state = { + "step": step, + "spec": spec, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "elapsed_training": elapsed_training, + "elapsed_eval": elapsed_eval, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(checkpoint) + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "complete" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "updated_utc": utc(), + "atomic": row["atomic"]["accuracy"], + "train": row["train_composite"]["accuracy"], + "test": row["test_composite"]["accuracy"], + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + nodes = [s for s in spec["nodes"] if s > start_step] + for end in nodes: + last_loss = None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + ix = stream.take(n * spec["batch_size"]).reshape(n, spec["batch_size"]) + atom_count = int((ix < len(world["atomic"])).sum()) + counts["atomic"] += atom_count + counts["composite"] += ix.size - atom_count + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + last_loss = graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + elapsed_training += time.perf_counter() - t0 + loss_value = float(last_loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at step {end}") + row = measure(end, loss_value) + start_step = end + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": row, + }, + ) + return row diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_depth_bridge.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_depth_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..ca05be9fcd170cee34075ae1aa2fa0c2bcca1e2c --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_depth_bridge.py @@ -0,0 +1,631 @@ +"""Prefix-only causal interventions on frozen grok-depth-v1 checkpoints. + +Donors are selected from world facts before any model is loaded. The only donor +input is its two-token atomic query; second relations and answers never enter the +forward pass that supplies the post-first-block residual state. +""" + +from __future__ import annotations + +import hashlib +import importlib +import json +import platform +import sys +import time +import types +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +CONDITIONS = ( + "baseline", + "identity_r1", + "different_bridge_r1", + "same_bridge_r1", + "different_bridge_h", + "different_bridge_h_r1", + "counterfactual_input", +) +DATA_FIELDS = ("entities", "relations", "degree", "phi", "id_fraction", "id_test_fraction") + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temporary.replace(path) + + +def require(condition, message): + if not condition: + raise AssertionError(message) + + +def _frozen_modules(source_dir, metadata): + """Verify all historical copies, then import exclusively from that snapshot.""" + snapshot = source_dir / "source" + copied = {p.relative_to(snapshot).as_posix(): p for p in snapshot.rglob("*") if p.is_file()} + verified = {} + for original, expected in metadata["files"].items(): + matches = [ + p for rel, p in copied.items() if original == rel or original.endswith("/" + rel) + ] + require(len(matches) == 1, f"missing or ambiguous historical copy: {original}") + path = matches[0] + actual = digest(path) + require(actual == expected, f"historical source hash mismatch: {path}") + verified[path.relative_to(snapshot).as_posix()] = actual + configs = [snapshot / p for p in verified if p.startswith("configs/")] + require(len(configs) == 1, "expected exactly one frozen configuration") + frozen = read_json(configs[0]) + require( + {**frozen["base"], **frozen["runs"][source_dir.name]} == metadata["spec"], + "historical metadata differs from its frozen configuration", + ) + package = "_grok_bridge_source_" + hashlib.sha256(str(source_dir).encode()).hexdigest()[:16] + namespace = types.ModuleType(package) + namespace.__path__ = [str(snapshot / "src/llm_memory_editability")] + sys.modules[package] = namespace + training = importlib.import_module(package + ".grok_depth") + data = importlib.import_module(package + ".grok_depth_data") + return training, data, verified + + +def load_source_run(source_dir, step, device="cuda:0"): + """Return a frozen model/world after source, world and checkpoint consistency checks.""" + source_dir = Path(source_dir).resolve() + metadata = read_json(source_dir / "metadata.json") + spec = metadata["spec"] + require(spec["phase"] == source_dir.parent.name, "historical phase/path mismatch") + training, data, verified = _frozen_modules(source_dir, metadata) + require(step in spec["weight_nodes"], f"unregistered historical weight node {step}") + checkpoint_path = source_dir / f"weights-{step:07d}.pt" + checkpoint_hash = digest(checkpoint_path) + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + require( + checkpoint["spec"] == spec and checkpoint["step"] == step, "checkpoint identity mismatch" + ) + require(digest(checkpoint_path) == checkpoint_hash, "checkpoint changed while loading") + if step == spec["steps"]: + latest = torch.load(source_dir / "latest.pt", map_location="cpu", weights_only=False) + require( + latest["step"] == step and latest["spec"] == spec, "latest checkpoint identity mismatch" + ) + require( + checkpoint["model"].keys() == latest["model"].keys() + and all(torch.equal(v, latest["model"][k]) for k, v in checkpoint["model"].items()), + "endpoint weights differ from latest checkpoint", + ) + del latest + world_path = source_dir / "world.npz" + world_hash = digest(world_path) + with np.load(world_path, allow_pickle=False) as stored: + world = {key: stored[key].copy() for key in stored.files} + world["metadata"] = read_json(source_dir / "world-metadata.json") + require(digest(world_path) == world_hash, "world changed while loading") + audit = data.audit_world(world) + require(audit == read_json(source_dir / "data-audit.json"), "historical world audit mismatch") + require( + audit["dataset_sha256"] == world["metadata"]["dataset_sha256"], + "world content hash mismatch", + ) + rebuilt = data.build_world(spec["world_seed"], **{key: spec[key] for key in DATA_FIELDS}) + require(rebuilt["metadata"] == world["metadata"], "regenerated world metadata mismatch") + for key, array in world.items(): + if key != "metadata": + require(np.array_equal(array, rebuilt[key]), f"regenerated world mismatch: {key}") + cfg = training.ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = training.SmallGPT(cfg, spec["dropout"]).to(device) + model.load_state_dict(checkpoint["model"], strict=True) + model.eval() + for parameter in model.parameters(): + parameter.requires_grad_(False) + provenance = { + "source_dir": str(source_dir), + "source_hashes": verified, + "checkpoint_sha256": checkpoint_hash, + "world_file_sha256": world_hash, + "dataset_sha256": audit["dataset_sha256"], + "world_audit": audit, + "source_metadata_sha256": digest(source_dir / "metadata.json"), + "source_predictions_sha256": digest(source_dir / f"predictions-{step:07d}.npz"), + "world_regenerated_identically": True, + } + return model, world, spec, provenance + + +def _choose(candidates, world_hash, seed, row, kind): + """Content-based uniform deterministic selection; no model input is accepted.""" + if not candidates: + return None + material = json.dumps([world_hash, int(seed), list(map(int, row)), kind], separators=(",", ":")) + rng = np.random.default_rng( + int.from_bytes(hashlib.sha256(material.encode()).digest()[:16], "big") + ) + return sorted(candidates)[int(rng.integers(len(candidates)))] + + +def select_donors(world, seed): + """Select once per test row; preserve all rows, masks and rejection counts. + + Different-bridge candidates share r1, change h/b/t, have ID second facts, + and yield a reserved-test or unused counterfactual. Same-bridge candidates + may change r1; only their bridge, query distinctness and h != original t + matter. No candidate is selected using model behavior. + """ + rows = world["test_composite"] + n = len(rows) + atoms = {tuple(map(int, row)) for row in world["id_atomic"]} + lookup = {(h, r): t for h, r, t in atoms} + held_out = { + tuple(map(int, row)) + for name in ("test_composite", "unused_composite") + for row in world[name] + } + training = {tuple(map(int, row)) for row in world["train_composite"]} + world_hash = world["metadata"]["dataset_sha256"] + out = { + "original_rows": rows.copy(), + "original_bridge": np.full(n, -1, dtype=np.int64), + "different_donor": np.full((n, 3), -1, dtype=np.int64), + "same_donor": np.full((n, 3), -1, dtype=np.int64), + "counterfactual_rows": np.full((n, 4), -1, dtype=np.int64), + "different_valid": np.zeros(n, dtype=bool), + "same_valid": np.zeros(n, dtype=bool), + "different_reason": np.full(n, "", dtype="U64"), + "same_reason": np.full(n, "", dtype="U64"), + "different_candidate_count": np.zeros(n, dtype=np.int64), + "same_candidate_count": np.zeros(n, dtype=np.int64), + "same_relation_control": np.full(n, "missing", dtype="U24"), + "different_nondegenerate": np.zeros(n, dtype=bool), + } + rejection_names = ( + "same_head", + "same_bridge", + "missing_id_second_fact", + "same_tail", + "head_is_answer", + "counterfactual_in_train", + "counterfactual_not_held_out", + ) + for reason in rejection_names: + out["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) + for index, row in enumerate(rows): + h, r1, r2, tail = map(int, row) + bridge = lookup[h, r1] + require(lookup.get((bridge, r2)) == tail, "recipient is not an ID-ID chain") + out["original_bridge"][index] = bridge + candidates = [] + for dh, dr, db in sorted(atoms): + if dr != r1: + continue + dt = lookup.get((db, r2)) + cf = (dh, r1, r2, dt) + reason = ( + "same_head" + if dh == h + else "same_bridge" + if db == bridge + else "missing_id_second_fact" + if dt is None + else "same_tail" + if dt == tail + else "head_is_answer" + if dh in (tail, dt) + else "counterfactual_in_train" + if cf in training + else "counterfactual_not_held_out" + if cf not in held_out + else None + ) + if reason: + out["different_rejected_" + reason][index] += 1 + else: + candidates.append((dh, dr, db, dt)) + donor = _choose(candidates, world_hash, seed, row, "different") + out["different_candidate_count"][index] = len(candidates) + if donor is None: + out["different_reason"][index] = "no_candidate_after_registered_exclusions" + else: + dh, dr, db, dt = donor + out["different_donor"][index] = dh, dr, db + out["counterfactual_rows"][index] = dh, r1, r2, dt + out["different_valid"][index] = True + out["different_reason"][index] = "eligible" + out["different_nondegenerate"][index] = db != dt and db != tail + candidates = [ + (dh, dr, db) + for dh, dr, db in atoms + if db == bridge and (dh, dr) != (h, r1) and dh != tail + ] + same_relation = [candidate for candidate in candidates if candidate[1] == r1] + donor = _choose(same_relation or candidates, world_hash, seed, row[:2], "same") + out["same_candidate_count"][index] = len(candidates) + if donor is None: + out["same_reason"][index] = "no_distinct_id_prefix_with_same_bridge_and_head_not_answer" + else: + out["same_donor"][index] = donor + out["same_valid"][index] = True + out["same_reason"][index] = "eligible" + out["same_relation_control"][index] = "same_r1" if donor[1] == r1 else "different_r1" + return out + + +@torch.no_grad() +def traced_forward( + model, + tokens, + positions=None, + donor_state=None, + patch_positions=(), + identity=False, + return_state=False, +): + """Frozen SmallGPT eval forward, replacing residuals after complete block 0. + + Both attention and MLP in the first block run before replacement. There is + no patch in another block, and final LN/output projection remain untouched. + """ + require(not model.training, "interventions require model.eval()") + require( + donor_state is None or not identity, "identity and donor patches are mutually exclusive" + ) + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + first_state = None + for index, block in enumerate(model.blocks): + z = block.ln1(x) + batch, length, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, length, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=0.0 + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + y + x = x + block.mlp(block.ln2(x)) + if index == 0: + if return_state: + first_state = x.clone() + if donor_state is not None or identity: + x = x.clone() + replacement = x.clone() if identity else donor_state + for position in patch_positions: + x[:, position, :] = replacement[:, position, :] + x = model.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, model.token.weight) + return (logits, first_state) if return_state else logits + + +@torch.no_grad() +def prefix_state(model, prefixes): + """Two informative tokens, padded to the historical four-position shape. + + Both suffix tokens are the fixed PAD token, never a relation or answer. + Causality makes the retained two states independent of these suffixes. + Matching the matrix shapes avoids TF32 kernel-dependent rounding changes. + """ + require(prefixes.ndim == 2 and prefixes.shape[1] == 2, "expected h/r1 prefixes") + padded = F.pad(prefixes, (0, 2), value=0) + _, state = traced_forward(model, padded, return_state=True) + return state[:, :2] + + +@torch.no_grad() +def evaluate_condition( + model, + rows, + device, + batch_size=1024, + donor_prefixes=None, + patch_positions=(), + identity=False, + verify_trace=False, +): + """Answer generation followed by EOS with the generated answer fed back. + + The exact same prefix state is reapplied on the second forward pass. Arrays + are local to the supplied rows; the caller scatters them to the full test set. + """ + n = len(rows) + answers, stops, original_logits = [], [], [] + trace_max_delta, trace_disagreements = 0.0, 0 + prefix_max_delta = 0.0 + for start in range(0, n, batch_size): + selected = rows[start : start + batch_size] + arity = rows.shape[1] + require(arity in (3, 4), "expected atomic or composite rows") + packed = np.zeros((len(selected), 4), dtype=np.int64) + packed[:, :arity] = selected + x = torch.as_tensor(packed, device=device) + pos = torch.as_tensor(np.tile([arity - 2, arity - 1], (len(x), 1)), device=device) + donor_state = None + if donor_prefixes is not None: + prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) + require(prefixes.shape == (len(x), 2), "donor model may receive only h and r1") + donor_state = prefix_state(model, prefixes) + logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) + if verify_trace: + reference = model(x, pos) + trace_max_delta = max(trace_max_delta, float((reference - logits).abs().max())) + trace_disagreements += int((reference.argmax(-1) != logits.argmax(-1)).sum()) + prefix = prefix_state(model, x[:, :2]) + _, whole = traced_forward(model, x, return_state=True) + prefix_max_delta = max(prefix_max_delta, float((prefix - whole[:, :2]).abs().max())) + require( + torch.allclose(prefix, whole[:, :2], atol=1e-4, rtol=1e-4), + "pure-prefix state does not match causal full-input prefix", + ) + answer = logits[:, 0].argmax(-1) + original_logits.append(logits[:, 0].cpu().numpy()) + x[:, arity - 1] = answer + generated_logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) + if verify_trace: + reference = model(x, pos) + trace_max_delta = max( + trace_max_delta, float((reference - generated_logits).abs().max()) + ) + trace_disagreements += int((reference.argmax(-1) != generated_logits.argmax(-1)).sum()) + answers.append(answer.cpu().numpy()) + stops.append(generated_logits[:, 1].argmax(-1).cpu().numpy()) + require(trace_disagreements == 0, "traced forward changes standard-forward discrete outputs") + require(trace_max_delta <= 1e-5, f"traced forward mismatch: {trace_max_delta}") + return { + "answer": np.concatenate(answers) if n else np.empty(0, dtype=np.int64), + "stop": np.concatenate(stops) if n else np.empty(0, dtype=np.int64), + "answer_logits": np.concatenate(original_logits) + if n + else np.empty((0, model.token.num_embeddings), dtype=np.float32), + }, { + "standard_forward_max_logit_delta": trace_max_delta, + "standard_forward_argmax_disagreements": trace_disagreements, + "prefix_vs_full_first_block_max_delta": prefix_max_delta, + "trace_comparison_performed": verify_trace, + } + + +def _metrics(answer, stop, original, cf, selected, cf_valid, total, baseline_answer): + count = int(selected.sum()) + counterfactual = selected & cf_valid + ncf = int(counterfactual.sum()) + correct = answer == original + cf_correct = answer == cf + return { + "n": count, + "total_test_n": total, + "coverage": count / total if total else None, + "original_answer_accuracy": float(correct[selected].mean()) if count else None, + "original_complete_accuracy": float((correct & (stop == 1))[selected].mean()) + if count + else None, + "eos_accuracy": float((stop[selected] == 1).mean()) if count else None, + "answer_change_rate": float((answer[selected] != baseline_answer[selected]).mean()) + if count + else None, + "cf_target_n": ncf, + "cf_answer_accuracy": float(cf_correct[counterfactual].mean()) if ncf else None, + "cf_complete_accuracy": float((cf_correct & (stop == 1))[counterfactual].mean()) + if ncf + else None, + } + + +def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): + """Evaluate all fixed conditions, then expose full and prerequisite subgroups.""" + started = time.perf_counter() + rows = world["test_composite"] + n = len(rows) + different, same = donors["different_valid"], donors["same_valid"] + arrays = {key: value.copy() for key, value in donors.items()} + audits = {} + for condition in CONDITIONS: + mask = ( + same + if condition == "same_bridge_r1" + else different + if condition.startswith("different_") or condition == "counterfactual_input" + else np.ones(n, dtype=bool) + ) + eval_rows = ( + donors["counterfactual_rows"][mask] + if condition == "counterfactual_input" + else rows[mask] + ) + donor_key = "same_donor" if condition == "same_bridge_r1" else "different_donor" + donor_prefix = donors[donor_key][mask, :2] if "bridge_" in condition else None + positions = ( + (0, 1) + if condition == "different_bridge_h_r1" + else (0,) + if condition == "different_bridge_h" + else (1,) + ) + result, audit = evaluate_condition( + model, + eval_rows, + device, + batch_size, + donor_prefix, + positions, + condition == "identity_r1", + condition == "baseline", + ) + audits[condition] = audit + answer = np.full(n, -1, dtype=np.int64) + stop = np.full(n, -1, dtype=np.int64) + answer[mask], stop[mask] = result["answer"], result["stop"] + arrays[condition + "_answer"], arrays[condition + "_stop"] = answer, stop + arrays[condition + "_valid"] = mask + original_logit = result["answer_logits"][np.arange(mask.sum()), rows[mask, -1]] + cf_logit = np.full(n, np.nan, dtype=np.float32) + cf_local = different[mask] + cf_logit[mask.nonzero()[0][cf_local]] = ( + result["answer_logits"][ + np.flatnonzero(cf_local), donors["counterfactual_rows"][mask][cf_local, -1] + ] + - original_logit[cf_local] + ) + arrays[condition + "_cf_minus_original_logit"] = cf_logit + for column in ("answer", "stop"): + require( + np.array_equal(arrays["baseline_" + column], arrays["identity_r1_" + column]), + f"identity patch changed {column}", + ) + if len(model.blocks) == 1: + for condition in ( + "different_bridge_r1", + "same_bridge_r1", + "different_bridge_h", + "different_bridge_h_r1", + ): + valid = arrays[condition + "_valid"] + require( + np.array_equal( + arrays["baseline_" + column][valid], arrays[condition + "_" + column][valid] + ), + f"one-layer structural negative control changed {condition}.{column}", + ) + baseline_correct = (arrays["baseline_answer"] == rows[:, -1]) & (arrays["baseline_stop"] == 1) + cf_correct = ( + different + & (arrays["counterfactual_input_answer"] == donors["counterfactual_rows"][:, -1]) + & (arrays["counterfactual_input_stop"] == 1) + ) + atomic_rows = { + "different_first": (donors["different_donor"], different), + "counterfactual_second": ( + np.c_[ + donors["different_donor"][:, 2], rows[:, 2], donors["counterfactual_rows"][:, -1] + ], + different, + ), + "same_first": (donors["same_donor"], same), + } + atomic_scores = {} + atomic_correct = {} + for name, (facts, mask) in atomic_rows.items(): + prediction, _ = evaluate_condition(model, facts[mask], device, batch_size) + answer = np.full(n, -1, dtype=np.int64) + stop = np.full(n, -1, dtype=np.int64) + answer[mask], stop[mask] = prediction["answer"], prediction["stop"] + arrays["atomic_" + name + "_rows"] = facts.copy() + arrays["atomic_" + name + "_answer"] = answer + arrays["atomic_" + name + "_stop"] = stop + arrays["atomic_" + name + "_valid"] = mask.copy() + correct = mask & (answer == facts[:, -1]) + atomic_correct[name] = correct & (stop == 1) + count = int(mask.sum()) + atomic_scores[name] = { + "n": count, + "total_test_n": n, + "coverage": count / n if n else None, + "answer_accuracy": float(correct[mask].mean()) if count else None, + "complete_accuracy": float(atomic_correct[name][mask].mean()) if count else None, + "eos_accuracy": float((stop[mask] == 1).mean()) if count else None, + } + groups = { + "all_test": np.ones(n, dtype=bool), + "different_donor_available": different, + "same_donor_available": same, + "baseline_and_counterfactual_complete_correct": baseline_correct & cf_correct, + "different_bridge_nondegenerate": donors["different_nondegenerate"], + "same_bridge_same_r1": same & (donors["same_relation_control"] == "same_r1"), + "same_bridge_different_r1": same & (donors["same_relation_control"] == "different_r1"), + "both_counterfactual_atomic_facts_complete_correct": atomic_correct["different_first"] + & atomic_correct["counterfactual_second"], + } + for group, mask in groups.items(): + arrays["subset_" + group] = mask + scores = { + group: { + "subset_n": int(mask.sum()), + "total_test_n": n, + "coverage": float(mask.mean()) if n else None, + "conditions": { + condition: _metrics( + arrays[condition + "_answer"], + arrays[condition + "_stop"], + rows[:, -1], + donors["counterfactual_rows"][:, -1], + mask & arrays[condition + "_valid"], + different, + n, + arrays["baseline_answer"], + ) + for condition in CONDITIONS + }, + } + for group, mask in groups.items() + } + summary = { + "conditions": list(CONDITIONS), + "scores": scores, + "atomic_preconditions": atomic_scores, + "donor_coverage": { + "total_test_n": n, + "different_n": int(different.sum()), + "same_n": int(same.sum()), + "different_reasons": dict(Counter(donors["different_reason"].tolist())), + "same_reasons": dict(Counter(donors["same_reason"].tolist())), + "same_relation_control": dict(Counter(donors["same_relation_control"].tolist())), + }, + "engineering_checks": { + "identity_predictions_equal": True, + "one_layer_all_early_position_patch_predictions_equal": True + if len(model.blocks) == 1 + else None, + "trace": audits["baseline"], + "eos_uses_generated_answer_and_reapplies_patch": True, + "donor_nonpadding_input_tokens": 2, + "donor_forward_sequence_length": 4, + "donor_pad_token": 0, + }, + "evaluation_seconds": time.perf_counter() - started, + } + return summary, arrays + + +def environment(device): + return { + "python": platform.python_version(), + "platform": platform.platform(), + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "device": str(device), + "gpu": torch.cuda.get_device_name(torch.device(device)) + if str(device).startswith("cuda") + else None, + "cuda_matmul_tf32": torch.backends.cuda.matmul.allow_tf32, + "cudnn_tf32": torch.backends.cudnn.allow_tf32, + "precision": "FP32 parameters and evaluation; TF32 flags recorded explicitly", + } diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_depth_data.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_depth_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8696c3ffe204466f57619157a3f47739f899c6c4 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_depth_data.py @@ -0,0 +1,281 @@ +"""Symbolic composition worlds adapted from GrokkedTransformer/composition.ipynb. + +Source: https://github.com/OSU-NLP-Group/GrokkedTransformer +Revision: 734ca654ec7a71dd6737d640407fac14491d538c (MIT). + +The graph, atomic ID/OOD split, reserved ID test chains, and phi downsampling +follow the authors' construction. Differences: integer tokens replace text; +randomness is local and seeded; atomic ordering is stable; graph size and the +reserved ID-test fraction are configurable. Unselected ID chains are returned +for audit only. No graph is regenerated to improve OOD counts or model results. + +Adapted source license: +MIT License +Copyright (c) 2024 OSU Natural Language Processing + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +PAD_TOKEN = 0 +EOS_TOKEN = 1 +ENTITY_OFFSET = 2 +SOURCE_URL = "https://github.com/OSU-NLP-Group/GrokkedTransformer" +SOURCE_COMMIT = "734ca654ec7a71dd6737d640407fac14491d538c" +ATOMIC_SPLITS = ("atomic", "id_atomic", "ood_atomic") +COMPOSITE_SPLITS = ( + "train_composite", + "test_composite", + "ood_composite", + "unused_composite", +) + + +def _array(rows: list, columns: int) -> np.ndarray: + return np.asarray(rows, dtype=np.int64).reshape(-1, columns) + + +def build_world( + seed: int, + entities: int = 128, + relations: int = 16, + degree: int = 8, + phi: float = 8.0, + id_fraction: float = 0.95, + id_test_fraction: float = 0.005, +) -> dict: + """Return atomic ``[h,r,t]`` and composite ``[h,r1,r2,t]`` int64 arrays. + + All atomics belong in training, including those labelled OOD. OOD refers + to *composition experience*: neither constituent of an OOD composite is + allowed in composite training. Mixed ID/OOD chains are excluded. The + test set is reserved before phi downsampling; unused ID chains are never + automatically reassigned to test. ``phi`` is relative to ID atomics, as in + the source. Requests larger than the available training pool are capped + and explicitly recorded. Empty test sets are retained and reported. + + Query tokens are every column except the last; the last is the entity + answer. EOS supervision, padding, and loss masks belong to the trainer. + """ + for name, value in (("entities", entities), ("relations", relations), ("degree", degree)): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 1: + raise ValueError(f"{name} must be a positive integer") + if degree > relations: + raise ValueError("degree cannot exceed relations") + if not math.isfinite(phi) or phi < 0: + raise ValueError("phi must be finite and nonnegative") + if not math.isfinite(id_fraction) or not 0 <= id_fraction <= 1: + raise ValueError("id_fraction must be in [0, 1]") + if not math.isfinite(id_test_fraction) or not 0 <= id_test_fraction <= 1: + raise ValueError("id_test_fraction must be in [0, 1]") + + # RandomState keeps the source's NumPy draw family, without global RNG use. + rng = np.random.RandomState(seed) + relation_offset = ENTITY_OFFSET + entities + rows = [] + outgoing = [[] for _ in range(entities)] + for head_index in range(entities): + selected = rng.choice(relations, size=degree, replace=False) + for relation_index in selected: + tail_index = int(rng.randint(entities)) + edge = ( + head_index + ENTITY_OFFSET, + int(relation_index) + relation_offset, + tail_index + ENTITY_OFFSET, + ) + outgoing[head_index].append(len(rows)) + rows.append(edge) + atomic = _array(rows, 3) + ood_count = round(len(atomic) * (1 - id_fraction)) + ood_mask = np.zeros(len(atomic), dtype=bool) + ood_mask[rng.choice(len(atomic), size=ood_count, replace=False)] = True + + eligible, test, ood = [], [], [] + mixed_count = 0 + for first_index, (head, relation1, bridge) in enumerate(atomic): + for second_index in outgoing[int(bridge) - ENTITY_OFFSET]: + _, relation2, tail = atomic[second_index] + row = (head, relation1, relation2, tail) + first_ood, second_ood = ood_mask[first_index], ood_mask[second_index] + if first_ood and second_ood: + ood.append(row) + elif first_ood or second_ood: + mixed_count += 1 + elif rng.uniform() > id_test_fraction: + eligible.append(row) + else: + test.append(row) + + requested_count = round(phi * int((~ood_mask).sum())) + train_count = min(requested_count, len(eligible)) + # Source choose() returns the full pool unchanged when it is saturated. + indices = ( + np.arange(len(eligible)) + if train_count == len(eligible) + else rng.choice(len(eligible), size=train_count, replace=False) + ) + eligible_array = _array(eligible, 4) + selected_mask = np.zeros(len(eligible), dtype=bool) + selected_mask[indices] = True + world = { + "atomic": atomic, + "id_atomic": atomic[~ood_mask], + "ood_atomic": atomic[ood_mask], + "train_composite": eligible_array[indices], + "test_composite": _array(test, 4), + "ood_composite": _array(ood, 4), + "unused_composite": eligible_array[~selected_mask], + "metadata": { + "seed": int(seed), + "entities": int(entities), + "relations": int(relations), + "degree": int(degree), + "phi_requested": float(phi), + "id_fraction": float(id_fraction), + "id_test_fraction": float(id_test_fraction), + "pad_token": PAD_TOKEN, + "eos_token": EOS_TOKEN, + "entity_offset": ENTITY_OFFSET, + "relation_offset": int(relation_offset), + "vocab_size": int(relation_offset + relations), + "train_composite_requested": int(requested_count), + "train_composite_capped": requested_count > len(eligible), + "phi_actual": train_count / max(int((~ood_mask).sum()), 1), + "mixed_composite_excluded": mixed_count, + "source_url": SOURCE_URL, + "source_commit": SOURCE_COMMIT, + "source_file": "composition.ipynb", + "source_license": "MIT", + "construction_differences": [ + "integer tokens and local seeded RNG", + "stable atomic ordering instead of Python set iteration", + "configurable graph size and ID-test reserve fraction", + "all evaluation rows retained instead of sampling at most 3000", + ], + }, + } + audit = audit_world(world) + world["metadata"]["counts"] = audit["counts"] + world["metadata"]["dataset_sha256"] = audit["dataset_sha256"] + world["metadata"]["warnings"] = audit["warnings"] + return world + + +def audit_world(world: dict) -> dict: + """Validate token ranges, graph truth, exhaustive partitions and no leakage. + + Raises ValueError on a broken contract; zero-sized test sets and capped + training pools are valid and surfaced as warnings, never resampled. + """ + metadata = world["metadata"] + entities, relations, degree = (int(metadata[x]) for x in ("entities", "relations", "degree")) + relation_offset = entities + ENTITY_OFFSET + digest = hashlib.sha256() + counts = {} + tuples = {} + for name in ATOMIC_SPLITS + COMPOSITE_SPLITS: + array = world[name] + columns = 3 if name in ATOMIC_SPLITS else 4 + if not isinstance(array, np.ndarray) or array.dtype != np.int64: + raise ValueError(f"{name} must be an int64 numpy array") + if array.ndim != 2 or array.shape[1] != columns: + raise ValueError(f"{name} must have {columns} columns") + for column in (0, columns - 1): + if np.any(array[:, column] < ENTITY_OFFSET) or np.any( + array[:, column] >= relation_offset + ): + raise ValueError(f"{name} has an invalid entity token") + if np.any(array[:, 1:-1] < relation_offset) or np.any( + array[:, 1:-1] >= relation_offset + relations + ): + raise ValueError(f"{name} has an invalid relation token") + rows = {tuple(map(int, row)) for row in array} + if len(rows) != len(array) or len({row[:-1] for row in rows}) != len(rows): + raise ValueError(f"{name} has duplicate or conflicting queries") + tuples[name] = rows + counts[name] = len(array) + digest.update(name.encode()) + digest.update(np.asarray(array.shape, dtype="= threshold for row in triple): + row = triple[0] + result.update( + reached=True, + step=row["step"], + confirmed_at_step=triple[-1]["step"], + previous_evaluation_step=rows[i - 1]["step"] if i else None, + examples=row["examples"], + atomic_exposures=row["counts"]["atomic"] / counts["atomic"], + composite_exposures=row["counts"]["composite"] / counts["train_composite"], + dataset_passes=row["examples"] / (counts["atomic"] + counts["train_composite"]), + estimated_training_flops=row["estimated_training_flops"], + effective_input_tokens=row["effective_input_tokens"], + supervised_tokens=row["supervised_tokens"], + ) + break + return result + + +def verify_files(root, expected): + for relative, sha in expected.items(): + assert digest(root / relative) == sha, f"Frozen input changed: {relative}" diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_data.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..18cae2dbd6dfdd997883935619a80811eede27d0 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_data.py @@ -0,0 +1,346 @@ +"""Audited data and fixed atomic/composite exposure for loop-depth comparisons. + +The graph, truth, complete-query holdout and phi sampling are inherited from +``grok_multihop_data``. Changing the atomic ID fraction is an explicit design +choice; no graph is regenerated in response to diagnostics or model scores. +""" + +from __future__ import annotations + +import copy +from collections.abc import Mapping + +import numpy as np + +from . import grok_multihop_data as multihop + +SPLITS = multihop.SPLITS +DATA_DEFAULTS = { + "hops": 2, + "entities": 128, + "relations": 16, + "degree": 8, + "phi": 6.0, + "id_fraction": 0.95, + "id_test_fraction": 0.1, + "evaluation_size": 1024, +} + + +def build_world(spec: Mapping) -> dict: + """Adapt a flat run specification while retaining the historical world API. + + ``world_seed`` (or ``seed``) is required. Unrelated model/training keys are + ignored. The default atomic ID/OOD fraction remains 95/5; use an explicit + ``id_fraction=0.75`` for the new composition-experience comparison. + + ``relevant_atomic_indices[split][i, j]`` identifies query i's true hop-j + fact in ``world['atomic']``. These truth indices are evaluation artifacts; + training must only use the original atomic and train-composite rows. + """ + if "world_seed" not in spec and "seed" not in spec: + raise ValueError("spec must contain world_seed or seed") + seed = spec.get("world_seed", spec.get("seed")) + fields = {key: spec.get(key, default) for key, default in DATA_DEFAULTS.items()} + world = multihop.build_world(seed, **fields) + world["relevant_atomic_indices"] = { + name: query_atomic_indices(world, world[name]) for name in SPLITS + } + world["metadata"]["loop_data_diagnostics"] = data_diagnostics(world) + world["metadata"]["loop_data_contract"] = { + "constructor": "grok_multihop_data.build_world", + "world_selection": "fixed supplied seed; no diagnostic or model-based selection", + "all_atomic_rows_are_training_facts": True, + "ood_definition": "all constituent facts absent from composite training by split", + "query_fact_indices": "evaluation truth only; no intermediate-entity supervision", + "suffix_statistics": "within-split descriptive counts; not fitted or held-out predictors", + } + audit_world(world) + return world + + +def query_atomic_indices(world: dict, rows: np.ndarray) -> np.ndarray: + """Return true constituent fact indices, including [N, 1] for atomics.""" + meta = world["metadata"] + _, edges = multihop.path_details( + rows, world["atomic"], int(meta["entities"]), int(meta["relations"]) + ) + return edges + + +def audit_world(world: dict) -> dict: + """Independently verify truth, ID/OOD partitions and recorded fact indices. + + The reused auditor checks truth by graph traversal and counts all-ID and + all-OOD paths by dynamic programming, independently of path construction. + Neither correct-looking diagnostics nor a saved metadata hash substitutes + for those checks. + """ + result = multihop.audit_world(world) + recorded = world.get("relevant_atomic_indices") + if recorded is not None: + if set(recorded) != set(SPLITS): + raise ValueError("Relevant atomic indices must cover every data split") + for name in SPLITS: + expected = query_atomic_indices(world, world[name]) + if ( + not isinstance(recorded[name], np.ndarray) + or recorded[name].dtype != np.int64 + or not np.array_equal(recorded[name], expected) + ): + raise ValueError(f"Incorrect relevant atomic indices: {name}") + if result["dataset_sha256"] != world["metadata"].get("dataset_sha256"): + raise ValueError("Recorded dataset hash disagrees with actual data") + return {**result, "relevant_atomic_indices_checked": recorded is not None} + + +def suffix_target_diagnostics(rows: np.ndarray) -> list[dict]: + """Describe target concentration after omitting the head and prefix relations. + + The empirical modal fraction sums each suffix group's largest target count + and divides by query count. It uses the same rows to count and summarize; + singleton suffixes score one automatically. It is not a model-independent + generalization bound, a learned baseline, or proof that heads are unnecessary. + """ + results = [] + n = len(rows) + for length in range(1, rows.shape[1] - 1): + suffix = rows[:, -(length + 1) : -1] + if not n: + results.append( + { + "suffix_relation_count": length, + "groups": 0, + "empirical_modal_target_fraction": None, + "single_target_group_query_fraction": None, + "singleton_group_query_fraction": None, + "multi_query_groups": 0, + "multi_query_coverage_fraction": None, + "multi_query_empirical_modal_target_fraction": None, + "multi_target_groups": 0, + "same_suffix_different_target_example": None, + } + ) + continue + _, groups, totals = np.unique(suffix, axis=0, return_inverse=True, return_counts=True) + pairs, pair_counts = np.unique(np.c_[groups, rows[:, -1]], axis=0, return_counts=True) + maxima = np.zeros(len(totals), dtype=np.int64) + np.maximum.at(maxima, pairs[:, 0], pair_counts) + multi = totals > 1 + multi_n = int(totals[multi].sum()) + multi_target = maxima != totals + example = None + if multi_target.any(): + # Deterministic first lexicographic suffix with incompatible targets. + group = int(np.flatnonzero(multi_target)[0]) + members = np.flatnonzero(groups == group) + first = members[0] + second = members[np.flatnonzero(rows[members, -1] != rows[first, -1])[0]] + example = [rows[first].tolist(), rows[second].tolist()] + results.append( + { + "suffix_relation_count": length, + "groups": len(totals), + "empirical_modal_target_fraction": float(maxima.sum() / n), + "single_target_group_query_fraction": float(totals[maxima == totals].sum() / n), + "singleton_group_query_fraction": float((totals == 1).sum() / n), + "multi_query_groups": int(multi.sum()), + "multi_query_coverage_fraction": float(multi_n / n), + "multi_query_empirical_modal_target_fraction": ( + float(maxima[multi].sum() / multi_n) if multi_n else None + ), + "multi_target_groups": int(multi_target.sum()), + "same_suffix_different_target_example": example, + } + ) + return results + + +def majority_tail_diagnostics(rows: np.ndarray) -> dict: + """Report the empirical within-split majority target, without fitting a model.""" + if not len(rows): + return {"target_token": None, "count": 0, "fraction": None, "distinct_targets": 0} + targets, counts = np.unique(rows[:, -1], return_counts=True) + index = int(counts.argmax()) + return { + "target_token": int(targets[index]), + "count": int(counts[index]), + "fraction": float(counts[index] / len(rows)), + "distinct_targets": len(targets), + } + + +def data_diagnostics(world: dict) -> dict: + """Pure data coverage and target distributions; never evaluate a predictor.""" + atomic_n = len(world["atomic"]) + indices = world.get("relevant_atomic_indices") + if indices is None: + indices = {name: query_atomic_indices(world, world[name]) for name in SPLITS} + training_counts = np.bincount(indices["train_composite"].ravel(), minlength=atomic_n) + id_facts = np.zeros(atomic_n, dtype=bool) + id_facts[indices["id_atomic"].ravel()] = True + training_majority = majority_tail_diagnostics(world["train_composite"]) + per_split = {} + for name in SPLITS: + rows, edges = world[name], indices[name] + distinct = np.unique(edges) + trained = training_counts[edges] > 0 + all_id, all_ood = id_facts[edges].all(axis=1), (~id_facts[edges]).all(axis=1) + per_split[name] = { + "n": len(rows), + "unique_relevant_atomic_facts": len(distinct), + "relevant_atomic_fact_coverage_of_graph": len(distinct) / atomic_n, + "all_relevant_facts_in_atomic_training_fraction": 1.0 if len(rows) else None, + "all_relevant_facts_in_composite_training_n": int(trained.all(axis=1).sum()), + "any_relevant_fact_in_composite_training_n": int(trained.any(axis=1).sum()), + "relevant_fact_occurrences_seen_in_composite_training_fraction": ( + float(trained.mean()) if edges.size else None + ), + "all_id_queries": int(all_id.sum()), + "all_ood_queries": int(all_ood.sum()), + "mixed_queries": int((~all_id & ~all_ood).sum()), + "unique_relevant_facts_by_hop": [ + len(np.unique(edges[:, j])) for j in range(edges.shape[1]) + ], + "within_split_majority_tail": majority_tail_diagnostics(rows), + "train_composite_majority_tail_fraction": ( + float((rows[:, -1] == training_majority["target_token"]).mean()) + if len(rows) and training_majority["target_token"] is not None + else None + ), + "suffix_without_head": suffix_target_diagnostics(rows), + } + return { + "interpretation": { + "atomic_coverage": "data availability only; does not establish model mastery", + "ood": "all facts are atomic training facts; none has composite-training experience", + "suffix": ( + "empirical within-split target concentration; singleton suffixes score 1; " + "not a predictor, generalization bound, or evidence that the model ignores head" + ), + "majority": "within-split descriptive ceiling plus fixed training-majority fraction", + }, + "atomic_facts": atomic_n, + "id_facts": int(id_facts.sum()), + "ood_facts": int((~id_facts).sum()), + "id_facts_seen_in_composite_training": int((training_counts[id_facts] > 0).sum()), + "ood_facts_seen_in_composite_training": int((training_counts[~id_facts] > 0).sum()), + "train_composite_fact_occurrence_counts": training_counts.tolist(), + "splits": per_split, + } + + +class _EpochStream: + """NumPy-only shuffled epochs, with the existing EpochStream draw convention.""" + + def __init__(self, size: int, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def take(self, n: int) -> np.ndarray: + if not n: + return np.empty(0, dtype=np.int64) + parts = [] + while n: + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(n, len(self.remaining)) + parts.append(self.remaining[:count]) + self.remaining = self.remaining[count:] + n -= count + return np.concatenate(parts) + + def state_dict(self) -> dict: + return { + "size": self.size, + "rng": copy.deepcopy(self.rng.bit_generator.state), + "remaining": self.remaining.copy(), + } + + def load_state_dict(self, state: dict): + if state["size"] != self.size: + raise ValueError("Epoch size mismatch") + remaining = np.asarray(state["remaining"]) + if ( + remaining.ndim != 1 + or remaining.dtype != np.int64 + or np.any((remaining < 0) | (remaining >= self.size)) + or len(np.unique(remaining)) != len(remaining) + ): + raise ValueError("Invalid remaining epoch indices") + self.rng.bit_generator.state = copy.deepcopy(state["rng"]) + self.remaining = remaining.copy() + + +class StratifiedStream: + """Fixed composition per batch over the table [atomics; train_composites]. + + Atomic, composite and interleaving draws use independent RNGs. Thus changing + phi or the composite pool cannot change the atomic sequence or its batch + positions. Individual strata use shuffled epochs and may cross an epoch + boundary within one batch. No evaluation data enters either stream. + """ + + def __init__( + self, atomic_size: int, composite_size: int, batch_size: int, n_atomic: int, seed: int + ): + fields = { + "atomic_size": atomic_size, + "composite_size": composite_size, + "batch_size": batch_size, + "n_atomic": n_atomic, + } + for name, value in fields.items(): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 0: + raise ValueError(f"{name} must be a nonnegative integer") + if batch_size < 1 or n_atomic > batch_size: + raise ValueError("Require batch_size > 0 and 0 <= n_atomic <= batch_size") + if (n_atomic and not atomic_size) or (batch_size > n_atomic and not composite_size): + raise ValueError("A sampled stratum cannot be empty") + self.atomic_size, self.composite_size = int(atomic_size), int(composite_size) + self.batch_size, self.n_atomic = int(batch_size), int(n_atomic) + self.atomic = _EpochStream(atomic_size, np.random.SeedSequence([int(seed), 145101])) + self.composite = _EpochStream(composite_size, np.random.SeedSequence([int(seed), 145102])) + self.interleave = np.random.default_rng(np.random.SeedSequence([int(seed), 145103])) + self.batches = 0 + + def take(self, n: int | None = None) -> np.ndarray: + if n is not None and n != self.batch_size: + raise ValueError("StratifiedStream only emits its configured batch_size") + indices = np.r_[ + self.atomic.take(self.n_atomic), + self.composite.take(self.batch_size - self.n_atomic) + self.atomic_size, + ] + self.batches += 1 + return indices[self.interleave.permutation(self.batch_size)] + + def state_dict(self) -> dict: + return { + "version": 1, + "atomic_size": self.atomic_size, + "composite_size": self.composite_size, + "batch_size": self.batch_size, + "n_atomic": self.n_atomic, + "atomic": self.atomic.state_dict(), + "composite": self.composite.state_dict(), + "interleave_rng": copy.deepcopy(self.interleave.bit_generator.state), + "batches": self.batches, + } + + def load_state_dict(self, state: dict): + if state.get("version") != 1: + raise ValueError("Unsupported StratifiedStream state version") + for name in ("atomic_size", "composite_size", "batch_size", "n_atomic"): + if state[name] != getattr(self, name): + raise ValueError(f"StratifiedStream {name} mismatch") + atomic, composite = copy.deepcopy(self.atomic), copy.deepcopy(self.composite) + interleave = copy.deepcopy(self.interleave) + atomic.load_state_dict(state["atomic"]) + composite.load_state_dict(state["composite"]) + interleave.bit_generator.state = copy.deepcopy(state["interleave_rng"]) + batches = state["batches"] + if not isinstance(batches, int) or batches < 0: + raise ValueError("Invalid completed batch count") + self.atomic, self.composite, self.interleave = atomic, composite, interleave + self.batches = batches diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_mechanism.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd1ad614952efa432b820d8f26f1e282657a947 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_mechanism.py @@ -0,0 +1,549 @@ +"""Prefix-only component interventions at every executed Transformer block. + +The recipient block runs normally before mixing cached attention and MLP +increments at r1. The current block's MLP is never recomputed after mixing. +Only later blocks consume the intervention. Donors are graph-selected before +evaluating the model and receive only [head, r1] followed by fixed PAD tokens. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections import Counter, defaultdict +from numbers import Integral + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_multihop import pack_rows + +COMPONENTS = ("attention", "mlp", "both", "full") +SPLITS = ("test_composite", "test_full_composite", "ood_composite") +TRACE_FIELDS = ("input", "attention", "mlp", "residual") + + +def _choose(candidates, world_hash, seed, row, family): + if not candidates: + return None + material = json.dumps([world_hash, int(seed), list(map(int, row)), family]) + index = int.from_bytes(hashlib.sha256(material.encode()).digest(), "big") % len(candidates) + return sorted(candidates)[index] + + +def _path(head, relations, graph): + edges = [] + for relation in relations: + fact = graph.get((int(head), int(relation))) + if fact is None: + return None + head, index = fact + edges.append(index) + return int(head), tuple(edges) + + +def select_donors(world, seed, split="test_composite"): + """Select same-r1 donors using only truth and split membership. + + ID recipients and every donor-path fact are restricted to ID facts. OOD + recipients and donor paths analogously use only OOD facts. Different-bridge + paths must change the target and their complete queries must be untrained. + Same-bridge paths may be trained; their split is saved for separate scoring. + Rows without donors remain present with explicit masks and reasons. + """ + if split not in SPLITS: + raise ValueError(f"split must be one of {SPLITS}") + rows = world[split] + n, hops = len(rows), rows.shape[1] - 2 + if not 2 <= hops <= 4: + raise ValueError("Interventions require two-, three- or four-hop rows") + atom_index = {tuple(map(int, row)): i for i, row in enumerate(world["atomic"])} + atomic_split = "ood_atomic" if split == "ood_composite" else "id_atomic" + graph = { + (int(h), int(r)): (int(t), atom_index[int(h), int(r), int(t)]) + for h, r, t in world[atomic_split] + } + by_relation = defaultdict(list) + for (head, relation), (tail, _) in graph.items(): + by_relation[relation].append((head, relation, tail)) + training = {tuple(map(int, row[:-1])) for row in world["train_composite"]} + reserved = {tuple(map(int, row[:-1])) for row in world["test_full_composite"]} + result = { + "split": np.asarray(split), + "atomic_split": np.asarray(atomic_split), + "original_rows": rows.copy(), + "original_bridge": np.full(n, -1, dtype=np.int64), + "original_atomic_indices": np.full((n, hops), -1, dtype=np.int64), + } + for family in ("different", "same"): + result.update( + { + family + "_donor": np.full((n, 3), -1, dtype=np.int64), + family + "_counterfactual_rows": np.full_like(rows, -1), + family + "_atomic_indices": np.full((n, hops), -1, dtype=np.int64), + family + "_valid": np.zeros(n, dtype=bool), + family + "_candidate_count": np.zeros(n, dtype=np.int64), + family + "_reason": np.full(n, "no_eligible_same_relation_path", dtype="U64"), + family + "_counterfactual_split": np.full(n, "missing", dtype="U16"), + } + ) + reasons = ( + "same_head", + "same_bridge", + "missing_successor", + "same_target", + "head_is_answer", + "trained_counterfactual", + ) + for reason in reasons: + result["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) + for i, row in enumerate(rows): + head, r1, target = int(row[0]), int(row[1]), int(row[-1]) + original = _path(head, row[1:-1], graph) + if original is None or original[0] != target: + raise ValueError(f"Recipient is not a true all-{atomic_split} path") + bridge = graph[head, r1][0] + result["original_bridge"][i] = bridge + result["original_atomic_indices"][i] = original[1] + candidates = {"different": [], "same": []} + for dh, dr, db in by_relation[r1]: + continuation = _path(dh, row[1:-1], graph) + if continuation is None: + reason = "missing_successor" + else: + dt, edges = continuation + query = (dh, *map(int, row[1:-1])) + if dh != head and db == bridge and dh != target: + candidates["same"].append((dh, dr, db, dt, edges)) + reason = ( + "same_head" + if dh == head + else "same_bridge" + if db == bridge + else "same_target" + if dt == target + else "head_is_answer" + if dh in (target, dt) + else "trained_counterfactual" + if query in training + else None + ) + if reason is None: + candidates["different"].append((dh, dr, db, dt, edges)) + if reason: + result["different_rejected_" + reason][i] += 1 + for family in ("different", "same"): + choices = candidates[family] + result[family + "_candidate_count"][i] = len(choices) + donor = _choose(choices, world["metadata"]["dataset_sha256"], seed, row, family) + if donor is None: + continue + dh, dr, db, dt, edges = donor + cf = (dh, *map(int, row[1:-1]), dt) + result[family + "_donor"][i] = dh, dr, db + result[family + "_counterfactual_rows"][i] = cf + result[family + "_atomic_indices"][i] = edges + result[family + "_valid"][i] = True + result[family + "_reason"][i] = "eligible" + result[family + "_counterfactual_split"][i] = ( + "ood" + if split == "ood_composite" + else "train" + if cf[:-1] in training + else "reserved_test" + if cf[:-1] in reserved + else "unused" + ) + return result + + +def executed_blocks(model): + return list(model.iter_blocks()) if hasattr(model, "iter_blocks") else list(model.blocks) + + +@torch.no_grad() +def traced_forward( + model, + tokens, + positions=None, + *, + patch_layer=None, + component="both", + donor_trace=None, + identity=False, + return_trace=False, +): + """Run eval forward, optionally mixing one executed layer's r1 state. + + Trace fields contain only position r1, with shape [batch, width]. For a + component patch the output is (recipient input + mixed A) + mixed M. Full + replacement also changes the incoming residual, so it equals replacing A + and M only at execution layer zero for same-r1 donors, not at later layers. + """ + if model.training: + raise ValueError("Interventions require model.eval()") + blocks = executed_blocks(model) + if component not in COMPONENTS: + raise ValueError(f"component must be one of {COMPONENTS}") + if patch_layer is not None and ( + isinstance(patch_layer, bool) + or not isinstance(patch_layer, Integral) + or not 0 <= patch_layer < len(blocks) + ): + raise ValueError("patch_layer must index an executed block") + if identity and donor_trace is not None: + raise ValueError("Identity and donor patches are mutually exclusive") + if (donor_trace is not None or identity) != (patch_layer is not None): + raise ValueError("A patch layer requires exactly one donor or identity patch") + if donor_trace is not None and len(donor_trace) != len(blocks): + raise ValueError("Donor trace must cover every executed layer") + if tokens.shape[1] < 2: + raise ValueError("The r1 position requires at least two tokens") + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + trace = [] + for layer, block in enumerate(blocks): + z = block.ln1(x) + batch, length, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, length, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + a = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=0.0, + ) + a = attention.proj(a.transpose(1, 2).reshape(batch, length, width)) + m = block.mlp(block.ln2(x + a)) + residual = (x + a) + m + current = { + "input": x[:, 1].clone(), + "attention": a[:, 1].clone(), + "mlp": m[:, 1].clone(), + "residual": residual[:, 1].clone(), + } + if return_trace: + trace.append(current) + if layer == patch_layer: + donor = current if identity else donor_trace[layer] + if any(donor[key].shape != current[key].shape for key in TRACE_FIELDS): + raise ValueError("Donor trace has incompatible batch or width") + if component == "full": + replacement = donor["residual"] + else: + mixed_a = donor["attention"] if component in ("attention", "both") else a[:, 1] + mixed_m = donor["mlp"] if component in ("mlp", "both") else m[:, 1] + replacement = (x[:, 1] + mixed_a) + mixed_m + residual = residual.clone() + residual[:, 1] = replacement + x = residual + x = model.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, model.token.weight) + return (logits, trace) if return_trace else logits + + +@torch.no_grad() +def prefix_trace(model, prefixes, padded_length): + """Evaluate only two supplied tokens and a fixed zero suffix; never a target.""" + if prefixes.ndim != 2 or prefixes.shape[1] != 2 or padded_length < 4: + raise ValueError("Need two-token prefixes and the fixed hops+2 sequence length") + tokens = torch.zeros((len(prefixes), padded_length), dtype=torch.long, device=prefixes.device) + tokens[:, :2] = prefixes + positions = torch.ones((len(prefixes), 1), dtype=torch.long, device=prefixes.device) + return traced_forward(model, tokens, positions, return_trace=True)[1] + + +@torch.no_grad() +def evaluate_condition( + model, + rows, + device, + padded_length, + *, + donor_prefixes=None, + patch_layer=None, + component="both", + identity=False, + batch_size=1024, + verify_trace=False, +): + """Generate answer then EOS, reapplying exactly the same donor intervention.""" + if donor_prefixes is not None and donor_prefixes.shape != (len(rows), 2): + raise ValueError("Donor prefixes must align one-to-one with recipient rows") + answers, stops, logits_saved = [], [], [] + max_delta = prefix_delta = 0.0 + packed = pack_rows(rows, padded_length) + for start in range(0, len(rows), batch_size): + x, pos, _ = (torch.as_tensor(a[start : start + batch_size], device=device) for a in packed) + x = x.clone() + donor = None + if donor_prefixes is not None: + prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) + donor = prefix_trace(model, prefixes, padded_length) + arguments = dict( + patch_layer=patch_layer, + component=component, + donor_trace=donor, + identity=identity, + ) + logits, trace = traced_forward(model, x, pos, return_trace=True, **arguments) + if verify_trace: + if patch_layer is not None: + raise ValueError("Native-forward verification applies to baseline only") + reference = model(x, pos) + max_delta = max(max_delta, float((reference - logits).abs().max())) + if not torch.equal(reference.argmax(-1), logits.argmax(-1)): + raise AssertionError("Traced forward changes native argmax") + prefix = prefix_trace(model, x[:, :2], padded_length) + for full, truncated in zip(trace, prefix, strict=True): + for field in TRACE_FIELDS: + prefix_delta = max( + prefix_delta, float((full[field] - truncated[field]).abs().max()) + ) + answer = logits[:, 0].argmax(-1) + logits_saved.append(logits[:, 0].cpu().numpy()) + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + continuation = traced_forward(model, x, pos, **arguments) + if verify_trace: + reference = model(x, pos) + max_delta = max(max_delta, float((reference - continuation).abs().max())) + if not torch.equal(reference.argmax(-1), continuation.argmax(-1)): + raise AssertionError("Generated-answer trace changes native argmax") + answers.append(answer.cpu().numpy()) + stops.append(continuation[:, 1].argmax(-1).cpu().numpy()) + if max_delta > 1e-5 or prefix_delta > 1e-5: + raise AssertionError(f"Native/prefix trace disagreement: {max_delta}, {prefix_delta}") + return { + "answer": np.concatenate(answers) if answers else np.empty(0, dtype=np.int64), + "stop": np.concatenate(stops) if stops else np.empty(0, dtype=np.int64), + "answer_logits": np.concatenate(logits_saved) + if logits_saved + else np.empty((0, model.token.num_embeddings), dtype=np.float32), + }, { + "native_comparison_performed": verify_trace, + "native_max_logit_delta": max_delta, + "prefix_only_vs_full_all_layers_max_delta": prefix_delta, + } + + +def _metrics(arrays, condition, selected, original, target, baseline): + mask = selected & arrays[condition + "_valid"] + n, total = int(mask.sum()), len(mask) + answer, stop = arrays[condition + "_answer"], arrays[condition + "_stop"] + + def mean(value): + return float(value[mask].mean()) if n else None + + return { + "n": n, + "total_n": total, + "coverage": n / total if total else None, + "target_answer_accuracy": mean(answer == target), + "target_complete_accuracy": mean((answer == target) & (stop == 1)), + "original_answer_accuracy": mean(answer == original), + "original_complete_accuracy": mean((answer == original) & (stop == 1)), + "other_answer_rate": mean((answer != target) & (answer != original)), + "eos_accuracy": mean(stop == 1), + "answer_change_rate": mean(answer != baseline), + } + + +def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): + """Evaluate every executed layer, preserving all rows and prerequisite masks.""" + started = time.perf_counter() + model.eval() + split = str(donors["split"].item()) + rows = world[split] + if not np.array_equal(rows, donors["original_rows"]): + raise ValueError("Donor rows differ from the registered evaluation split") + n, padded_length = len(rows), int(world["metadata"]["hops"]) + 2 + arrays = {key: value.copy() for key, value in donors.items()} + all_rows = np.ones(n, dtype=bool) + conditions, audits = {}, {} + + def evaluate(name, mask, inputs, *, family=None, **kwargs): + result, audit = evaluate_condition( + model, inputs[mask], device, padded_length, batch_size=batch_size, **kwargs + ) + for key in ("answer", "stop"): + values = np.full(n, -1, dtype=np.int64) + values[mask] = result[key] + arrays[name + "_" + key] = values + arrays[name + "_valid"] = mask.copy() + targets = rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] + for suffix, labels in (("original_logit", rows[:, -1]), ("target_logit", targets)): + values = np.full(n, np.nan, dtype=np.float32) + values[mask] = result["answer_logits"][np.arange(mask.sum()), labels[mask]] + arrays[name + "_" + suffix] = values + conditions[name] = { + "family": family, + **{k: v for k, v in kwargs.items() if k in ("patch_layer", "component", "identity")}, + } + audits[name] = audit + + evaluate("baseline", all_rows, rows, verify_trace=True) + for family in ("different", "same"): + valid = donors[family + "_valid"] + # Match batch shape as well as sequence shape for floating-point controls. + evaluate(family + "_matched_baseline", valid, rows, family=family) + evaluate( + family + "_counterfactual_input", + valid, + donors[family + "_counterfactual_rows"], + family=family, + ) + blocks = executed_blocks(model) + for layer in range(len(blocks)): + for component in COMPONENTS: + identity_name = f"e{layer:03d}_identity_{component}" + evaluate( + identity_name, all_rows, rows, patch_layer=layer, component=component, identity=True + ) + for key in ("answer", "stop", "original_logit", "target_logit"): + if not np.array_equal(arrays[identity_name + "_" + key], arrays["baseline_" + key]): + raise AssertionError(f"Identity patch changes {identity_name}.{key}") + for family in ("different", "same"): + valid = donors[family + "_valid"] + name = f"e{layer:03d}_{family}_{component}" + evaluate( + name, + valid, + rows, + family=family, + patch_layer=layer, + component=component, + donor_prefixes=donors[family + "_donor"][valid, :2], + ) + if layer == len(blocks) - 1: + for key in ("answer", "stop", "original_logit"): + if not np.array_equal( + arrays[name + "_" + key][valid], + arrays[family + "_matched_baseline_" + key][valid], + ): + raise AssertionError("Last-block r1 patch changes later answer/EOS") + if layer == 0: + for family in ("different", "same"): + valid = donors[family + "_valid"] + for key in ("answer", "stop", "original_logit", "target_logit"): + left = arrays[f"e000_{family}_both_{key}"][valid] + right = arrays[f"e000_{family}_full_{key}"][valid] + if not np.array_equal(left, right): + raise AssertionError("First-layer same-r1 both/full differ") + atomics, _ = evaluate_condition( + model, world["atomic"], device, padded_length, batch_size=batch_size + ) + atom_correct = (atomics["answer"] == world["atomic"][:, -1]) & (atomics["stop"] == 1) + arrays["atomic_rows"] = world["atomic"].copy() + arrays["atomic_answer"], arrays["atomic_stop"] = atomics["answer"], atomics["stop"] + groups = {"all_rows": all_rows} + prerequisites = {} + for family in ("original", "different", "same"): + valid = all_rows if family == "original" else donors[family + "_valid"] + indices = donors[family + "_atomic_indices"] + correct = np.zeros_like(indices, dtype=bool) + correct[valid] = atom_correct[indices[valid]] + arrays[family + "_atomic_complete_correct"] = correct + complete = valid & correct.all(axis=1) + groups[family + "_all_atomic_correct"] = complete + prerequisites[family] = { + "n": int(valid.sum()), + "total_n": n, + "coverage": float(valid.mean()) if n else None, + "all_hops_complete_accuracy": float(complete[valid].mean()) if valid.any() else None, + "per_hop_complete_accuracy": correct[valid].mean(axis=0).tolist() + if valid.any() + else None, + } + for family in ("different", "same"): + valid = donors[family + "_valid"] + baseline_correct = (arrays[family + "_matched_baseline_answer"] == rows[:, -1]) & ( + arrays[family + "_matched_baseline_stop"] == 1 + ) + groups[family + "_donor_available"] = valid + groups[family + "_donor_missing"] = ~valid + cf = family + "_counterfactual_input" + cf_correct = valid & ( + arrays[cf + "_answer"] == donors[family + "_counterfactual_rows"][:, -1] + ) + cf_correct &= arrays[cf + "_stop"] == 1 + groups[family + "_native_original_and_counterfactual_correct"] = ( + baseline_correct & cf_correct + ) + for category in ("train", "reserved_test", "unused", "ood"): + groups[family + "_counterfactual_" + category] = valid & ( + donors[family + "_counterfactual_split"] == category + ) + scores = {} + for group, mask in groups.items(): + arrays["subset_" + group] = mask.copy() + scored = {} + for condition, description in conditions.items(): + family = description["family"] + target = ( + rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] + ) + scored[condition] = _metrics( + arrays, + condition, + mask, + rows[:, -1], + target, + arrays[(family + "_matched_baseline" if family else "baseline") + "_answer"], + ) + scores[group] = { + "n": int(mask.sum()), + "total_n": n, + "coverage": float(mask.mean()) if n else None, + "conditions": scored, + } + return { + "split": split, + "atomic_split": str(donors["atomic_split"].item()), + "sample_rule": "training-independent fixed probe" + if split == "test_composite" + else "full split", + "hops": padded_length - 2, + "executed_depth": len(blocks), + "unique_layers": len(model.blocks), + "repeats": getattr(model, "repeats", 1), + "patch_position": 1, + "conditions": conditions, + "scores": scores, + "atomic_preconditions": prerequisites, + "donor_coverage": { + family: { + "n": int(donors[family + "_valid"].sum()), + "total_n": n, + "reasons": dict(Counter(donors[family + "_reason"].tolist())), + "counterfactual_split": dict( + Counter(donors[family + "_counterfactual_split"].tolist()) + ), + } + for family in ("different", "same") + }, + "engineering_checks": { + "native_trace": audits["baseline"], + "identity_all_layers_components": True, + "first_layer_same_r1_both_equals_full": True, + "last_layer_r1_patch_cannot_change_later_answer_or_eos": True, + "donor_nonpadding_tokens": 2, + "donor_padded_length": padded_length, + "mlp_recomputed_after_mixing": False, + "eos_uses_generated_answer_and_reapplies_same_patch": True, + }, + "interpretation": ( + "End-to-end prefix-state interventions, not proof that facts reside only in MLP. " + "Component mixtures retain recipient incoming residual. Both/full are equivalent " + "only at first execution layer with same r1; later differences are expected. " + "Facts and queries within one world are not independent experimental worlds." + ), + "evaluation_seconds": time.perf_counter() - started, + }, arrays diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_model.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed46483cb7277c172f8848cefb9e2d085d67c0b --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_model.py @@ -0,0 +1,108 @@ +"""Depth-shared GPT blocks for controlled composition-learning comparisons. + +This keeps the existing SmallGPT tokenization, causal attention, dropout and tied +readout. ``config.layers`` counts independently parameterized blocks; each loop +executes this whole block group. Positions and token embeddings are added once. +""" + +from __future__ import annotations + +import math +from dataclasses import replace +from numbers import Integral + +import torch +from torch.nn import functional as F + +from .bios_model import matmul_flops +from .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, + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f3cac329831b303c1dc9ca05c270837de0614eec --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py @@ -0,0 +1,342 @@ +"""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 fed +to the model. ID donors must have actually occurred at the first position of +composite training. OOD donors have zero composite exposure at either position. +All eligible donors and ID x OOD pairs are retained. A pair is a repeated +measurement of its recipient, not an independent query or world. +""" + +from __future__ import annotations + +import hashlib +import json +from collections import defaultdict +from collections.abc import Mapping +from 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 result diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..48fa45f53e08b7da9c17a92df8eb5ba4efd8a229 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py @@ -0,0 +1,353 @@ +"""Same-bridge prefix interventions, with query-balanced donor summaries. + +The donor selector never sees model scores. This evaluator reuses the audited +first-block component mixer; it does not retrain models or recompute the current +MLP after mixing. All candidate donors are evaluated, then averaged within the +recipient query before any world-level aggregation. +""" + +from __future__ import annotations + +import hashlib +import time + +import numpy as np +import 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", + } diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_supervision.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_supervision.py new file mode 100644 index 0000000000000000000000000000000000000000..104364e93299229e1a8216acabb046e5fae1dde4 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_supervision.py @@ -0,0 +1,349 @@ +"""Paired continuation: terminal versus distributed answer supervision. + +Historical model/trainer files remain unchanged. All heads branch off the same +trajectory; their LayerNorm outputs never replace the recurrent residual state. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_data import StratifiedStream +from .grok_loop_model import LoopGPT, flops +from .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, + }, + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_train.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_train.py new file mode 100644 index 0000000000000000000000000000000000000000..ffee809fcc7335c7b68e3321427ffcc0342c3086 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_loop_train.py @@ -0,0 +1,214 @@ +"""Frozen loop comparison trainer with stratified exposure and executed-depth FLOPs.""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_data import StratifiedStream +from .grok_loop_model import LoopGPT, flops +from .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] diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_multihop.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_multihop.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0824b5e038658e91c3cbc5e521a316861f20a4 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_multihop.py @@ -0,0 +1,278 @@ +"""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 json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_json +from .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] diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_multihop_data.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_multihop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d857233765485dc4bf1a210fda171628a20d9817 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_multihop_data.py @@ -0,0 +1,245 @@ +"""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 and +one 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 hashlib +import math + +import numpy as np + +from .grok_depth_data import ENTITY_OFFSET +from .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="= 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, + } diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_usage_data.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_usage_data.py new file mode 100644 index 0000000000000000000000000000000000000000..04e5650b0bdea1e25cfde235045efc9b14e0c769 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_usage_data.py @@ -0,0 +1,397 @@ +"""Paired fact-use assignments and constituent-occurrence repetition controls. + +The same random graph and held-out queries are used in every arm. A/B change +which random fact cohort may occur in composition training. repA/repB replace +each 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 copy +import hashlib +from collections.abc import Mapping + +import numpy as np + +from .grok_depth_data import build_world as build_graph_world +from .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=" 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"] diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_usage_train.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_usage_train.py new file mode 100644 index 0000000000000000000000000000000000000000..8460dcf149ad8f229cc4c16783e8e7429acd0610 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grok_usage_train.py @@ -0,0 +1,261 @@ +"""Paired training of composition experience versus constituent-fact repetition.""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .grok_multihop import autonomous_calls, evaluate_rows, pack_rows +from .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(), + }, + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..9530969731263b69c576f12989a3610ead6036f5 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py @@ -0,0 +1,421 @@ +"""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 copy +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step_mechanism import traced_forward +from .grok_depth import write_json +from .latent_scaling import model_digest +from .storage_composition import generate_rows, pack_sentences +from .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 result diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grokking_reproduction.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grokking_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f7ba958ea469d5edea6e98c9941dcc49427a6f --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/grokking_reproduction.py @@ -0,0 +1,563 @@ +"""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 initialization +are retained. SDPA, selecting supervised logits, CUDA graphs and bf16 AMP are +explicit execution/numerical adaptations, checked against Hugging Face GPT-2. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F +from transformers import GPT2Config, GPT2LMHeadModel, GPT2TokenizerFast + +from .bios_model import ModelConfig, matmul_flops +from .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"" for i in range(2000)] + [f"" for i in range(200)] + vocab += ["", "", "", "", "", ""] + 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(""), + "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 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) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_data.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_data.py new file mode 100644 index 0000000000000000000000000000000000000000..b67eee718fd00d44c1de51a2821e24aa7251196b --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_data.py @@ -0,0 +1,396 @@ +"""CounterFact true-label data, explicit audit decisions and indivisible subject pools.""" + +from __future__ import annotations + +import hashlib +import re +import unicodedata +from 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"(? 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 coverage diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_followup.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..89afed17153ba18880997b4089ddadb1b997f80b --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_followup.py @@ -0,0 +1,103 @@ +"""Fixed-content worlds and conservative full-entity answer parsing.""" + +from __future__ import annotations + +import hashlib +import re +import unicodedata +from 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}")) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_future.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_future.py new file mode 100644 index 0000000000000000000000000000000000000000..24171d0e5bc0c31f7cc4ac32af06d86dd8ec15f4 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_future.py @@ -0,0 +1,148 @@ +"""Exploratory kernel prediction and balanced multi-hop worlds, September 2026.""" + +from __future__ import annotations + +import hashlib +import json +from 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])] diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_interface.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..0135ee958b76df5e2df2aa4ea0c2c57c40f2b24a --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_interface.py @@ -0,0 +1,566 @@ +"""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 hashlib +import importlib.metadata +import json +import platform +import sys +import time +from dataclasses import asdict +from pathlib import Path + +import numpy as np +import torch +import 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 summary diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_learning.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..78155602739f614f369304edc920dbb75b590bea --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_learning.py @@ -0,0 +1,187 @@ +"""Prospective Hebbian study: numerical calibration and auditable common primitives.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import math +import os +from datetime import datetime, timezone +from 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()) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_model.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_model.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8e5da864f18f673c829d8b68db641d728ca437 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_model.py @@ -0,0 +1,339 @@ +"""FP32 Qwen adapter. All CE/KL reductions preserve per-sequence weighting.""" + +from __future__ import annotations + +import copy +import hashlib +import os +import time + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import AutoModelForCausalLM, AutoTokenizer, StoppingCriteria, StoppingCriteriaList + +from .hebbian_data import TEMPLATE, score_answer +from .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}, + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_statistics.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..52bcc965886f86bf20041ec40ce6aa95b96a725f --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_statistics.py @@ -0,0 +1,168 @@ +"""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 None diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_train.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_train.py new file mode 100644 index 0000000000000000000000000000000000000000..f70905fa1648aeba1d7bad8aca55a77bbcadd72f --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/hebbian_train.py @@ -0,0 +1,811 @@ +"""Paired formation/adaptation, prospective diagnostics and exact state resumption.""" + +from __future__ import annotations + +import itertools +import json +import random +import time + +import numpy as np +import torch +import 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", + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/independent_alignment.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/independent_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..88bc143ff025e794e6a5f1ec62e514b99563d88b --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/independent_alignment.py @@ -0,0 +1,124 @@ +"""Replicate the existing state objective in two ordinary, independent GPT layers.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import representation_alignment as original +from .grok_depth import write_json +from .latent_scaling import build_world, model_digest +from .storage_composition import data_digest, evaluate, file_hash + + +def validate_model(spec, model): + if spec["layers"] != 2 or spec["repeats"] != 1: + raise ValueError("This replication requires two independent layers, executed once") + blocks = list(model.iter_blocks()) + assert len(blocks) == 2 and blocks[0] is not blocks[1] + assert not {p.data_ptr() for p in blocks[0].parameters()} & { + p.data_ptr() for p in blocks[1].parameters() + } + assert all(p.requires_grad for p in model.parameters()) + + +@torch.no_grad() +def diagnose(model, world, device): + """Original readout of a pure first-hop prefix; no fitted probe or final answer.""" + model.eval() + metrics, predictions = {}, {} + for task in ("common_atomic", "familiar_test", "strict_test"): + rows = world[task] + prefixes = np.column_stack( + (np.full(len(rows), 2), rows[:, 0], np.full(len(rows), 3), rows[:, 1]) + ) + labels = rows[:, 2] + guesses, cosines = [], [] + for start in range(0, len(rows), 256): + tokens = torch.as_tensor(prefixes[start : start + 256], device=device) + targets = torch.as_tensor(labels[start : start + 256], device=device) + _, state = model(tokens, return_bridge=True) + logits = F.linear(model.ln_final(state), model.token.weight) + guesses.append(logits.argmax(-1).cpu().numpy()) + cosines.append(F.cosine_similarity(state, model.token(targets)).cpu().numpy()) + guess, cosine = np.concatenate(guesses), np.concatenate(cosines) + correct = guess == labels + metrics[task] = dict( + n=len(rows), + first_hop_original_readout_accuracy=float(correct.mean()), + mean_cosine_to_input_embedding=float(cosine.mean()), + pure_prefix=True, + ) + predictions.update( + {task + "_guess": guess, task + "_correct": correct, task + "_cosine": cosine} + ) + return metrics, predictions + + +def train(spec, out, source, device): + model = original.new_model(spec, "cpu") + validate_model(spec, model) + assert model_digest(model) == spec["initial_model_sha256"] + assert data_digest(build_world(spec)) == spec["data_sha256"] + del model + # Keep the historical trainer, objective, sampling, optimizer and arithmetic intact. + original.train(spec, out, source, device) + out = Path(out) + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + model = original.new_model(spec, device) + model.load_state_dict(payload["model"]) + metrics, predictions = diagnose(model, build_world(spec), device) + write_json(out / "state-diagnostics.json", metrics) + np.savez_compressed(out / "state-predictions.npz", **predictions) + + +def audit(out, device): + """Independent process reload of full generation and original intermediate readout.""" + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + spec = payload["spec"] + model = original.new_model(spec, device) + validate_model(spec, model) + model.load_state_dict(payload["model"]) + world = build_world(spec) + stored_world = np.load(out / "world.npz") + for key, value in world.items(): + np.testing.assert_array_equal(value, stored_world[key]) + assert data_digest(world) == spec["data_sha256"] + complete = json.loads((out / "complete.json").read_text()) + assert file_hash(out / "model.pt") == complete["model_sha256"] + metrics, predictions = evaluate(model, world, "low", device) + saved = np.load(out / f"predictions-{spec['steps']:06d}.npz") + maximum = 0.0 + for key, value in predictions.items(): + if key.endswith("nll"): + maximum = max(maximum, float(np.max(np.abs(value - saved[key])))) + np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(value, saved[key]) + state_metrics, state_predictions = diagnose(model, world, device) + saved_state = np.load(out / "state-predictions.npz") + for key, value in state_predictions.items(): + if key.endswith("cosine"): + np.testing.assert_allclose(value, saved_state[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(value, saved_state[key]) + write_json( + out / "audit.json", + dict( + passed=True, + metrics=metrics, + state_metrics=state_metrics, + max_nll_error=maximum, + allow_tf32=True, + independent_parameters=True, + ), + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/interface_editing.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/interface_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..7065e910e82f4aa54e312af63f4f99925c4e1269 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/interface_editing.py @@ -0,0 +1,759 @@ +"""Local factual updates and downstream composition in existing aligned GPTs. + +Cases are selected from the graph alone, before loading any model predictions. +Every edit has a same-budget old-fact sham, fresh optimizer, and frozen parent +replay reference. No composition labels or intermediate-state targets enter +optimization. Finite replay KL is a regularizer, not exact preservation. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import build_world, model_digest +from .representation_alignment import new_model +from .storage_composition import data_digest, file_hash, generate_rows, pack_sentences + +ROLES = ("first", "second") +STRATA = ("familiar", "strict") +DEFAULT_NODES = (0, 32, 128, 512) + + +def _rows(values, width): + return np.asarray(values, dtype=np.int64).reshape(-1, width) + + +def _unique(values, width): + return _rows(sorted(set(map(tuple, _rows(values, width)))), width) + + +def _hash_json(value): + return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() + + +def _batch_hash(batch): + digest = hashlib.sha256() + for tensor in batch: + array = tensor.detach().cpu().numpy() + digest.update(str(array.dtype).encode()) + digest.update(str(array.shape).encode()) + digest.update(array.tobytes()) + return digest.hexdigest() + + +def learned_atoms(world): + """Only atomics actually supervised in the representation parent.""" + return _unique(np.concatenate([world["common_atomic"], world["anchor_atomic"]]), 3) + + +def composition_pools(world): + """All legal untrained queries, plus the original holdout and training sets.""" + trained = set(map(tuple, world["train_composite"])) + full = _unique(np.concatenate([world["available_composite"], world["familiar_test"]]), 5) + familiar = _rows([r for r in full if tuple(r) not in trained], 5) + return { + "familiar": familiar, + "strict": world["strict_test"].copy(), + "registered_familiar": world["familiar_test"].copy(), + "train": world["train_composite"].copy(), + } + + +def affected(rows, fact, role): + """Whether a query uses this factual address, independently of its answer.""" + columns = (0, 1) if role == "first" else (2, 3) + return (rows[:, columns[0]] == fact[0]) & (rows[:, columns[1]] == fact[1]) + + +def rewrite(rows, old_fact, new_fact, role, lookup): + result = rows.copy() + mask = affected(rows, old_fact, role) + if role == "first": + result[mask, 2] = new_fact[2] + for index in np.flatnonzero(mask): + result[index, 4] = lookup[int(new_fact[2]), int(rows[index, 3])] + else: + result[mask, 4] = new_fact[2] + return result + + +def graph_cases(parent_spec, *, seed=780011, per_cell=2, replay_n=32): + """Return JSON-compatible selected cases and graph-only eligibility counts. + + Each distinct atomic address receives at most one counterfactual per role. + First-hop replacements stay in the original familiar/strict bridge group and + change at least one affected untrained composition answer. Strict cases never + borrow a bridge with composition experience from the familiar group. + """ + if per_cell < 1 or replay_n < 1: + raise ValueError("Positive case and replay counts are required") + world = build_world(parent_spec) + atoms = learned_atoms(world) + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + pools = composition_pools(world) + rng = np.random.default_rng(seed + int(parent_spec["world"])) + candidates, qualification = [], {} + for role in ROLES: + for stratum in STRATA: + rows = pools[stratum] + addresses = _unique(rows[:, [0, 1, 2] if role == "first" else [2, 3, 4]], 3) + bridges = np.unique(rows[:, 2]) + # Include all trained bridges in that group, even if the holdout + # happens not to visit them (strict rows enumerate all chains). + group = world["background_atomic"] if stratum == "familiar" else world["common_atomic"] + group_bridges = np.unique(group[group[:, 1] >= 17, 0]) + if stratum == "strict": + familiar_bridges = world["background_atomic"] + familiar_bridges = familiar_bridges[familiar_bridges[:, 1] >= 17, 0] + group_bridges = np.setdiff1d(group_bridges, familiar_bridges) + bridges = np.union1d(bridges, group_bridges) + tails = np.unique(atoms[atoms[:, 1] >= 17, 2]) + eligible, replacement_count = [], 0 + for old in addresses: + impacted = rows[affected(rows, old, role)] + choices = [] + for value in bridges if role == "first" else tails: + if value == old[2]: + continue + new = [int(old[0]), int(old[1]), int(value)] + updated = rewrite(impacted, old, new, role, lookup) + if np.any(updated[:, -1] != impacted[:, -1]): + choices.append(new) + replacement_count += len(choices) + if choices: + eligible.append((old.tolist(), choices)) + key = f"{role}_{stratum}" + qualification[key] = { + "candidate_addresses": len(addresses), + "eligible_addresses": len(eligible), + "eligible_replacements": replacement_count, + "untrained_queries": len(rows), + } + if len(eligible) < per_cell: + raise ValueError(f"Insufficient graph-qualified {key} cases: {qualification[key]}") + order = rng.permutation(len(eligible))[:per_cell] + for serial, index in enumerate(order): + old, choices = eligible[index] + new = choices[int(rng.integers(len(choices)))] + candidates.append( + { + "case_id": f"{key}-{serial:02d}", + "role": role, + "stratum": stratum, + "old_fact": old, + "new_fact": new, + } + ) + for case in candidates: + tasks, originals = case_tasks(world, case, replay_indices=None) + necessary = set(map(tuple, tasks["necessary_atomic"])) + allowed = [ + i + for i, row in enumerate(atoms) + if tuple(row) != tuple(case["old_fact"]) and tuple(row) not in necessary + ] + if len(allowed) < replay_n: + raise ValueError("Insufficient independent replay atomics") + case["replay_indices"] = sorted(map(int, rng.choice(allowed, replay_n, replace=False))) + case["affected_untrained_n"] = {name: len(rows) for name, rows in originals.items()} + return candidates, qualification + + +def case_tasks(world, case, replay_indices=None): + """Construct E/R/U/D with address-based exclusions and recomputed truth.""" + atoms = learned_atoms(world) + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + old, new, role = case["old_fact"], case["new_fact"], case["role"] + if lookup[tuple(old[:2])] != old[2] or old[:2] != new[:2] or old[2] == new[2]: + raise ValueError("An edit must replace one existing factual value") + tasks = {"E_old": _rows([old], 3), "E_new": _rows([new], 3)} + originals, necessary = {}, [] + for stratum, rows in composition_pools(world).items(): + mask = affected(rows, old, role) + tasks[f"U_{stratum}"] = rows[~mask].copy() + old_rows = rows[mask].copy() + new_rows = rewrite(old_rows, old, new, role, lookup) + changed = old_rows[:, -1] != new_rows[:, -1] + if stratum == "train": + # Training-query transfer is reported separately from held-out D. + name = f"T_{role}_train" + originals[name] = old_rows + tasks[name] = new_rows + else: + name = f"D_{role}_{stratum}" + originals[name] = old_rows[changed] + tasks[name] = new_rows[changed] + same = f"S_same_answer_{role}_{stratum}" + originals[same] = old_rows[~changed] + tasks[same] = new_rows[~changed] + if stratum in STRATA: + for h, r1, b, r2, t in tasks[name]: + prerequisite = (b, r2, t) if role == "first" else (h, r1, b) + necessary.append(prerequisite) + tasks["necessary_atomic"] = _unique(necessary, 3) + replay = case.get("replay_indices", []) if replay_indices is None else replay_indices + if len(set(replay)) != len(replay): + raise ValueError("Replay indices must be unique") + target = np.flatnonzero(np.all(atoms == np.asarray(old), axis=1)) + if len(target) != 1 or int(target[0]) in replay: + raise ValueError("Replay cannot contain the edited address") + tasks["R_atomic"] = atoms[replay].copy() + tasks["U_atomic"] = np.delete(atoms, [int(target[0]), *replay], axis=0) + return tasks, originals + + +def answer_batch(rows, device): + """Only answer, punctuation and EOS labels; no prefix or bridge labels.""" + tokens, labels = pack_sentences(_rows(rows, 3)) + positions = np.tile([4, 5, 6], (len(rows), 1)) + targets = labels[np.arange(len(rows))[:, None], positions] + expected = np.column_stack([np.asarray(rows)[:, 2], np.full(len(rows), 5), np.ones(len(rows))]) + np.testing.assert_array_equal(targets, expected) + return tuple(torch.as_tensor(x, device=device) for x in (tokens, positions, targets)) + + +def edit_objective(model, target_batch, replay_batch, parent_log, replay_weight=1.0): + target = model(target_batch[0], positions=target_batch[1]) + ce = F.cross_entropy(target.flatten(0, 1), target_batch[2].flatten()) + replay = model(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + if parent_log.requires_grad: + raise ValueError("Replay reference must be detached") + kl = F.kl_div(replay, parent_log, log_target=True, reduction="none").sum(-1).mean() + return ce + replay_weight * kl, ce, kl + + +def _generate(model, rows, device, batch_size): + if len(rows): + return generate_rows(model, rows, device, batch_size=batch_size) + return ( + {"n": 0, "accuracy": None, "answer_accuracy": None, "answer_nll": None}, + { + "generated": np.empty((0, 3), dtype=np.int64), + "correct": np.empty(0, dtype=bool), + "answer_nll": np.empty(0), + }, + ) + + +def evaluate_case(model, tasks, originals, parent_correct, role, device, batch_size=512): + """Full-pool scores and separately labelled prerequisite/parent subsets.""" + metrics, raw = {}, {} + for name, rows in tasks.items(): + values, predictions = _generate(model, rows, device, batch_size) + raw.update({f"{name}__{k}": v for k, v in predictions.items()}) + if name in originals: + old = originals[name] + generated = predictions["generated"] + changed = old[:, -1] != rows[:, -1] + old_correct = (generated[:, 0] == old[:, -1]) & np.all( + generated[:, 1:] == [5, 1], axis=1 + ) + prerequisite = rows[:, [2, 3, 4] if role == "first" else [0, 1, 2]] + _m, needed = _generate(model, prerequisite, device, batch_size) + edited_ok = metrics["E_new"]["accuracy"] == 1.0 + covered = needed["correct"] & edited_ok + baseline = parent_correct[name] + valid_parent = baseline & changed + correct = predictions["correct"] + values.update( + { + "changed_answer_n": int(changed.sum()), + "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None, + "parent_correct_n": int(baseline.sum()), + "parent_correct_coverage": float(baseline.mean()) if len(rows) else None, + "new_following_parent_correct": float(correct[valid_parent].mean()) + if valid_parent.any() + else None, + "old_retained_parent_correct": float(old_correct[valid_parent].mean()) + if valid_parent.any() + else None, + "direct_edit_success": edited_ok, + "necessary_atomic_correct_n": int(needed["correct"].sum()), + "operation_correct_n": int(covered.sum()), + "operation_correct_coverage": float(covered.mean()) if len(rows) else None, + "new_following_operation_correct": float(correct[covered].mean()) + if covered.any() + else None, + } + ) + raw[f"{name}__parent_correct"] = baseline + raw[f"{name}__operation_correct"] = covered + raw[f"{name}__old_correct"] = old_correct + raw[f"{name}__necessary_generated"] = needed["generated"] + raw[f"{name}__new_rows"] = rows + raw[f"{name}__old_rows"] = old + metrics[name] = values + return metrics, raw + + +def editable_parameters(model, scope="mlp", block_index=0): + prefix = f"blocks.{block_index}.mlp." + selected = [ + name + for name, _ in model.named_parameters() + if name.startswith(prefix) and (scope == "mlp" or name == prefix + "down.weight") + ] + if scope not in {"mlp", "down"} or not selected: + raise ValueError("Unknown or empty local parameter scope") + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name in selected) + parameter.grad = None + return selected + + +def _configure(device): + device = torch.device(device) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + return device + + +def _load_parent(parent_dir, device): + path = Path(parent_dir) / "model.pt" + payload = torch.load(path, map_location="cpu", weights_only=False) + model = new_model(payload["spec"], device).eval() + model.load_state_dict(payload["model"]) + world = build_world(payload["spec"]) + if (Path(parent_dir) / "world.npz").exists(): + with np.load(Path(parent_dir) / "world.npz") as saved: + for name, rows in world.items(): + np.testing.assert_array_equal(rows, saved[name]) + return model, world, payload["spec"] + + +def _parent_masks(parent, originals, device, batch_size): + return { + name: _generate(parent, rows, device, batch_size)[1]["correct"] + for name, rows in originals.items() + } + + +def run(spec, out, device="cuda:0"): + """Execute one parent, a graph-selected case set and optional development lr grid. + + The caller owns source freezing, resource allocation and W&B startup. Each + branch has run/learning/complete artifacts. Root ``step`` is a strictly + increasing evaluation index, including every branch's unchanged node zero; + ``optimizer_updates`` separately records cumulative optimization work. + Target labels and replay KL positions have separate exposure counters. + ``status.json`` retains completed-branch progress, explicitly labelled in + the manifest; it does not define the tracking series' step axis. + """ + device = _configure(device) + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite an existing attempt: {out}") + nodes = spec.get("nodes", list(DEFAULT_NODES)) + if not nodes or nodes[0] != 0 or nodes != sorted(set(nodes)) or nodes[-1] <= 0: + raise ValueError("Nodes must increase from zero to a positive fixed endpoint") + rates = spec.get("learning_rates", [spec.get("lr", 1e-4)]) + if not rates or any(lr <= 0 for lr in rates) or len(set(rates)) != len(rates): + raise ValueError("Learning rates must be positive and unique") + if spec.get("phase") not in {"development", "engineering"} and len(rates) > 1: + raise ValueError("Learning-rate grids are development-only") + arms = spec.get("arms", ["edit", "sham"]) + if sorted(arms) != ["edit", "sham"]: + raise ValueError("Every case requires paired edit and sham branches") + parent, world, parent_spec = _load_parent(spec["parent_dir"], device) + parent_hash = model_digest(parent) + cases, qualification = graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + if "case_ids" in spec: + requested = set(spec["case_ids"]) + if not requested or not requested <= {c["case_id"] for c in cases}: + raise ValueError("Unknown/empty fixed graph-selected case subset") + cases = [c for c in cases if c["case_id"] in requested] + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "cases": cases, + "qualification": qualification, + "case_sha256": _hash_json(cases), + "parent_file_sha256": file_hash(Path(spec["parent_dir"]) / "model.pt"), + "parent_model_sha256": parent_hash, + "world_sha256": data_digest(world), + "created_utc": utc(), + "dtype": "float32", + "allow_tf32": True, + "pid": os.getpid(), + "gpu": device.index if device.type == "cuda" else None, + "branches": len(cases) * len(rates) * len(arms), + "planned_updates": len(cases) * len(rates) * len(arms) * nodes[-1], + "planned_evaluations": len(cases) * len(rates) * len(arms) * len(nodes), + "learning_step_unit": "evaluation_index", + "status_step_unit": "completed_branches", + "scope_warning": "The selected MLP is shared across all repeated executions", + } + write_json(out / "run.json", manifest) + write_json(out / "cases.json", cases) + np.savez_compressed(out / "world.npz", **world) + root_learning, branch_summaries, completed_steps = [], [], 0 + started = time.perf_counter() + training_seconds = 0.0 + batch_size = spec.get("eval_batch_size", 512) + for case in cases: + tasks, originals = case_tasks(world, case) + parent_correct = _parent_masks(parent, originals, device, batch_size) + parent_metrics, parent_predictions = evaluate_case( + parent, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + case_out = out / case["case_id"] + case_out.mkdir() + np.savez_compressed(case_out / "parent-predictions.npz", **parent_predictions) + write_json(case_out / "parent-metrics.json", parent_metrics) + np.savez_compressed(case_out / "tasks.npz", **tasks) + replay_batch = answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + parent_log = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1).detach() + for lr in rates: + for arm in arms: + branch_name = f"lr{lr:.8g}-{arm}" + branch_out = case_out / branch_name + branch_out.mkdir() + model = copy.deepcopy(parent).eval() + selected = editable_parameters( + model, + spec.get("parameter_scope", "mlp"), + spec.get("block_index", 0), + ) + parameters = dict(model.named_parameters()) + optimizer = torch.optim.Adam([parameters[n] for n in selected], lr=lr) + target = tasks["E_new" if arm == "edit" else "E_old"] + target_batch = answer_batch(target, device) + write_json( + branch_out / "run.json", + { + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + "parent_model_sha256": parent_hash, + "editable_parameters": selected, + "optimizer": "Adam, fresh state, zero weight decay", + "sampling": "same fixed full replay batch on every update; no dropout", + "old_fact_sha256": _hash_json(case["old_fact"]), + "new_fact_sha256": _hash_json(case["new_fact"]), + "target_batch_sha256": _batch_hash(target_batch), + "replay_batch_sha256": _batch_hash(replay_batch), + "parent_reference_sha256": _batch_hash((parent_log,)), + "nodes": nodes, + }, + ) + np.savez_compressed( + branch_out / "replay-reference.npz", log_probabilities=parent_log.cpu().numpy() + ) + step, losses, history = 0, [], [] + for node in nodes: + if device.type == "cuda": + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, ce, kl = edit_objective( + model, + target_batch, + replay_batch, + parent_log, + spec.get("replay_weight", 1.0), + ) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite edit loss at {step}") + loss.backward() + gradient_norm = torch.nn.utils.clip_grad_norm_( + [parameters[n] for n in selected], + spec.get("clip_norm", 1.0), + ) + optimizer.step() + step += 1 + losses.append( + { + "step": step, + "loss": float(loss.detach()), + "target_ce": float(ce.detach()), + "replay_kl": float(kl.detach()), + "gradient_norm": float(gradient_norm), + } + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + metrics, predictions = evaluate_case( + model, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + current_hash = model_digest(model) + record = { + "step": step, + "metrics": metrics, + "model_sha256": current_hash, + "target_success": metrics["E_new" if arm == "edit" else "E_old"]["accuracy"] + == 1, + "U_atomic_at_least_95": metrics["U_atomic"]["accuracy"] >= 0.95, + "loss": losses[-1] if losses else None, + } + history.append(record) + write_json(branch_out / "learning.json", history) + write_json(branch_out / "losses.json", losses) + np.savez_compressed(branch_out / f"predictions-{step:06d}.npz", **predictions) + torch.save( + { + "edited_tensors": { + n: parameters[n].detach().cpu().clone() for n in selected + }, + "model_sha256": current_hash, + "step": step, + }, + branch_out / f"tensors-{step:06d}.pt", + ) + root_learning.append( + { + "step": len(root_learning), + "branch_step": step, + "completed_branches": len(branch_summaries) + int(step == nodes[-1]), + "optimizer_updates": completed_steps + step, + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + "metrics": metrics, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": (completed_steps + step) * (1 + len(tasks["R_atomic"])), + "target_supervised_tokens": (completed_steps + step) * 3, + "replay_distillation_positions": (completed_steps + step) + * len(tasks["R_atomic"]) + * 3, + } + ) + write_json(out / "learning.json", root_learning) + write_json( + out / "status.json", + { + "state": "running", + "step": len(branch_summaries), + "optimizer_updates": completed_steps + step, + "budget": manifest["branches"], + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + }, + ) + changed = [ + n + for n, t in model.state_dict().items() + if not torch.equal(t, parent.state_dict()[n]) + ] + if set(changed) - set(selected) or model_digest(parent) != parent_hash: + raise AssertionError("A frozen parameter or the parent changed") + complete = { + "case_id": case["case_id"], + "role": case["role"], + "stratum": case["stratum"], + "lr": lr, + "arm": arm, + "path": str(branch_out.relative_to(out)), + "metrics": metrics, + "steps": step, + "changed_tensors": changed, + "parent_model_sha256": parent_hash, + "final_model_sha256": current_hash, + "delta_l2": float( + torch.sqrt( + sum( + (parameters[n] - dict(parent.named_parameters())[n]).square().sum() + for n in selected + ) + ).detach() + ), + "tensor_file_sha256": file_hash(branch_out / f"tensors-{step:06d}.pt"), + } + write_json(branch_out / "complete.json", complete) + branch_summaries.append(complete) + completed_steps += step + result = { + "status": "complete", + "branches": branch_summaries, + "updates": completed_steps, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "finished_utc": utc(), + "case_sha256": manifest["case_sha256"], + } + write_json(out / "complete.json", result) + write_json( + out / "status.json", + { + "state": "complete", + "step": len(branch_summaries), + "optimizer_updates": completed_steps, + "budget": manifest["branches"], + }, + ) + return result + + +def audit(out, device="cuda:0"): + """Reload every saved node from parent plus exact tensors and re-score it.""" + device, out = _configure(device), Path(out) + manifest = json.loads((out / "run.json").read_text()) + spec = manifest["spec"] + if file_hash(Path(spec["parent_dir"]) / "model.pt") != manifest["parent_file_sha256"]: + raise AssertionError("Parent checkpoint hash changed") + parent, world, parent_spec = _load_parent(spec["parent_dir"], device) + if model_digest(parent) != manifest["parent_model_sha256"]: + raise AssertionError("Parent model digest changed") + cases, qualification = graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + if "case_ids" in spec: + cases = [c for c in cases if c["case_id"] in spec["case_ids"]] + if cases != manifest["cases"] or _hash_json(cases) != manifest["case_sha256"]: + raise AssertionError("Graph-selected cases changed") + if qualification != manifest["qualification"] or data_digest(world) != manifest["world_sha256"]: + raise AssertionError("World qualification changed") + summary = json.loads((out / "complete.json").read_text()) + rates = spec.get("learning_rates", [spec.get("lr", 1e-4)]) + expected_branches = { + (c["case_id"], lr, arm) for c in cases for lr in rates for arm in ("edit", "sham") + } + actual_branches = [(b["case_id"], b["lr"], b["arm"]) for b in summary["branches"]] + if len(actual_branches) != len(expected_branches) or set(actual_branches) != expected_branches: + raise AssertionError("The fixed paired branch matrix is incomplete") + root_learning = json.loads((out / "learning.json").read_text()) + nodes = spec.get("nodes", list(DEFAULT_NODES)) + expected_evaluations = len(actual_branches) * len(nodes) + if len(root_learning) != expected_evaluations or [row["step"] for row in root_learning] != list( + range(expected_evaluations) + ): + raise AssertionError("Root learning evaluation indices are incomplete or repeated") + for index, row in enumerate(root_learning): + branch_index, node_index = divmod(index, len(nodes)) + updates = branch_index * nodes[-1] + nodes[node_index] + if ( + (row["case_id"], row["lr"], row["arm"]) != actual_branches[branch_index] + or row["branch_step"] != nodes[node_index] + or row["optimizer_updates"] != updates + or row["target_supervised_tokens"] != updates * 3 + or row["replay_distillation_positions"] != updates * spec.get("replay_n", 32) * 3 + or "supervised_tokens" in row + ): + raise AssertionError("Root learning optimizer or exposure accounting changed") + batch_size = spec.get("eval_batch_size", 512) + checked_nodes, checked_predictions, max_error = 0, 0, 0.0 + for case in cases: + tasks, originals = case_tasks(world, case) + parent_correct = _parent_masks(parent, originals, device, batch_size) + for branch in summary["branches"]: + if branch["case_id"] != case["case_id"]: + continue + directory = out / branch["path"] + branch_spec = json.loads((directory / "run.json").read_text()) + target = tasks["E_new" if branch["arm"] == "edit" else "E_old"] + target_batch = answer_batch(target, device) + replay_batch = answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + reference = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + expected_hashes = { + "old_fact_sha256": _hash_json(case["old_fact"]), + "new_fact_sha256": _hash_json(case["new_fact"]), + "target_batch_sha256": _batch_hash(target_batch), + "replay_batch_sha256": _batch_hash(replay_batch), + "parent_reference_sha256": _batch_hash((reference,)), + } + if any(branch_spec[key] != value for key, value in expected_hashes.items()): + raise AssertionError("Target or paired replay provenance changed") + history = json.loads((directory / "learning.json").read_text()) + if [record["step"] for record in history] != spec.get("nodes", list(DEFAULT_NODES)): + raise AssertionError("Saved edit node matrix is incomplete") + if ( + file_hash(directory / f"tensors-{history[-1]['step']:06d}.pt") + != branch["tensor_file_sha256"] + ): + raise AssertionError("Final exact tensor file hash changed") + for record in history: + state = torch.load( + directory / f"tensors-{record['step']:06d}.pt", + map_location="cpu", + weights_only=True, + ) + model = copy.deepcopy(parent).eval() + selected = editable_parameters( + model, spec.get("parameter_scope", "mlp"), spec.get("block_index", 0) + ) + if set(state["edited_tensors"]) != set(selected): + raise AssertionError("Unexpected edited tensor scope") + merged = model.state_dict() + merged.update(state["edited_tensors"]) + model.load_state_dict(merged) + if model_digest(model) != record["model_sha256"]: + raise AssertionError("Exact saved tensors did not reconstruct the model") + metrics, predictions = evaluate_case( + model, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + with np.load(directory / f"predictions-{record['step']:06d}.npz") as saved: + if set(saved.files) != set(predictions): + raise AssertionError("Prediction keys changed") + for name, actual in predictions.items(): + if name.endswith("answer_nll"): + np.testing.assert_allclose(actual, saved[name], rtol=1e-5, atol=1e-5) + if len(actual): + max_error = max( + max_error, float(np.max(np.abs(actual - saved[name]))) + ) + else: + np.testing.assert_array_equal(actual, saved[name]) + checked_predictions += actual.size + for name, values in metrics.items(): + for key, value in values.items(): + expected = record["metrics"][name][key] + if key == "answer_nll" and value is not None: + np.testing.assert_allclose(value, expected, rtol=1e-5, atol=1e-5) + elif value != expected: + raise AssertionError(f"Re-scoring mismatch: {name}/{key}") + checked_nodes += 1 + result = { + "passed": True, + "nodes": checked_nodes, + "array_elements": checked_predictions, + "max_nll_error": max_error, + "case_sha256": manifest["case_sha256"], + "finished_utc": utc(), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/interface_tracking.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/interface_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d7812ba16f84199f575a2c6eb88ba64a6bf26d --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/interface_tracking.py @@ -0,0 +1,203 @@ +"""Use the existing W&B sidecar, finishing only after the independent audit.""" + +import argparse +import fcntl +import importlib +import json +import os +import time +from pathlib import Path + +from . import experiment_tracking as tracking + + +class ContainerSDK: + def __init__(self, sdk, runtime): + self.sdk, self.runtime = sdk, runtime + + def __getattr__(self, name): + return getattr(self.sdk, name) + + def Settings(self, **options): + options.pop("x_stats_pid", None) + if self.runtime: + options["x_stats_pid"] = self.runtime["host_pid"] + options["x_stats_gpu_device_ids"] = (self.runtime["physical_gpu"],) + return self.sdk.Settings(**options) + + +class AuditedRunTracker(tracking.ArtifactRunTracker): + def __init__(self, sdk, batch, path, settings): + runtime_path = path / "container-runtime.json" + runtime = tracking.read_json(runtime_path) + super().__init__(ContainerSDK(sdk, runtime), batch, path, settings) + self.run.config.update( + { + key: self.metadata[key] + for key in ( + "parent_spec", + "cases", + "learning_step_unit", + "status_step_unit", + ) + if key in self.metadata + } + ) + if runtime: + self.run.config.update({"container_runtime": runtime}) + + def poll(self): + history = tracking.read_json(self.path / "learning.json") + previous = None + for record in history: + step = int(record["step"]) + if step > self.cursor: + metrics = tracking.learning_metrics(record, previous) + for key in ("case", "case_id", "condition", "variant", "arm"): + if key in record: + metrics["condition/" + key] = record[key] + if "optimizer_updates" in record: + metrics["evaluation/index"] = step + metrics["condition/step_unit"] = "evaluation_index" + metrics.pop("perf/updates_per_second", None) + metrics.pop("perf/training_ms_per_update", None) + if previous is not None: + seconds = record.get("wall_seconds", 0) - previous.get("wall_seconds", 0) + updates = record["optimizer_updates"] - previous.get("optimizer_updates", 0) + if seconds > 0: + metrics["perf/updates_per_second"] = updates / seconds + self.run.log(metrics, step=step) + self.cursor = step + self.state["last_logged_step"] = step + tracking.write_json(self.state_path, self.state) + previous = record + status_path = self.path / "status.json" + if status_path.exists(): + self.run.summary["training_state"] = tracking.read_json(status_path).get("state") + failed = (self.path / "failure.json").exists() + audit_path = self.path / "audit.json" + audit = tracking.read_json(audit_path) if audit_path.exists() else {} + audited = audit.get("passed") is True + complete = (self.path / "complete.json").exists() and audited + self.run.summary["has_failure_record"] = failed + self.run.summary["independently_reloaded"] = audited + if complete or failed: + self.run.summary["scientific_final_step"] = self.cursor + self.run.finish(exit_code=1 if failed else 0) + # Preserve the authoritative resume cursor even when every point + # was already on the server and this process logged no new points. + self.state["last_logged_step"] = self.cursor + tracking.write_json(self.state_path, self.state) + return True + return False + + +def discover_runs(runs_dir): + return { + path + for path in Path(runs_dir).glob("*") + if (path / "run.json").exists() and (path / "learning.json").exists() + } + + +def final_step(path): + history = tracking.read_json(path / "learning.json") + return max((int(record["step"]) for record in history), default=-1) + + +def drain_runs(sdk, root, runs_dir, settings, *, once=False, tracker_factory=None): + """Drain late-created runs and late final nodes before terminal exit. + + SDK initialization and uploads may take longer than an entire scientific + run. Consequently, a scan made before those calls is never an exit proof. + Finished runs stay in this process's cursor map and are reopened only if + their saved learning trajectory acquired an unlogged final node. + """ + root, runs_dir = Path(root), Path(runs_dir) + tracker_factory = tracker_factory or AuditedRunTracker + active, finished = {}, {} + try: + while True: + for path in sorted(discover_runs(runs_dir)): + if path in active or path in finished: + continue + active[path] = tracker_factory(sdk, root, path, settings) + print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True) + for path, tracker in list(active.items()): + current = tracking.read_json(path / "run.json") + if current.get("pid") != tracker.metadata.get("pid"): + tracker.close() + tracker = tracker_factory(sdk, root, path, settings) + active[path] = tracker + if tracker.poll(): + finished[path] = tracker.cursor + del active[path] + if once: + return {str(path): cursor for path, cursor in finished.items()} + manifest = root / "controller-state.json" + state = tracking.read_json(manifest) if manifest.exists() else {} + terminal = state.get("state") in { + "complete", + "finished_with_failures", + "development_prerequisite_not_met", + } + # Rescan AFTER all SDK calls and after reading the controller's + # terminal state, so runs born during initialization cannot vanish. + fresh = discover_runs(runs_dir) + stale = {path for path, cursor in finished.items() if final_step(path) > cursor} + for path in stale: + del finished[path] + if terminal and not active: + expected = {runs_dir / name for name in state.get("completed", [])} + if missing := expected - fresh: + raise RuntimeError(f"Completed runs lack logging artifacts: {sorted(missing)}") + if fresh <= finished.keys(): + result = { + "passed": True, + "registered_runs": len(finished), + "runs": { + path.name: { + "last_logged_step": finished[path], + "final_step": final_step(path), + } + for path in sorted(fresh) + }, + } + tracking.write_json(root / "tracking-completion.json", result) + return result + if fresh - (active.keys() | finished.keys()): + continue + time.sleep(settings["poll_seconds"]) + finally: + for tracker in active.values(): + tracker.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--runs-dir", type=Path) + parser.add_argument("--defaults", type=Path, default=tracking.DEFAULTS) + parser.add_argument("--entity") + parser.add_argument("--project") + parser.add_argument("--mode", choices=("online", "offline")) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + settings = tracking.read_json(args.defaults) + for key in ("entity", "project", "mode"): + settings[key] = ( + getattr(args, key) or os.environ.get(f"WANDB_{key.upper()}") or settings[key] + ) + if not settings["enabled"]: + raise SystemExit("Experiment tracking is disabled in the selected defaults") + local = args.root / "tracking-wandb" + local.mkdir(parents=True, exist_ok=True) + sdk = importlib.import_module("wandb") + with (local / "tracker.lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + tracking.write_json(args.root / "tracking-ready.json", {"sdk_version": sdk.__version__}) + drain_runs(sdk, args.root, args.runs_dir or args.root / "runs", settings, once=args.once) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/knowledge_change.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/knowledge_change.py new file mode 100644 index 0000000000000000000000000000000000000000..1481d60ac7e43d3617f38f6ca360b241dca20b70 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/knowledge_change.py @@ -0,0 +1,381 @@ +"""Learn to use temporarily changed factual parameters, without test edit labels. + +Every episode uses an atomic-only MLP update, followed by language-model training +of the remaining parameters. The edited MLP is then restored exactly. This is +episodic reader adaptation, not differentiable meta-learning or an assertion +that all facts reside in that MLP. All three arms use the same restricted scope. +""" + +from __future__ import annotations + +import copy +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from . import interface_editing as editing +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .latent_scaling import build_world, compare_metrics, compare_predictions, model_digest +from .shared_cache import construct, executed_flops +from .storage_composition import FullTokenStep, evaluate, file_hash, generate_rows, pack_sentences + +TRAINING_ARMS = ("fixed", "changed_atomic", "changed_use") +CASE_SEED = 107270041 +CASE_POOL = 16 +TEST_PER_CELL = 4 + + +def panel(spec): + """Split update addresses from graph only; reserve all test addresses first.""" + cases, qualification = editing.graph_cases( + spec, seed=CASE_SEED, per_cell=CASE_POOL, replay_n=32 + ) + test = [c for c in cases if int(c["case_id"].rsplit("-", 1)[1]) < TEST_PER_CELL] + reserved = {tuple(c["old_fact"][:2]) for c in test} + world = build_world(spec) + train = [] + for role in editing.ROLES: + selected = [ + c + for c in cases + if c["role"] == role + and c["stratum"] == "familiar" + and tuple(c["old_fact"][:2]) not in reserved + and editing.affected(world["train_composite"], c["old_fact"], role).any() + ] + if len(selected) < 4: + raise ValueError(f"Need four train update addresses per role, got {len(selected)}") + train.extend(selected[:4]) + train_addresses = {tuple(c["old_fact"][:2]) for c in train} + if train_addresses & reserved or len(train_addresses) != len(train): + raise AssertionError("Training/test update addresses overlap") + return dict(train=train, test=test, qualification=qualification) + + +def episode_rows(world, case, arm): + """No heldout query or bridge labels enter any episode's LM objective.""" + if arm not in TRAINING_ARMS: + raise ValueError(arm) + atoms = editing.learned_atoms(world) + original_atoms = atoms.copy() + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + target = case["old_fact"] if arm == "fixed" else case["new_fact"] + mask = np.all(atoms[:, :2] == np.asarray(target[:2]), axis=1) + assert mask.sum() == 1 + atoms[mask, 2] = target[2] + queries = world["train_composite"].copy() + affected = editing.affected(queries, case["old_fact"], case["role"]) + if not affected.any(): + raise ValueError("Training edit must affect taught composition queries") + if arm == "changed_use": + queries = editing.rewrite(queries, case["old_fact"], case["new_fact"], case["role"], lookup) + if arm == "changed_atomic": + # Remove affected queries: old answers would contradict the current fact. + emphasized = queries[~affected] + else: + emphasized = queries[affected] + unaffected = queries[~affected] + # Four matched streams: target atomic, other atomics, emphasized composition, + # unaffected composition. The atomic-only control differs in query exposure; + # this limitation is recorded rather than claiming exact information matching. + strata = [np.asarray([target]), atoms[~mask], emphasized, unaffected] + return strata, dict( + affected_training_n=int(affected.sum()), + changed_training_answers=int(np.sum(queries[:, -1] != world["train_composite"][:, -1])), + direct_atomic_changed=bool(np.any(atoms != original_atoms)), + stream_sizes=[len(x) for x in strata], + ) + + +class AtomicStep: + """Captured atomic edit with exact warmup rollback and fresh Adam state.""" + + def __init__(self, model, target, replay, reference, lr): + self.model, self.target, self.replay, self.reference = model, target, replay, reference + self.parameters = [p for p in model.parameters() if p.requires_grad] + self.optimizer = torch.optim.Adam(self.parameters, lr=lr, capturable=True, foreach=False) + before = [p.detach().clone() for p in model.parameters()] + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(3): + self.eager() + torch.cuda.current_stream().wait_stream(stream) + self.graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(self.graph): + self.loss = self.eager() + torch.cuda.synchronize() + with torch.no_grad(): + for parameter, old in zip(model.parameters(), before, strict=True): + parameter.copy_(old) + if parameter.grad is not None: + parameter.grad.zero_() + for state in self.optimizer.state.values(): + for value in state.values(): + if torch.is_tensor(value): + value.zero_() + + def eager(self): + self.optimizer.zero_grad(set_to_none=True) + loss, _, _ = editing.edit_objective( + self.model, self.target, self.replay, self.reference, 1.0 + ) + loss.backward() + torch.nn.utils.clip_grad_norm_(self.parameters, 1.0, foreach=True) + self.optimizer.step() + return loss + + def run(self, steps): + for _ in range(steps): + self.graph.replay() + torch.cuda.synchronize() + result = float(self.loss.detach()) + if not np.isfinite(result): + raise FloatingPointError(result) + return result + + +def set_reader_scope(model): + for name, parameter in model.named_parameters(): + parameter.requires_grad_(not name.startswith("blocks.0.mlp.")) + parameter.grad = None + + +def train(spec, out, source, engineering=False): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists(): + raise FileExistsError(out) + editing._configure("cuda:0") + parent_path = Path(spec["parent_dir"]) / "model-128000.pt" + payload = torch.load(parent_path, map_location="cpu", weights_only=False) + parent_spec = payload["spec"] + model = construct(parent_spec, "cuda:0") + model.load_state_dict(payload["model"]) + model.eval() + world = build_world(parent_spec) + selected_panel = panel(parent_spec) + assert editing._hash_json(selected_panel) == spec["panel_sha256"] + writer = { + n: p.detach().clone() for n, p in model.named_parameters() if n.startswith("blocks.0.mlp.") + } + manifest = dict( + spec=spec, + parent_spec=parent_spec, + parent_sha256=file_hash(parent_path), + initial_model_sha256=model_digest(model), + writer_names=list(writer), + panel=selected_panel, + source=source, + pid=__import__("os").getpid(), + gpu=int(__import__("os").environ.get("PHYSICAL_GPU", 0)), + created_utc=utc(), + ) + write_json(out / "run.json", manifest) + np.savez_compressed(out / "world.npz", **world) + episodes = 2 if engineering else spec["episodes"] + inner_steps = 4 if engineering else spec["inner_steps"] + reader_steps = 4 if engineering else spec["reader_steps"] + history, records = [], [] + training_seconds = 0.0 + started = time.perf_counter() + + def measure(episode): + nonlocal model + metrics, predictions = evaluate(model, world, "low", "cuda:0") + node = episode * (inner_steps + reader_steps) + history.append( + dict( + step=node, + episode=episode, + metrics=metrics, + training_seconds=training_seconds, + wall_seconds=time.perf_counter() - started, + reader_updates=episode * reader_steps, + atomic_update_steps=episode * inner_steps, + examples=episode * (inner_steps * 33 + reader_steps * spec["batch_size"]), + target_supervised_tokens=episode * inner_steps * 3, + replay_distillation_positions=episode * inner_steps * 32 * 3, + reader_supervised_tokens=episode * reader_steps * spec["batch_size"] * 8, + # Execution-shape estimate; frozen MLP and KL are not exact backward FLOPs. + estimated_matmul_training_flops=episode + * ( + inner_steps + * executed_flops(model.config, model.repeats, 33, 9, model.memory_arm, 3) + + reader_steps + * executed_flops( + model.config, model.repeats, spec["batch_size"], 9, model.memory_arm + ) + ), + ) + ) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{episode:03d}.npz", **predictions) + torch.save( + dict(spec=parent_spec, model=model.state_dict(), episode=episode), + out / f"model-{episode:03d}.pt", + ) + write_json(out / "status.json", dict(state="running", step=node, episode=episode)) + print(json.dumps(dict(name=spec["name"], episode=episode, metrics=metrics)), flush=True) + + measure(0) + for episode in range(episodes): + case = selected_panel["train"][episode % len(selected_panel["train"])] + before_writer = {n: p.detach().clone() for n, p in model.named_parameters() if n in writer} + for n in writer: + torch.testing.assert_close(before_writer[n], writer[n], rtol=0, atol=0) + tasks, _ = editing.case_tasks(world, case) + replay = editing.answer_batch(tasks["R_atomic"], "cuda:0") + model.eval() + with torch.no_grad(): + reference = model(replay[0], positions=replay[1]).log_softmax(-1).detach() + selected = editing.editable_parameters(model) + assert set(selected) == set(writer) + target = case["old_fact"] if spec["training_arm"] == "fixed" else case["new_fact"] + target_batch = editing.answer_batch(np.asarray([target]), "cuda:0") + torch.cuda.synchronize() + began = time.perf_counter() + operation = AtomicStep(model, target_batch, replay, reference, spec["inner_lr"]) + if engineering: + eager_model = copy.deepcopy(model) + eager_parameters = [p for p in eager_model.parameters() if p.requires_grad] + eager_optimizer = torch.optim.Adam( + eager_parameters, lr=spec["inner_lr"], capturable=True, foreach=False + ) + for _ in range(inner_steps): + eager_optimizer.zero_grad(set_to_none=True) + eager_loss, _, _ = editing.edit_objective( + eager_model, target_batch, replay, reference, 1.0 + ) + eager_loss.backward() + torch.nn.utils.clip_grad_norm_(eager_parameters, 1.0, foreach=True) + eager_optimizer.step() + inner_loss = operation.run(inner_steps) + if engineering: + for actual, expected in zip(model.parameters(), eager_model.parameters(), strict=True): + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + del eager_model, eager_optimizer + training_seconds += time.perf_counter() - began + inner_metrics, _ = generate_rows(model, np.asarray([target]), "cuda:0") + del operation + strata, info = episode_rows(world, case, spec["training_arm"]) + set_reader_scope(model) + model.train() + table = tuple( + torch.as_tensor(np.concatenate(parts), device="cuda:0") + 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(n, spec["stream_seed"] + episode * 10 + i) for i, n in enumerate(sizes) + ] + batch = spec["batch_size"] + reader_lr = torch.tensor(spec["reader_lr"], device="cuda:0") + optimizer = make_optimizer(model, reader_lr, 0.0) + began = time.perf_counter() + graph = FullTokenStep(model, optimizer, table, batch) + for start in range(0, reader_steps, 128): + n = min(128, reader_steps - start) + indices = np.concatenate( + [ + s.take(n * batch // 4).reshape(n, batch // 4) + offset + for s, offset in zip(streams, offsets, strict=True) + ], + axis=1, + ) + indices = torch.as_tensor(indices, device="cuda:0") + for j in range(n): + loss = graph(indices[j]) + torch.cuda.synchronize() + training_seconds += time.perf_counter() - began + reader_loss = float(loss.detach()) + if not np.isfinite(reader_loss): + raise FloatingPointError(reader_loss) + after_metrics, _ = generate_rows(model, np.asarray([target]), "cuda:0") + del graph, optimizer + with torch.no_grad(): + for name, parameter in model.named_parameters(): + if name in writer: + parameter.copy_(writer[name]) + records.append( + dict( + episode=episode + 1, + case_id=case["case_id"], + role=case["role"], + target=target, + inner_success=inner_metrics["accuracy"], + after_use_atomic_success=after_metrics["accuracy"], + inner_loss=inner_loss, + reader_loss=reader_loss, + **info, + ) + ) + write_json(out / "episodes.json", records) + if episode + 1 in {1, 8, 16, 24, episodes}: + measure(episode + 1) + torch.save(dict(spec=parent_spec, model=model.state_dict()), out / "model.pt") + result = dict( + spec=spec, + endpoint=history[-1], + episodes=records, + writer_restored_exact=True, + final_model_sha256=model_digest(model), + checkpoint_sha256=file_hash(out / "model.pt"), + training_seconds=training_seconds, + process_seconds=time.perf_counter() - started, + finished_utc=utc(), + engineering=engineering, + ) + write_json(out / "complete.json", result) + return result + + +def audit(out): + editing._configure("cuda:0") + out = Path(out) + manifest = json.loads((out / "run.json").read_text()) + complete = json.loads((out / "complete.json").read_text()) + spec = manifest["parent_spec"] + world = build_world(spec) + if panel(spec) != manifest["panel"]: + raise AssertionError("Update partition changed") + parent = torch.load( + Path(manifest["spec"]["parent_dir"]) / "model-128000.pt", + map_location="cpu", + weights_only=False, + ) + maximum = 0.0 + history = json.loads((out / "learning.json").read_text()) + for row in history: + payload = torch.load( + out / f"model-{row['episode']:03d}.pt", map_location="cpu", weights_only=False + ) + model = construct(spec, "cuda:0") + model.load_state_dict(payload["model"]) + for name in manifest["writer_names"]: + torch.testing.assert_close( + payload["model"][name], parent["model"][name], rtol=0, atol=0 + ) + metrics, predictions = evaluate(model, world, "low", "cuda:0") + compare_metrics(metrics, row["metrics"]) + with np.load(out / f"predictions-{row['episode']:03d}.npz") as saved: + maximum = max(maximum, compare_predictions(predictions, saved)) + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + model.load_state_dict(payload["model"]) + assert model_digest(model) == complete["final_model_sha256"] + assert file_hash(out / "model.pt") == complete["checkpoint_sha256"] + write_json( + out / "audit.json", + dict( + passed=True, + checked_nodes=len(history), + max_nll_error=maximum, + writer_exact=True, + utc=utc(), + ), + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/latent_scaling.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/latent_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..7abd21f4255e3f7de35ecee337ed09d32da707ff --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/latent_scaling.py @@ -0,0 +1,311 @@ +"""Scaling knowledge use in ordinary GPT blocks with fixed facts and tests. + +Independent composition examples and optimization time are separate axes. All +blocks retain learned embeddings, causal attention, residuals and 4x GELU MLPs. +Historical experiments and their frozen implementations are left untouched. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .storage_composition import FullTokenStep, data_digest, evaluate, file_hash, pack_sentences +from .storage_composition import build_world as historical_world +from .storage_frontier import SOURCE_FILES as STABILITY_SOURCES +from .storage_frontier import learning_rate +from .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 checked diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/latent_support.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/latent_support.py new file mode 100644 index 0000000000000000000000000000000000000000..4b307c09f7a1fe633c634ae39b3a83e964675355 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/latent_support.py @@ -0,0 +1,363 @@ +"""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 so +historical sources retain their frozen hashes. Architecture, optimizer, sentence +packing, evaluation and streams are reused; only build_world selects support. +""" + +from __future__ import annotations + +import json +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .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 checked diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/low_rank.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/low_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..3a58bee0d460cb3ae042e17d22b7132b2035bd4b --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/low_rank.py @@ -0,0 +1,138 @@ +"""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, Real +from 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 report diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/memory_reuse.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/memory_reuse.py new file mode 100644 index 0000000000000000000000000000000000000000..89520ed7649557ad7e4cfc2611ac85b8d9db8396 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/memory_reuse.py @@ -0,0 +1,469 @@ +"""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 used +by its optimizer, and all evaluation uses continuous intermediate states. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from 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 result diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/multihop_scaling.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/multihop_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..64b5a3d67ef6bab20c60904e626e811876d72279 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/multihop_scaling.py @@ -0,0 +1,518 @@ +"""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 copy +import hashlib +import json +import time +from functools import lru_cache +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import depth_step +from .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_json +from .grok_loop_model import flops +from .latent_scaling import model_digest +from .storage_composition import FullTokenStep, file_hash +from .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=" 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 checked diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/natural_composition_confirmation.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/natural_composition_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9608e59339683c91de69b2f1f392b93b8f0171 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/natural_composition_confirmation.py @@ -0,0 +1,687 @@ +"""Full-Qwen, nested compositional support with matched atomic supervision.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import platform +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +import transformers +from 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) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e949ff27eac75a758644d6a7ffd81f2a9477ea --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py @@ -0,0 +1,687 @@ +"""Full-Qwen, nested compositional support with matched atomic supervision.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import platform +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +import transformers +from 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) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/neural.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/neural.py new file mode 100644 index 0000000000000000000000000000000000000000..ce1f02e8195f4e583817b3781b044f021a41fbfb --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/neural.py @@ -0,0 +1,328 @@ +"""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 argparse +import copy +import json +import math +import platform +import statistics +import subprocess +import time +from dataclasses import asdict, dataclass +from pathlib import Path + +import numpy as np + +try: + import torch + from torch import nn + from torch.nn import functional as F +except ModuleNotFoundError as exc: + raise SystemExit("Neural experiments require PyTorch: pip install '.[neural]'") from exc + +from .neural_data import make_world +from .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()) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/neural_data.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/neural_data.py new file mode 100644 index 0000000000000000000000000000000000000000..555b2a06a7db0805d441a3f8f89bc2100deaa72a --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/neural_data.py @@ -0,0 +1,147 @@ +"""Balanced fact-table interventions, defined independently of model training.""" + +from dataclasses import dataclass +from 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, + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/neural_models.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/neural_models.py new file mode 100644 index 0000000000000000000000000000000000000000..448b3499cdce6fac7d4bcac1e60883f4c383df82 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/neural_models.py @@ -0,0 +1,157 @@ +"""Trainable nonlinear fact models; importing this module requires PyTorch.""" + +import torch +from 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 selected diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/parametric_architecture.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/parametric_architecture.py new file mode 100644 index 0000000000000000000000000000000000000000..a254bf6f90931d21d80c57972a6770ad6665c13a --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/parametric_architecture.py @@ -0,0 +1,443 @@ +"""Paired GPT-2 architecture extensions for the closed-book memory experiment. + +Dense execution delegates to the historical ReproductionGPT without changing +its numerical path. New modules use an independent, checkpointed initialization +seed; the eight-block reference is always constructed before taking a prefix. +The mHC residual convention is ``output[n] = sum_m H_res[m,n] * input[m]``. +""" + +from __future__ import annotations + +import hashlib +import math +from collections.abc import Sequence + +import torch +from torch import nn +from torch.nn import functional as F +from transformers import GPT2Config +from transformers.models.gpt2.modeling_gpt2 import GPT2MLP + +from .grokking_reproduction import ReproductionGPT + +ARMS = { + "D4": (4, 1, "dense"), + "D8": (8, 1, "dense"), + "L4R2": (4, 2, "dense"), + "M8": (8, 1, "moe"), + "W8": (8, 1, "wide"), + "IHC8": (8, 1, "identity_mhc"), + "HC8": (8, 1, "mhc"), + "M4": (4, 1, "moe"), + "LM4R2": (4, 2, "moe"), +} + + +def sinkhorn(logits: torch.Tensor, iterations: int = 20, eps: float = 1e-6): + """Accepted mHC A.6: initial row softmax, then 20 column normalizations. + + There are 19 intervening row normalizations. This is a finite-iteration + approximation, not an exact doubly stochastic projection. + """ + if iterations < 1: + raise ValueError("Sinkhorn requires at least one iteration") + with torch.autocast(logits.device.type, enabled=False): + matrix = logits.float().softmax(dim=-1) + eps + matrix = matrix / (matrix.sum(dim=-2, keepdim=True) + eps) + for _ in range(iterations - 1): + matrix = matrix / (matrix.sum(dim=-1, keepdim=True) + eps) + matrix = matrix / (matrix.sum(dim=-2, keepdim=True) + eps) + return matrix + + +def residual_mix(streams, matrix): + """Rows are source streams and columns are destination streams.""" + return torch.einsum("...mn,...mc->...nc", matrix, streams) + + +class ControllerRMSNorm(nn.Module): + def __init__(self, width): + super().__init__() + self.weight = nn.Parameter(torch.ones(width)) + + def forward(self, x): + return x * torch.rsqrt(x.square().mean(dim=-1, keepdim=True) + 1e-20) * self.weight + + +class HyperConnection(nn.Module): + """Four-stream pre/post controller with optional constrained residual map.""" + + def __init__(self, width, sublayer_id, streams=4, identity=False): + super().__init__() + self.streams, self.identity = streams, identity + count = 2 * streams + (0 if identity else streams * streams) + self.norm = ControllerRMSNorm(streams * width) + self.projection = nn.Linear(streams * width, count, bias=False) + nn.init.zeros_(self.projection.weight) + self.pre_bias = nn.Parameter(torch.full((streams,), -3.0)) + with torch.no_grad(): + self.pre_bias[sublayer_id % streams] = 3.0 + self.post_bias = nn.Parameter(torch.zeros(streams)) + self.alpha_pre = nn.Parameter(torch.tensor(0.01)) + self.alpha_post = nn.Parameter(torch.tensor(0.01)) + if not identity: + self.res_bias = nn.Parameter(6 * torch.eye(streams) - 3) + self.alpha_res = nn.Parameter(torch.tensor(0.01)) + + def coefficients(self, x): + n = self.streams + with torch.autocast(x.device.type, enabled=False): + dynamic = self.projection(self.norm(x.float().flatten(-2))) + pre = torch.sigmoid(dynamic[..., :n] * self.alpha_pre + self.pre_bias) + 1e-6 + post = 2 * torch.sigmoid(dynamic[..., n : 2 * n] * self.alpha_post + self.post_bias) + res = None + if not self.identity: + logits = dynamic[..., 2 * n :].reshape(*x.shape[:-2], n, n) + res = sinkhorn(logits * self.alpha_res + self.res_bias) + return pre, post, res + + def forward(self, x, sublayer): + pre, post, res = self.coefficients(x) + with torch.autocast(x.device.type, enabled=False): + contracted = (pre[..., None] * x.float()).sum(dim=-2) + y = sublayer(contracted.to(x.dtype)) + with torch.autocast(x.device.type, enabled=False): + residual = x.float() if res is None else residual_mix(x.float(), res) + output = residual + post[..., None] * y.float().unsqueeze(-2) + return output.to(x.dtype) + + +def _initialize_mlp(mlp, initializer_range): + # Eight-block GPT-2 reference residual projection scale, also for loops. + nn.init.normal_(mlp.c_fc.weight, std=initializer_range) + nn.init.normal_(mlp.c_proj.weight, std=initializer_range / math.sqrt(2 * 8)) + nn.init.zeros_(mlp.c_fc.bias) + nn.init.zeros_(mlp.c_proj.bias) + + +class DroplessMoE(nn.Module): + """Top-2 normalized routing, one output dropout, no capacity/token drops.""" + + def __init__(self, config, experts=8, top_k=2): + super().__init__() + self.expert_count, self.top_k = experts, top_k + self.router = nn.Linear(config.n_embd, experts, bias=False) + nn.init.normal_(self.router.weight, std=config.initializer_range) + self.experts = nn.ModuleList() + for _ in range(experts): + expert = GPT2MLP(2 * config.n_embd, config) + expert.dropout = nn.Identity() + _initialize_mlp(expert, config.initializer_range) + self.experts.append(expert) + self.dropout = nn.Dropout(config.resid_pdrop) + + def forward(self, x, valid_mask=None): + flat = x.reshape(-1, x.shape[-1]) + if valid_mask is None: + selected_tokens = torch.arange(len(flat), device=x.device) + else: + selected_tokens = valid_mask.flatten().nonzero(as_tuple=True)[0] + valid = flat.index_select(0, selected_tokens) + with torch.autocast(x.device.type, enabled=False): + probabilities = F.linear(valid.float(), self.router.weight.float()).softmax(-1) + top_weights, expert_ids = probabilities.topk(self.top_k, dim=-1) + weights = top_weights / top_weights.sum(dim=-1, keepdim=True) + # Accumulate selected expert outputs in FP32 for consistent BF16 routing. + combined = torch.zeros_like(valid, dtype=torch.float32) + for expert_id, expert in enumerate(self.experts): + token_ids, slots = (expert_ids == expert_id).nonzero(as_tuple=True) + if token_ids.numel(): + values = expert(valid.index_select(0, token_ids)) + weighted = values.float() * weights[token_ids, slots, None] + combined = combined.index_add(0, token_ids, weighted) + output = torch.zeros_like(flat).index_copy(0, selected_tokens, combined.to(flat.dtype)) + counts = torch.bincount(expert_ids.flatten(), minlength=self.expert_count).detach() + n_valid = probabilities.new_tensor(len(valid)) + stats = { + "assignment_counts": counts, + "probability_sum": probabilities.sum(dim=0), + "valid_tokens": n_valid, + "top_k": self.top_k, + "processed_assignments": counts.sum(), + "dropped_assignments": counts.new_zeros(()), + "entropy_sum": -(probabilities * probabilities.clamp_min(1e-30).log()).sum().detach(), + "selected_mass_sum": top_weights.sum().detach(), + } + return self.dropout(output.view_as(x)), stats + + +def combine_router_fractions(stats_by_microbatch: Sequence[Sequence[dict]]): + """Combine detached counts before a replay that computes exact batch aux. + + Counts are per executed block (thus distinguish Loop passes). Replay must + restore dropout RNG state, so its hard routes equal the counting pass. + """ + if not stats_by_microbatch or not stats_by_microbatch[0]: + return [], 0 + layers = len(stats_by_microbatch[0]) + if any(len(stats) != layers for stats in stats_by_microbatch): + raise ValueError("All microbatches must have the same executed routing layers") + total = sum(stats[0]["valid_tokens"] for stats in stats_by_microbatch) + fractions = [] + for layer in range(layers): + counts = sum(stats[layer]["assignment_counts"] for stats in stats_by_microbatch) + fractions.append( + counts.float() / (total * stats_by_microbatch[0][layer]["top_k"]).clamp_min(1) + ) + return fractions, total + + +def router_balance_loss(stats, assignment_fractions=None, total_valid_tokens=None): + """N * sum(f * p), averaged over executed layers. + + With externally supplied whole-batch fractions and denominator, this returns + the current microbatch's additive contribution to the exact batch objective. + Assignment fractions are discrete and intentionally detached. + """ + if not stats: + return torch.tensor(0.0) + if assignment_fractions is not None and len(assignment_fractions) != len(stats): + raise ValueError("One assignment-fraction vector is required per executed layer") + losses = [] + for index, record in enumerate(stats): + count = record["valid_tokens"] + denominator = count if total_valid_tokens is None else total_valid_tokens + denominator = torch.as_tensor(denominator, device=count.device).clamp_min(1) + fractions = ( + record["assignment_counts"].float() / (count * record["top_k"]).clamp_min(1) + if assignment_fractions is None + else assignment_fractions[index].detach() + ) + probabilities = record["probability_sum"] / denominator + losses.append(probabilities.numel() * (fractions * probabilities).sum()) + return torch.stack(losses).mean() + + +class ParametricGPT(ReproductionGPT): + def __init__(self, config, architecture="D8", module_seed=0): + blocks, repeats, kind = ARMS[architecture] + # Always initialize the same independent eight blocks before slicing. + config.n_layer = 8 + super().__init__(config, repeats=repeats) + self.transformer.h = nn.ModuleList(list(self.transformer.h)[:blocks]) + self.config.n_layer = blocks + self.architecture, self.kind, self.module_seed = architecture, kind, module_seed + with torch.random.fork_rng(devices=[]): + torch.manual_seed(module_seed) + if kind in {"wide", "moe"}: + for block in self.transformer.h: + if kind == "moe": + block.mlp = DroplessMoE(config) + else: + block.mlp = GPT2MLP(16 * config.n_embd, config) + _initialize_mlp(block.mlp, config.initializer_range) + elif kind in {"mhc", "identity_mhc"}: + self.connections = nn.ModuleList( + HyperConnection(config.n_embd, index, identity=kind == "identity_mhc") + for index in range(2 * blocks) + ) + + def _attention(self, block, x): + cfg = self.config + batch, length = x.shape[:2] + q, k, v = block.attn.c_attn(block.ln_1(x)).split(cfg.n_embd, dim=2) + shape = (batch, 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(batch, length, cfg.n_embd)) + return F.dropout(y, cfg.resid_pdrop, self.training) + + def forward(self, tokens, positions=None, *, valid_mask=None, return_aux=False): + if valid_mask is not None and ( + valid_mask.shape != tokens.shape or valid_mask.dtype != torch.bool + ): + raise ValueError("valid_mask must be boolean and have the tokens' shape") + if self.kind in {"dense", "wide"}: + logits = super().forward(tokens, positions) + if return_aux: + return logits, {"balance_loss": logits.new_zeros(()), "router_stats": []} + return logits + 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) + stats = [] + if self.kind in {"mhc", "identity_mhc"}: + x = x.unsqueeze(-2).expand(-1, -1, 4, -1) + for _ in range(self.repeats): + for index, block in enumerate(t.h): + if self.kind == "moe": + x = x + self._attention(block, x) + y, layer_stats = block.mlp(block.ln_2(x), valid_mask) + x = x + y + stats.append(layer_stats) + else: + x = self.connections[2 * index](x, lambda z, b=block: self._attention(b, z)) + x = self.connections[2 * index + 1](x, lambda z, b=block: b.mlp(b.ln_2(z))) + if self.kind in {"mhc", "identity_mhc"}: + x = x.mean(dim=-2) + x = t.ln_f(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, t.wte.weight) + if return_aux: + loss = router_balance_loss(stats) if stats else logits.new_zeros(()) + return logits, {"balance_loss": loss, "router_stats": stats} + return logits + + +def construct(config, spec, device): + """Historical config/spec convention, extended by ``spec['architecture']``.""" + architecture = spec["architecture"] + if architecture not in ARMS: + raise ValueError(f"Unknown architecture: {architecture}") + torch.manual_seed(spec["initialization"]) + cfg = GPT2Config( + vocab_size=config["vocab_size"], + n_positions=config.get("positions", 1024), + n_embd=config["hidden_size"], + n_head=config.get("attention_heads", config.get("heads", 12)), + n_layer=8, + resid_pdrop=config["dropout"], + embd_pdrop=config["dropout"], + attn_pdrop=config["dropout"], + activation_function="gelu_new", + use_cache=False, + ) + # Separate reproducible new-shape RNG, explicitly recorded in the manifest. + module_seed = spec.get("module_initialization", spec["initialization"] + 1_000_003) + model = ParametricGPT(cfg, architecture, module_seed) + model.initialization_seed = spec["initialization"] + return model.to(device) + + +def optimizer_for(model, lr, decay): + groups = [{"params": [], "weight_decay": decay}, {"params": [], "weight_decay": 0.0}] + for name, parameter in model.named_parameters(): + if not parameter.requires_grad: + continue + exempt = any(part in name for part in ("bias", "ln")) + exempt |= name.startswith("connections.") and (".norm." in name or ".alpha_" in name) + groups[int(exempt)]["params"].append(parameter) + return torch.optim.AdamW( + groups, lr=lr, betas=(0.9, 0.999), eps=1e-8, fused=next(model.parameters()).is_cuda + ) + + +def parameter_ledger(model): + d, layers = model.config.n_embd, len(model.transformer.h) + total = sum(parameter.numel() for parameter in model.parameters()) + expert = sum(p.numel() for n, p in model.named_parameters() if ".experts." in n) + controller = sum(p.numel() for n, p in model.named_parameters() if n.startswith("connections.")) + router = sum(p.numel() for n, p in model.named_parameters() if ".router." in n) + fixed = (model.config.vocab_size + model.config.n_positions) * d + 2 * d + attention_and_norms = 4 * d * d + 8 * d + if model.kind == "moe": + per_block = attention_and_norms + 8 * (4 * d * d + 3 * d) + 8 * d + else: + width = (16 if model.kind == "wide" else 4) * d + per_block = attention_and_norms + 2 * d * width + width + d + expected_controller = 0 + if model.kind in {"mhc", "identity_mhc"}: + n = 4 + count = 2 * n + (n * n if model.kind == "mhc" else 0) + alphas = 3 if model.kind == "mhc" else 2 + expected_controller = 2 * layers * (n * d * count + n * d + count + alphas) + if controller != expected_controller: + raise AssertionError( + f"Controller parameter mismatch: {controller} != {expected_controller}" + ) + expected = fixed + layers * per_block + expected_controller + if total != expected: + raise AssertionError(f"Parameter ledger mismatch: {total} != {expected}") + return { + "architecture": model.architecture, + "total_parameters": total, + "trainable_parameters": sum(p.numel() for p in model.parameters() if p.requires_grad), + "expected_parameters": expected, + "expert_parameters": expert, + "router_parameters": router, + "controller_parameters": controller, + "nominal_parameters_selected_per_token": total - expert + expert // 4, + "active_parameter_convention": ( + "All nonexpert parameters (including whole embedding table) plus two of eight " + "experts; not FLOPs or touched embedding rows." + ), + "unique_blocks": layers, + "repeats": model.repeats, + "executed_blocks": layers * model.repeats, + "residual_streams": 4 if controller else 1, + "parameter_dtype": str(next(model.parameters()).dtype), + "residual_dtype_under_bf16_autocast": "torch.float32 with FP32 parameters", + "controller_dtype": "torch.float32", + } + + +def flop_ledger(model, *, executed_tokens, projected_positions, attention_pairs, valid_tokens=None): + """Leading forward matmuls with actual padding/dispatch/readout counts. + + ``attention_pairs`` is sum(B*T*T) over microbatches, before block count. + Training 3x is explicitly an approximation; Sinkhorn autograd, scalar ops, + and a counting/replay pass are not silently folded into this estimate. + """ + d, blocks = model.config.n_embd, len(model.transformer.h) * model.repeats + valid_tokens = executed_tokens if valid_tokens is None else valid_tokens + attention = blocks * (8 * executed_tokens * d * d + 4 * attention_pairs * d) + readout = 2 * projected_positions * d * model.config.vocab_size + router = controller = 0 + if model.kind == "moe": + ffn = blocks * 4 * valid_tokens * d * (2 * 2 * d) + router = blocks * 2 * valid_tokens * d * 8 + else: + inner = (16 if model.kind == "wide" else 4) * d + ffn = blocks * 4 * executed_tokens * d * inner + if model.kind in {"mhc", "identity_mhc"}: + n = 4 + count = 2 * n + (n * n if model.kind == "mhc" else 0) + controller = ( + 2 * blocks * (2 * executed_tokens * n * d * count + 2 * executed_tokens * d * count) + ) + forward = attention + readout + ffn + router + controller + return { + "forward_attention_matmul_flops": attention, + "forward_ffn_matmul_flops": ffn, + "forward_readout_matmul_flops": readout, + "forward_router_matmul_flops": router, + "forward_controller_matmul_flops": controller, + "forward_leading_matmul_flops": forward, + "estimated_matmul_training_flops": 3 * forward, + "sinkhorn_normalization_passes": 39 if model.kind == "mhc" else 0, + "sinkhorn_matrix_elements_per_forward": 2 * blocks * executed_tokens * 16 + if model.kind == "mhc" + else 0, + "selected_expert_assignments": blocks * valid_tokens * 2 if model.kind == "moe" else 0, + "executed_input_tokens": executed_tokens, + "effective_input_tokens": valid_tokens, + "projected_positions": projected_positions, + "excluded_ops": ( + "Nonlinearities, normalization, dropout, dispatch/index-add, softmax, Sinkhorn " + "scalar arithmetic/autograd, final mean, counting/replay and optimizer; " + "3x is approximate." + ), + } + + +def initialization_manifest(model): + """CPU-byte hashes of each actual initialized tensor; no sampled hash.""" + shared, introduced = {}, {} + for name, tensor in model.state_dict().items(): + is_new = name.startswith("connections.") or ( + model.kind in {"moe", "wide"} and ".mlp." in name + ) + raw = tensor.detach().cpu().contiguous().reshape(-1).view(torch.uint8).numpy().tobytes() + (introduced if is_new else shared)[name] = hashlib.sha256(raw).hexdigest() + return { + "architecture": model.architecture, + "reference_initialization": getattr(model, "initialization_seed", None), + "module_initialization": model.module_seed, + "reference_blocks_before_slicing": 8, + "shared_tensor_sha256": shared, + "introduced_tensor_sha256": introduced, + } diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/parametric_architecture_train.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/parametric_architecture_train.py new file mode 100644 index 0000000000000000000000000000000000000000..55c77a2f48a116b87a2159b90bb2ab76a6730887 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/parametric_architecture_train.py @@ -0,0 +1,626 @@ +"""Resumable, exposure-matched training for the parametric architecture study. + +The ordinary data stream, answer-plus-EOS objective and generated evaluator are +shared with the historical experiment. MoE balancing is computed over the true +effective batch using an RNG-replayed routing pass, not a sum of local products. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import random +import time +from pathlib import Path + +import numpy as np +import torch +import transformers +from transformers import GPT2TokenizerFast + +from . import realworld_composition as historical +from .grok_depth import utc +from .grokking_reproduction import model_digest +from .realworld_composition_data import sha256, write_json + + +def _architecture(): + from . import parametric_architecture + + return parametric_architecture + + +def rng_state(device): + state = { + "python": random.getstate(), + "numpy": np.random.get_state(), + "cpu": torch.get_rng_state(), + } + if torch.device(device).type == "cuda": + state["cuda"] = torch.cuda.get_rng_state(device) + return state + + +def restore_rng(state, device): + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["cpu"].cpu()) + if "cuda" in state: + torch.cuda.set_rng_state(state["cuda"].cpu(), device) + + +def pack(records, pad, device): + """EOS is a valid input token; validity comes from lengths, never token IDs.""" + tokens, positions, labels = historical.pack(records, pad, device) + lengths = torch.tensor([len(r["encoded"]["input"]) for r in records], device=device) + valid = torch.arange(tokens.shape[1], device=device)[None] < lengths[:, None] + return tokens, positions, labels, valid + + +def _synchronize(device): + if torch.device(device).type == "cuda": + torch.cuda.synchronize(device) + + +def _finite(value, name): + if not math.isfinite(float(value)): + raise FloatingPointError(f"Nonfinite {name}; this candidate must retain its failure") + + +def update(model, optimizer, records, spec, device, pad): + """One historical effective batch, with exact full-batch routing gradients. + + Hard assignment fractions have no gradient. A no-grad pass collects their + global values when there are multiple microbatches; replaying the same + dropout RNG realizes the same routing in the differentiable pass. One + microbatch already contains the full objective and needs no prepass. + """ + if not records: + raise ValueError("An update requires at least one example") + microbatch = int(spec["microbatch_size"]) + if microbatch < 1: + raise ValueError("microbatch_size must be positive") + api = _architecture() + model.train() + optimizer.zero_grad(set_to_none=True) + chunks = [records[i : i + microbatch] for i in range(0, len(records), microbatch)] + is_moe = spec["architecture"] in {"M8", "M4", "LM4R2"} + needs_prepass = is_moe and len(chunks) > 1 + coefficient = float(spec.get("balance_coefficient", 0.01)) if is_moe else 0.0 + global_fractions, total_tokens, collected = None, None, [] + if needs_prepass: + before = rng_state(device) + try: + with torch.no_grad(): + for chunk in chunks: + tokens, positions, _, valid = pack(chunk, pad, device) + with historical.autocast(device): + _, aux = model(tokens, positions, valid_mask=valid, return_aux=True) + collected.append(aux["router_stats"]) + global_fractions, total_tokens = api.combine_router_fractions(collected) + finally: + restore_rng(before, device) + answer_loss, balance_loss = 0.0, 0.0 + executed, readout, attention = 0, 0, 0 + replay_count_error = torch.zeros((), dtype=torch.int64, device=device) + for chunk_index, chunk in enumerate(chunks): + tokens, positions, labels, valid = pack(chunk, pad, device) + with historical.autocast(device): + logits, aux = model(tokens, positions, valid_mask=valid, return_aux=True) + answer = historical.example_losses(logits, labels).sum() / len(records) + balance = ( + api.router_balance_loss( + aux["router_stats"], + assignment_fractions=global_fractions, + total_valid_tokens=total_tokens, + ) + if is_moe + else answer.new_zeros(()) + ) + loss = answer + coefficient * balance + if needs_prepass: + replay_count_error += sum( + (left["assignment_counts"] - right["assignment_counts"]).abs().sum() + for left, right in zip(collected[chunk_index], aux["router_stats"], strict=True) + ) + elif is_moe: + collected = [aux["router_stats"]] + global_fractions, total_tokens = api.combine_router_fractions(collected) + _finite(loss.detach(), "objective") + loss.backward() + answer_loss += float(answer.detach()) + balance_loss += float(balance.detach()) + executed += tokens.numel() + readout += positions.numel() + attention += len(chunk) * tokens.shape[1] ** 2 + if int(replay_count_error) != 0: + raise RuntimeError("MoE RNG replay did not reproduce routing assignment counts") + norm = torch.nn.utils.clip_grad_norm_( + model.parameters(), float(spec.get("clip_grad_norm", 1.0)), error_if_nonfinite=True + ) + _finite(norm, "gradient norm") + optimizer.step() + effective = sum(len(r["encoded"]["input"]) for r in records) + result = { + "loss": answer_loss, + "answer_ce": answer_loss, + "balance_loss": balance_loss, + "balance_coefficient": coefficient, + "objective": answer_loss + coefficient * balance_loss, + "gradient_norm": float(norm), + "executed_input_tokens": executed, + "effective_input_tokens": effective, + "padding_input_tokens": executed - effective, + "readout_positions": readout, + "attention_token_pairs": attention, + "routing_prepass_executed_input_tokens": executed if needs_prepass else 0, + "routing_prepass_effective_input_tokens": effective if needs_prepass else 0, + } + result["compute"] = api.flop_ledger( + model, + executed_tokens=executed, + valid_tokens=effective, + projected_positions=readout, + attention_pairs=attention, + ) + prepass = result["compute"]["forward_leading_matmul_flops"] if needs_prepass else 0 + result["compute"]["routing_prepass_matmul_flops"] = prepass + result["estimated_matmul_training_flops"] = ( + result["compute"]["estimated_matmul_training_flops"] + prepass + ) + result["compute"]["estimated_total_training_matmul_flops"] = result[ + "estimated_matmul_training_flops" + ] + if is_moe: + layer_count = len(global_fractions) + assignments = torch.stack( + [sum(c[layer]["assignment_counts"] for c in collected) for layer in range(layer_count)] + ) + processed = torch.stack( + [ + sum(c[layer]["processed_assignments"] for c in collected) + for layer in range(layer_count) + ] + ) + dropped = sum(s["dropped_assignments"] for c in collected for s in c) + if int(dropped) != 0 or not torch.equal(processed, assignments.sum(-1)): + raise AssertionError("Dropless routing lost selected token assignments") + result["router"] = { + "assignment_fractions": torch.stack(global_fractions).detach().cpu().tolist(), + "assignment_counts": assignments.detach().cpu().tolist(), + "valid_tokens_per_layer": effective, + "selected_assignments_per_layer": assignments.sum(-1).detach().cpu().tolist(), + "processed_assignments_per_layer": processed.detach().cpu().tolist(), + "router_entropy_per_layer": torch.stack( + [ + sum(c[layer]["entropy_sum"] for c in collected) / effective + for layer in range(layer_count) + ] + ) + .detach() + .cpu() + .tolist(), + "selected_probability_mass_per_layer": torch.stack( + [ + sum(c[layer]["selected_mass_sum"] for c in collected) / effective + for layer in range(layer_count) + ] + ) + .detach() + .cpu() + .tolist(), + "dropped_assignments": int(dropped), + "replay_assignment_count_error": int(replay_count_error), + "replay_checked": needs_prepass, + "balance_scope": ( + "full_effective_batch_two_pass_rng_replay" + if needs_prepass + else "full_effective_batch_single_forward" + ), + } + return result + + +def selection_score(metrics): + """Frozen development panels only; no held-out-composition selection.""" + atomic, composition = metrics["atomic"]["nll"], metrics["train_composition"]["nll"] + if atomic is None or composition is None: + raise ValueError("Both fixed development panels need answer NLL measurements") + value = 0.5 * atomic + 0.5 * composition + _finite(value, "development selection NLL") + return value + + +def _routing_metrics(router): + """Expose numeric dictionaries to the existing W&B sidecar's flattening.""" + if not router: + return {} + return { + "dropped_assignments": router["dropped_assignments"], + "replay_assignment_count_error": router["replay_assignment_count_error"], + "layers": { + str(layer): { + "entropy": router["router_entropy_per_layer"][layer], + "selected_probability_mass": router["selected_probability_mass_per_layer"][layer], + "expert_fraction": {str(i): value for i, value in enumerate(fractions)}, + } + for layer, fractions in enumerate(router["assignment_fractions"]) + }, + } + + +def save_checkpoint(path, model, optimizer, stream, counts, step, counters, device, **extra): + path = Path(path) + temporary = path.with_suffix(".tmp") + torch.save( + { + "format_version": 1, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "step": step, + "counters": counters, + "rng": rng_state(device), + **extra, + }, + temporary, + ) + temporary.replace(path) + + +def load_checkpoint(path, model, optimizer, stream, device): + state = torch.load(path, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + stream.load_state_dict(state["stream"]) + restore_rng(state["rng"], device) + return state + + +def _identity(config, spec): + payload = { + "model": config["model"], + "spec": spec, + "data_sha256": config["data_sha256"], + "tokenizer_sha256": config.get("tokenizer_sha256", config.get("tokenizer_files", {})), + "source_files": config.get("source_files", {}), + } + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + + +def verify(config, config_path=None): + """Check the concrete execution freeze; the historical design is not mutated.""" + if config.get("launch_enabled") is False: + raise ValueError("This configuration explicitly disables execution") + if sha256(config["data_file"]) != config["data_sha256"]: + raise ValueError("Frozen data changed") + for name, expected in config.get("tokenizer_sha256", {}).items(): + path = Path(config["tokenizer"]) / name + if sha256(path) != expected: + raise ValueError(f"Frozen tokenizer changed: {path}") + for group in ("tokenizer_files", "source_files"): + for path, expected in config.get(group, {}).items(): + if sha256(path) != expected: + raise ValueError(f"Frozen {group} changed: {path}") + if config.get("source_root"): + root = Path(config["source_root"]).resolve() + for module in (Path(__file__), Path(_architecture().__file__), Path(historical.__file__)): + if not module.resolve().is_relative_to(root): + raise ValueError(f"Imported code is outside the frozen source_root: {module}") + if config_path is not None: + if not config.get("execution_lock"): + raise ValueError("CLI requires an execution_lock with the frozen config hash") + lock = json.loads(Path(config["execution_lock"]).read_text()) + if lock["config_sha256"] != sha256(config_path): + raise ValueError("Frozen configuration changed") + if "torch" in lock.get("environment", {}): + if str(torch.__version__) != lock["environment"]["torch"]: + raise ValueError("Frozen torch version changed") + if "transformers" in lock.get("environment", {}): + if transformers.__version__ != lock["environment"]["transformers"]: + raise ValueError("Frozen transformers version changed") + + +def _setup(device, config): + torch.set_num_threads(int(config.get("cpu_threads", 4))) + if torch.device(device).type == "cuda": + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.cuda.reset_peak_memory_stats(device) + + +def _resources(device): + if torch.device(device).type != "cuda": + return {"peak_gpu_memory_bytes": 0, "peak_gpu_reserved_bytes": 0} + return { + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device), + "peak_gpu_reserved_bytes": torch.cuda.max_memory_reserved(device), + } + + +def _process_identity(): + """Different containers can both run Python as PID 1; identify the namespace.""" + identity = {"pid": os.getpid()} + if Path("/proc/self/stat").exists(): + identity["pid_namespace"] = os.readlink("/proc/self/ns/pid") + identity["start_ticks"] = Path("/proc/self/stat").read_text().rsplit(")", 1)[1].split()[19] + return identity + + +def run(config, spec, out, device="cuda:0"): + """Train one frozen candidate. An independent process must subsequently audit.""" + verify(config) + _setup(device, config) + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "trained.json").exists(): + trained = json.loads((out / "trained.json").read_text()) + if trained["identity"] != _identity(config, spec): + raise ValueError("Existing output belongs to a different frozen training recipe") + return trained + api = _architecture() + data = json.loads(Path(config["data_file"]).read_text()) + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + records = data["atoms"] + data["train_compositions"] + model = api.construct(config["model"], spec, device) + optimizer = api.optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + stream = historical.BatchStream(len(records), spec["sampling_seed"]) + identity = _identity(config, spec) + counts = np.zeros(len(records), dtype=np.int64) + counters = { + "training_seconds": 0.0, + "examples": 0, + "supervised_tokens": 0, + "executed_input_tokens": 0, + "effective_input_tokens": 0, + "estimated_matmul_training_flops": 0, + "routing_prepass_executed_input_tokens": 0, + } + initial_step, wall_offset, history, last = 0, 0.0, [], {} + if (out / "latest.pt").exists(): + saved = load_checkpoint(out / "latest.pt", model, optimizer, stream, device) + if saved["identity"] != identity: + raise ValueError("Checkpoint belongs to a different frozen training recipe") + counts, initial_step, counters = saved["counts"], saved["step"], saved["counters"] + wall_offset, last = saved.get("wall_seconds", 0.0), saved.get("last_update", {}) + learning = out / "learning.json" + history = [r for r in json.loads(learning.read_text()) if r["step"] <= initial_step] + metadata = json.loads((out / "run.json").read_text()) + metadata.update(pid=os.getpid(), resumed_from_step=initial_step) + del saved + else: + torch.manual_seed(spec["dropout_seed"]) + random.seed(spec["dropout_seed"]) + np.random.seed(spec["dropout_seed"]) + metadata = { + "spec": spec, + "model": config["model"], + "phase": config.get("phase", "development"), + "evaluation_nodes": config["evaluation_nodes"], + "world_sha256": config["data_sha256"], + "initial_model_sha256": model_digest(model), + "initial_tensor_sha256": historical.tensor_digests(model), + "initialization_manifest": api.initialization_manifest(model), + "parameters": sum(p.numel() for p in model.parameters()), + "parameter_ledger": api.parameter_ledger(model), + "atomic_examples": len(data["atoms"]), + "composition_examples": len(data["train_compositions"]), + "vocab_size": len(tokenizer), + "dtype": "BF16 AMP; FP32 parameters and Adam states", + "device": str(device), + "gpu": torch.device(device).index or 0, + "gpu_name": torch.cuda.get_device_name(device) + if torch.device(device).type == "cuda" + else "cpu", + "pid": os.getpid(), + "job_type": config.get("phase", "development") + "-training", + "tracking_group": config.get("tracking", {}).get("group", config.get("experiment")), + "learning_step_unit": "optimizer_updates", + "identity": identity, + "selection": "0.5 atomic + 0.5 train-composition NLL on original fixed panels", + "selection_panel_sizes": { + key: len(data["panels"][key]) for key in ("atomic", "train_composition") + }, + "moe_balance": ( + "full-effective-batch; single forward when one microbatch, otherwise two-pass " + "RNG replay; actual prepass compute included" + ), + "learning_rate_schedule": "historical lr * min((step - 1) / warmup_steps, 1)", + } + if config.get("execution_lock"): + metadata["execution_lock_sha256"] = sha256(config["execution_lock"]) + write_json(out / "run.json", metadata) + write_json(out / "learning.json", history) + nodes = set(config["evaluation_nodes"]) | {int(spec["steps"])} + log_interval = int(config.get("log_interval", 100)) + checkpoint_interval = int(config.get("resume_checkpoint_interval", 1000)) + started = time.perf_counter() + + def checkpoint(step): + save_checkpoint( + out / "latest.pt", + model, + optimizer, + stream, + counts, + step, + counters, + device, + identity=identity, + wall_seconds=wall_offset + time.perf_counter() - started, + last_update=last, + ) + + for step in range(initial_step, spec["steps"] + 1): + if step > initial_step: + warmup = int(spec["warmup_steps"]) + lr = spec["learning_rate"] * (min((step - 1) / warmup, 1.0) if warmup else 1.0) + for group in optimizer.param_groups: + group["lr"] = lr + ids = stream.batch(spec["batch_size"]) + selected = [records[i] for i in ids] + _synchronize(device) + begin = time.perf_counter() + last = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id) + _synchronize(device) + counters["training_seconds"] += time.perf_counter() - begin + 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", + "routing_prepass_executed_input_tokens", + ): + counters[key] += last[key] + if step in nodes or step % log_interval == 0: + if not any(r["step"] == step for r in history): + metrics = {} + if step in nodes: + metrics, predictions = historical.evaluate_dataset( + model, data, tokenizer, device + ) + write_json(out / f"predictions-{step:07d}.json", predictions) + metrics["selection"] = { + "mixed_answer_nll": selection_score(metrics), + "atomic_n": metrics["atomic"]["nll_n"], + "train_composition_n": metrics["train_composition"]["nll_n"], + } + if last.get("router"): + metrics["routing"] = _routing_metrics(last["router"]) + record = { + "step": step, + "metrics": metrics, + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "loss": last.get("answer_ce"), + "answer_ce": last.get("answer_ce"), + "balance_loss": last.get("balance_loss"), + "objective": last.get("objective"), + "gradient_norm": last.get("gradient_norm"), + "learning_rate": optimizer.param_groups[0]["lr"], + "atomic_epochs": float(counts[: len(data["atoms"])].mean()), + "composition_epochs": float(counts[len(data["atoms"]) :].mean()), + "router": last.get("router", {}), + "compute_per_update": last.get("compute", {}), + **_resources(device), + "created_utc": utc(), + } + history.append(record) + write_json(out / "learning.json", history) + print( + json.dumps({"step": step, "loss": record["loss"], "metrics": metrics}), + flush=True, + ) + write_json( + out / "status.json", + { + "state": "training", + "step": step, + "target_step": spec["steps"], + "loss": last.get("answer_ce"), + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "pid": os.getpid(), + "updated_utc": utc(), + }, + ) + if step in nodes or (step > initial_step and step % checkpoint_interval == 0): + checkpoint(step) + if step in nodes: + target = out / f"checkpoint-{step:07d}.pt" + temporary = target.with_suffix(".tmp") + torch.save( + {"model": model.state_dict(), "step": step, "identity": identity}, temporary + ) + temporary.replace(target) + np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts) + metrics, predictions = historical.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(), + "process_identity": _process_identity(), + "identity": identity, + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + **counters, + "selection_mixed_answer_nll": next( + r["metrics"]["selection"]["mixed_answer_nll"] + for r in reversed(history) + if r["step"] == spec["steps"] + ), + "wall_seconds": wall_offset + time.perf_counter() - started, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + return result + + +def audit(config, spec, out, device="cuda:0"): + """Reconstruct and regenerate the full endpoint in an independent process.""" + verify(config) + _setup(device, config) + out = Path(out) + trained = json.loads((out / "trained.json").read_text()) + same_process = ( + trained["process_identity"] == _process_identity() + if "process_identity" in trained + else trained["pid"] == os.getpid() + ) + if same_process: + raise ValueError("Independent audit must run in a different process") + if trained["identity"] != _identity(config, spec): + raise ValueError("Audit recipe differs from the training freeze") + if sha256(out / "latest.pt") != trained["checkpoint_sha256"]: + raise ValueError("Training checkpoint changed") + model = _architecture().construct(config["model"], spec, device) + checkpoint = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) + if checkpoint["step"] != spec["steps"]: + raise ValueError("Final checkpoint does not contain the requested endpoint") + model.load_state_dict(checkpoint["model"]) + del checkpoint + if model_digest(model) != trained["model_sha256"]: + raise ValueError("Reloaded model does not match the trained endpoint") + data = json.loads(Path(config["data_file"]).read_text()) + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + metrics, predictions = historical.evaluate_dataset( + model, data, tokenizer, device, full=True, autonomous=True + ) + if predictions != json.loads((out / "endpoint-predictions.json").read_text()): + raise AssertionError("Independent endpoint generation or NLL failed exact reproduction") + if metrics != json.loads((out / "endpoint.json").read_text()): + raise AssertionError("Independent endpoint metric recount failed") + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "process_identity": _process_identity(), + "source_process_identity": trained.get("process_identity"), + "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, + }, + ) + return result diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/qwen_constraints.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/qwen_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..6181f6dad22ab1a99443ffddb19f67c7c6ad701b --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/qwen_constraints.py @@ -0,0 +1,94 @@ +"""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) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/qwen_path_learning.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/qwen_path_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..bc113a47da9c9fc22e346812c7f48f5ae7bc8b92 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/qwen_path_learning.py @@ -0,0 +1,416 @@ +"""Position-routed down updates, complete-answer objectives, and audited data helpers.""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import time +from datetime import datetime, timezone +from pathlib import Path + +os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") +os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import AutoModelForCausalLM, AutoTokenizer + +from .hebbian_data import TEMPLATE, encode_answer, score_answer +from .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 articles diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/qwen_path_train.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/qwen_path_train.py new file mode 100644 index 0000000000000000000000000000000000000000..fabb31112396100c708fafd83993acdb8c46f918 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/qwen_path_train.py @@ -0,0 +1,627 @@ +"""Frozen-matrix execution and development-only selection for path learning.""" + +from __future__ import annotations + +import json +import os +import platform +import shutil +import time + +import numpy as np +import torch +import 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 result diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/realworld_composition.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/realworld_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..a05d1c9d956093315cedab365228e2fce72b6022 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/realworld_composition.py @@ -0,0 +1,629 @@ +"""Complete GPT/Loop training on original 2Wiki questions and atomic facts.""" + +from __future__ import annotations + +import copy +import hashlib +import json +import math +import os +import time +from contextlib import nullcontext +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import GPT2Config, GPT2TokenizerFast + +from .grok_depth import utc +from .grokking_reproduction import ReproductionGPT, model_digest +from .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), + canonical_answer_globally_unambiguous=row.get( + "canonical_answer_globally_unambiguous", True + ), + 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_unambiguous_canonical_answers": lambda r: r.get( + "canonical_answer_globally_unambiguous", True + ), + "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) + 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": row["id"], + "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": bool(row.get("unambiguous_answers", [])), + "canonical_answer_globally_unambiguous": row.get( + "canonical_answer_globally_unambiguous", True + ), + "invalid_generated_bridge_length": True, + } + for row 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, wall_seconds=None): + 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, + "wall_seconds": wall_seconds, + "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) + phase = config.get("phase", "development") + out = Path(config["results_root"]) / phase / 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 = checkpoint.get("wall_seconds") + if wall_offset is None: + wall_offset = history[-1]["wall_seconds"] if history else 0.0 + metadata = json.loads((out / "run.json").read_text()) + metadata.update(pid=os.getpid(), gpu=gpu, resumed_from_step=initial_step) + write_json(out / "run.json", metadata) + del checkpoint + else: + torch.manual_seed(spec["dropout_seed"]) + metadata = { + "spec": spec, + "model": config["model"], + "phase": phase, + "evaluation_nodes": config["evaluation_nodes"], + "execution_lock_sha256": sha256(config["execution_lock"]), + "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": phase + "-training", + "tracking_group": config["tracking"]["group"], + } + 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, + "training_seconds": counters["training_seconds"], + "examples": counters["examples"], + "wall_seconds": wall_offset + time.perf_counter() - started, + "pid": os.getpid(), + "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, + wall_offset + time.perf_counter() - started, + ) + 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, + ) + elif ( + step > initial_step and step % config.get("resume_checkpoint_interval", 1000000000) == 0 + ): + save_checkpoint( + out / "latest.pt", + model, + optimizer, + stream, + counts, + step, + counters, + wall_offset + time.perf_counter() - started, + ) + 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"]) / config.get("phase", "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}, + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/realworld_composition_data.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/realworld_composition_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e907ece415c9c6e027e965818c1b8e6f82a2462e --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/realworld_composition_data.py @@ -0,0 +1,270 @@ +"""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 which +evaluation facts may be learned separately, never with evaluation chain labels. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import string +import zipfile +from collections import Counter, defaultdict +from 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]} diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/realworld_confirmation.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/realworld_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..5cfed1010e1cc6f386e54d10c69675d34f4bed4a --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/realworld_confirmation.py @@ -0,0 +1,322 @@ +"""Data-only confirmation isolation and independent endpoint recounting.""" + +from __future__ import annotations + +import ast +import copy +import json +import re +import statistics +import string +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from .realworld_composition_data import normalize_answer, order, sha256, write_json + + +def head_bridge_names(data, canonical, aliases): + names = defaultdict(set) + for row in data["train_compositions"] + data["evaluation_compositions"]: + for index in (0, 2): + identifier = row["edges"][0][index] + labels = [canonical[identifier], row["surfaces"][0][index]] + for label in labels + aliases.get(identifier, []): + normalized = normalize_answer(label) + if normalized: + names[identifier].add(normalized) + return names + + +def answer_owners(canonical, aliases): + owners = defaultdict(set) + for identifier in set(canonical) | set(aliases): + for name in [canonical.get(identifier, ""), *aliases.get(identifier, [])]: + normalized = normalize_answer(name) + if normalized: + owners[normalized].add(identifier) + return owners + + +def isolate_confirmation(candidate, development, canonical, aliases): + """Exclude every chain touching a development head/bridge name, then rebuild.""" + dev_names = set().union(*head_bridge_names(development, canonical, aliases).values()) + formal_names = head_bridge_names(candidate, canonical, aliases) + excluded_entities = {e for e, names in formal_names.items() if names & dev_names} + excluded = {} + parts = {} + for key in ("train_compositions", "evaluation_compositions"): + excluded[key] = [ + r["id"] + for r in candidate[key] + if {r["edges"][0][0], r["edges"][0][2]} & excluded_entities + ] + excluded_ids = set(excluded[key]) + parts[key] = [copy.deepcopy(r) for r in candidate[key] if r["id"] not in excluded_ids] + all_chains = parts["train_compositions"] + parts["evaluation_compositions"] + used = {a for r in all_chains for a in r["atom_ids"]} + atoms = [copy.deepcopy(r) for r in candidate["atoms"] if r["id"] in used] + first, second = ({r["atom_ids"][i] for r in parts["train_compositions"]} for i in (0, 1)) + seen = first | second + direct = {(r["edge"][0], r["edge"][2]) for r in atoms} + pairs = {(r["edges"][0][0], r["edges"][1][2]) for r in parts["train_compositions"]} + operations = {tuple(e[1] for e in r["edges"]) for r in parts["train_compositions"]} + owners = answer_owners(canonical, aliases) + for row in atoms + all_chains: + identifier = row["edge"][2] if "edge" in row else row["edges"][1][2] + row["canonical_answer_globally_unambiguous"] = owners[normalize_answer(row["answer"])] == { + identifier + } + for row in all_chains: + a, b = row["atom_ids"] + row["role"] = ("I" if a in seen else "O") + ("I" if b in seen else "O") + row["required_role"] = ("I" if a in first else "O") + ("I" if b in second else "O") + pair = row["edges"][0][0], row["edges"][1][2] + row["known_direct_shortcut"] = pair in direct + row["head_tail_seen_in_combination_training"] = pair in pairs + row["operation_seen"] = tuple(e[1] for e in row["edges"]) in operations + panels = { + "test_" + role.lower(): [ + r["id"] + for r in sorted( + [r for r in parts["evaluation_compositions"] if r["role"] == role], + key=lambda r: order(r["id"], "panel:"), + )[:64] + ] + for role in ("II", "IO", "OI", "OO") + } + panels["train_composition"] = [ + r["id"] + for r in sorted(parts["train_compositions"], key=lambda r: order(r["id"], "panel:"))[:128] + ] + selected = {i for ids in panels.values() for i in ids} + required = {a for r in all_chains if r["id"] in selected for a in r["atom_ids"]} + panels["atomic"] = sorted( + required + | {r["id"] for r in sorted(atoms, key=lambda r: order(r["id"], "atom-panel:"))[:128]} + ) + data = {"atoms": atoms, **parts, "panels": panels} + report = { + "rule": ( + "Exclude chains whose head/bridge canonical, annotated surface or official alias " + "name overlaps development head/bridge names after author normalization; " + "retain shared tails." + ), + "excluded_entities": sorted(excluded_entities), + "excluded_case_ids": excluded, + "excluded_counts": {key: len(ids) for key, ids in excluded.items()}, + "colliding_names": sorted(dev_names & set().union(*formal_names.values())), + "model_results_used": False, + } + return data, report + + +def audit_confirmation(data, development, canonical, aliases): + """Recount from the selected records rather than selection bookkeeping.""" + atoms = {r["id"]: r for r in data["atoms"]} + train, held = data["train_compositions"], data["evaluation_compositions"] + rows = train + held + dev_names = head_bridge_names(development, canonical, aliases) + formal_names = head_bridge_names(data, canonical, aliases) + assert not set(dev_names) & set(formal_names) + assert not set().union(*dev_names.values()) & set().union(*formal_names.values()) + assert len(atoms) == len(data["atoms"]) + assert len({r["id"] for r in rows}) == len(rows) + + def chain(row): + return tuple(tuple(e) for e in row["edges"]) + + assert not {chain(r) for r in train} & {chain(r) for r in held} + held_questions = {normalize_answer(r["question"]) for r in held} + assert not {normalize_answer(r["question"]) for r in train} & held_questions + assert not {normalize_answer(r["question"]) for r in atoms.values()} & held_questions + assert not {normalize_answer(r["question"]) for r in atoms.values()} & { + normalize_answer(r["question"]) for r in development["atoms"] + } + seen = {a for r in train for a in r["atom_ids"]} + first, second = ({r["atom_ids"][i] for r in train} for i in (0, 1)) + owners = answer_owners(canonical, aliases) + for row in rows: + a, b = row["atom_ids"] + assert [atoms[a]["edge"], atoms[b]["edge"]] == row["edges"] + assert row["edges"][0][2] == row["edges"][1][0] + assert row["role"] == ("I" if a in seen else "O") + ("I" if b in seen else "O") + assert row["required_role"] == ("I" if a in first else "O") + ("I" if b in second else "O") + assert not row["structural_errors"] + assert not any(r["known_prior_case"] for r in held) + for pool in (list(atoms.values()), train, held): + prompt_answers = defaultdict(set) + for row in pool: + prompt_answers[normalize_answer(row["question"])].add(normalize_answer(row["answer"])) + identifier = row["edge"][2] if "edge" in row else row["edges"][1][2] + assert row["canonical_answer_globally_unambiguous"] == ( + owners[normalize_answer(row["answer"])] == {identifier} + ) + e = row["encoded"] + assert e["target"][-1] == 50256 and len(e["target"]) <= 64 + assert e["input"] == (e["prefix"] + e["target"])[:-1] + assert len(e["prefix"]) + len(e["target"]) <= 256 + assert all(len(answers) == 1 for answers in prompt_answers.values()) + panel_ids = {i for name, ids in data["panels"].items() if name != "atomic" for i in ids} + assert {a for r in rows if r["id"] in panel_ids for a in r["atom_ids"]} <= set( + data["panels"]["atomic"] + ) + return { + "passed": True, + "atoms": len(atoms), + "train_compositions": len(train), + "evaluation_compositions": len(held), + "evaluation_roles": dict(Counter(r["role"] for r in held)), + "required_role_counts": dict(Counter(r["required_role"] for r in held)), + "canonical_unambiguous_evaluation_count": sum( + r["canonical_answer_globally_unambiguous"] for r in held + ), + "panels": {name: len(ids) for name, ids in data["panels"].items()}, + "head_bridge_id_overlap": 0, + "head_bridge_normalized_name_overlap": 0, + "necessary_atomic_coverage": 1.0, + "known_direct_shortcuts": sum(r["known_direct_shortcut"] for r in held), + "unseen_operations": sum(not r["operation_seen"] for r in held), + "max_input_tokens": max(len(r["encoded"]["input"]) for r in list(atoms.values()) + rows), + "atomic_relations": dict(Counter(r["edge"][1] for r in atoms.values())), + "train_relation_pairs": dict(Counter(" -> ".join(e[1] for e in r["edges"]) for r in train)), + } + + +def finalize_confirmation(config): + """Independently score raw outputs using the pinned author's scorer functions.""" + root, art = Path(config["results_root"]), Path(config["artifact_root"]) + data = json.loads(Path(config["data_file"]).read_text()) + scorer = Path(config["official_scorer"]) + scope = dict(re=re, string=string, Counter=Counter) + tree = ast.parse(scorer.read_text()) + functions = [ + n + for n in tree.body + if isinstance(n, ast.FunctionDef) and n.name in {"normalize_answer", "exact_match_score"} + ] + exec(compile(ast.Module(body=functions, type_ignores=[]), str(scorer), "exec"), scope) + + def score(prediction, row): + return float( + any( + scope["exact_match_score"](prediction, g) + for g in [row["answer"], *row.get("aliases", [])] + ) + ) + + held = data["evaluation_compositions"] + summary, scores, atom_scores, exposures, metadata = {}, {}, {}, {}, {} + for spec in config["runs"]: + name = spec["name"] + out = root / config["phase"] / name + complete = json.loads((out / "complete.json").read_text()) + assert complete["step"] == spec["steps"] and complete["independently_reloaded"] + raw = json.loads((out / "endpoint-predictions.json").read_text()) + metrics = json.loads((out / "endpoint.json").read_text()) + for group, records in [ + ("atomic", data["atoms"]), + ("train_composition", data["train_compositions"]), + ("test_all", held), + ]: + by_id = {p["id"]: p for p in raw[group]} + assert len(by_id) == len(records) == len(raw[group]) + assert set(by_id) == {r["id"] for r in records} + recomputed = {r["id"]: score(by_id[r["id"]]["prediction"], r) for r in records} + assert all(recomputed[i] == by_id[i]["alias_em"] for i in recomputed) + assert abs(sum(recomputed.values()) / len(records) - metrics[group]["alias_em"]) < 1e-12 + if group == "test_all": + scores[name] = recomputed + for role in ("II", "IO", "OI", "OO"): + selected = [r for r in held if r["role"] == role] + assert ( + abs( + sum(recomputed[r["id"]] for r in selected) / len(selected) + - metrics["test_" + role.lower()]["alias_em"] + ) + < 1e-12 + ) + if group == "atomic": + atom_scores[name] = recomputed + summary[name] = metrics + exposures[name] = { + step: np.load(out / f"exposure-{step:07d}.npz")["counts"] + for step in config["evaluation_nodes"] + } + metadata[name] = json.loads((out / "run.json").read_text()) + assert complete["checkpoint_sha256"] == sha256(out / "latest.pt") + comparisons = [] + for seed in sorted({s["initialization"] for s in config["runs"]}): + specs = {s["architecture"]: s for s in config["runs"] if s["initialization"] == seed} + assert set(specs) == {"standard8", "loop4x2", "standard4"} + names = [s["name"] for s in specs.values()] + assert len({metadata[n]["common_four_block_initial_sha256"] for n in names}) == 1 + for step in config["evaluation_nodes"]: + assert all( + np.array_equal(exposures[names[0]][step], exposures[n][step]) for n in names[1:] + ) + for baseline in ("standard8", "standard4"): + loop, base = specs["loop4x2"]["name"], specs[baseline]["name"] + for role in ("all", "OO"): + selected = held if role == "all" else [r for r in held if r["role"] == role] + common = [ + r + for r in selected + if all(atom_scores[n][a] for n in (loop, base) for a in r["atom_ids"]) + ] + comparisons.append( + { + "initialization": seed, + "baseline": baseline, + "pool": role, + "n": len(selected), + "paired_difference": sum( + scores[loop][r["id"]] - scores[base][r["id"]] for r in selected + ) + / len(selected), + "both_models_necessary_atoms_correct_n": len(common), + "both_models_necessary_atoms_correct_coverage": len(common) / len(selected), + "conditional_paired_difference": sum( + scores[loop][r["id"]] - scores[base][r["id"]] for r in common + ) + / len(common) + if common + else None, + } + ) + means = {} + for architecture in ("standard8", "loop4x2", "standard4"): + names = [s["name"] for s in config["runs"] if s["architecture"] == architecture] + means[architecture] = {} + for group in ( + "atomic", + "train_composition", + "test_all", + "test_ii", + "test_io", + "test_oi", + "test_oo", + "autonomous", + ): + values = [summary[n][group]["alias_em"] for n in names] + means[architecture][group] = { + "mean": statistics.mean(values), + "sample_sd": statistics.stdev(values), + "per_initialization": values, + } + result = { + "passed": True, + "runs": len(config["runs"]), + "scientific_updates": sum(s["steps"] for s in config["runs"]), + "independent_dataset_splits": 1, + "paired_initializations": 3, + "paired_exposures_equal_at_all_nodes": True, + "architecture_scores": means, + "paired_comparisons": comparisons, + "source_data_sha256": sha256(config["data_file"]), + "official_scorer_sha256": sha256(scorer), + } + write_json(art / "confirmation-summary.json", summary) + write_json(art / "confirmation-recount-audit.json", result) + return result diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..1b6fcadbe2e7be2944fe6e398e29c0812ca1329f --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py @@ -0,0 +1,119 @@ +"""Registered relation/component and paired-knowledge trajectory descriptions.""" + +from __future__ import annotations + +import json +from collections import defaultdict +from pathlib import Path + +from .realworld_composition_data import write_json + + +def threshold_intervals(history, group, threshold): + passed = [r["metrics"][group]["alias_em"] >= threshold for r in history] + + def interval(index): + if index is None: + return None + return [history[index - 1]["step"] if index else None, history[index]["step"]] + + first = next((i for i, value in enumerate(passed) if value), None) + sustained = next((i for i, value in enumerate(passed) if value and all(passed[i:])), None) + return { + "first_observed_interval": interval(first), + "sustained_observed_interval": interval(sustained), + } + + +def analyze_confirmation(config): + root = Path(config["results_root"]) / config["phase"] + data = json.loads(Path(config["data_file"]).read_text()) + held = {r["id"]: r for r in data["evaluation_compositions"]} + endpoint_groups, thresholds, nodes = {}, {}, {} + for spec in config["runs"]: + name = spec["name"] + out = root / name + raw = json.loads((out / "endpoint-predictions.json").read_text())["test_all"] + by_relation, by_component = defaultdict(list), defaultdict(list) + for prediction in raw: + row = held[prediction["id"]] + by_relation[" -> ".join(e[1] for e in row["edges"])].append(prediction["alias_em"]) + by_component[row["group"]].append(prediction["alias_em"]) + endpoint_groups[name] = { + key: {k: {"n": len(v), "alias_em": sum(v) / len(v)} for k, v in groups.items()} + for key, groups in [ + ("relation_pair", by_relation), + ("source_head_bridge_component", by_component), + ] + } + history = json.loads((out / "learning.json").read_text()) + thresholds[name] = { + f"{group}_{value}": threshold_intervals(history, group, value) + for group, value in [("train_composition", 0.99), ("test_all", 0.5), ("test_all", 0.9)] + } + nodes[name] = {} + for step in config["evaluation_nodes"]: + node = json.loads((out / f"predictions-{step:07d}.json").read_text()) + nodes[name][step] = { + group: {r["id"]: r["alias_em"] for r in node[group]} + for group in ("atomic", "test_all") + } + trajectories = [] + for seed in sorted({s["initialization"] for s in config["runs"]}): + specs = {s["architecture"]: s for s in config["runs"] if s["initialization"] == seed} + loop = specs["loop4x2"]["name"] + for baseline in ("standard8", "standard4"): + base = specs[baseline]["name"] + for step in config["evaluation_nodes"]: + left, right = nodes[loop][step], nodes[base][step] + assert set(left["test_all"]) == set(right["test_all"]) + for pool in ("all", "OO"): + selected = [ + held[i] + for i in left["test_all"] + if pool == "all" or held[i]["role"] == pool + ] + common = [ + r + for r in selected + if all(n["atomic"][a] for n in (left, right) for a in r["atom_ids"]) + ] + trajectories.append( + { + "initialization": seed, + "baseline": baseline, + "step": step, + "pool": pool, + "panel_n": len(selected), + "both_models_necessary_atoms_correct_n": len(common), + "both_models_necessary_atoms_correct_coverage": len(common) + / len(selected), + "full_panel_paired_difference": sum( + left["test_all"][r["id"]] - right["test_all"][r["id"]] + for r in selected + ) + / len(selected), + "conditional_paired_difference": sum( + left["test_all"][r["id"]] - right["test_all"][r["id"]] + for r in common + ) + / len(common) + if common + else None, + } + ) + result = { + "endpoint_groups": endpoint_groups, + "threshold_intervals": thresholds, + "paired_knowledge_trajectories": trajectories, + "trajectory_scope": ( + "Fixed panels at registered nodes; threshold brackets are descriptive and do not " + "identify exact crossing times or establish grokking." + ), + "endpoint_scope": ( + "Full registered evaluation pool; source components are shared by questions, " + "not independent worlds." + ), + } + write_json(Path(config["artifact_root"]) / "confirmation-analysis.json", result) + return result diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/recurrence_use.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/recurrence_use.py new file mode 100644 index 0000000000000000000000000000000000000000..3f2cf4432769a0bc1ea0278bf25468307718877b --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/recurrence_use.py @@ -0,0 +1,416 @@ +"""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 frequency +from creating additional scientific observations. +""" + +from __future__ import annotations + +import time + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import EOS, prompt_rows, truth_path_details +from .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, + } diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/representation_alignment.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/representation_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..923e412fdf09bfaf85ca6de1fcb11cf4d6e754de --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/representation_alignment.py @@ -0,0 +1,269 @@ +"""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 hashlib +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .latent_scaling import build_world, construct, model_digest +from .storage_composition import data_digest, evaluate, file_hash, pack_sentences +from .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}, + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/residual_cache.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/residual_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..20f4f21ac38bfedf6fa1d48968333c80c07f06ea --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/residual_cache.py @@ -0,0 +1,258 @@ +"""Shared LoopGPT backbone with independently controlled residual and KV access. + +The single/gamma=1 numerical path delegates to the historical shared-cache +implementation. Eight unique controllers are reused across every loop; streams +and the first-loop per-layer KV are carried through the complete unroll. +""" + +from __future__ import annotations + +import torch +from torch import nn +from torch.nn import functional as F + +from .grok_depth import make_optimizer as ordinary_optimizer +from .grok_loop_model import _positive_integer +from .latent_scaling import construct as ordinary_construct +from .parametric_architecture import HyperConnection, residual_mix, sinkhorn +from .shared_cache import SharedCacheGPT +from .shared_cache import executed_flops as cache_flops + +KINDS = ("single", "identity_mhc", "mhc") +_compiled_sinkhorn = None + + +def training_sinkhorn(logits): + global _compiled_sinkhorn + if _compiled_sinkhorn is None: + _compiled_sinkhorn = torch.compile( + sinkhorn, fullgraph=True, dynamic=False, options={"triton.cudagraphs": False} + ) + return _compiled_sinkhorn(logits) + + +class LoopHyperConnection(HyperConnection): + def coefficients(self, x): + n = self.streams + with torch.autocast(x.device.type, enabled=False): + dynamic = self.projection(self.norm(x.float().flatten(-2))) + pre = torch.sigmoid(dynamic[..., :n] * self.alpha_pre + self.pre_bias) + 1e-6 + post = 2 * torch.sigmoid(dynamic[..., n : 2 * n] * self.alpha_post + self.post_bias) + matrix = None + if not self.identity: + logits = dynamic[..., 2 * n :].reshape(*x.shape[:-2], n, n) + logits = logits * self.alpha_res + self.res_bias + projection = training_sinkhorn if self.training and x.is_cuda else sinkhorn + matrix = projection(logits) + return pre, post, matrix + + +class ResidualCacheGPT(SharedCacheGPT): + def __init__( + self, + config, + repeats, + dropout=0.0, + arm="local", + window=2, + residual_kind="single", + gamma=1.0, + controller_seed=107260751, + ): + super().__init__(config, repeats, dropout, arm, window) + if residual_kind not in KINDS or gamma <= 0: + raise ValueError("Invalid residual kind or branch scale") + self.residual_kind, self.gamma = residual_kind, float(gamma) + self.diagnostic_records = None + if residual_kind != "single": + with torch.random.fork_rng(devices=[]): + torch.manual_seed(controller_seed) + self.connections = nn.ModuleList( + LoopHyperConnection(config.width, i, identity=residual_kind == "identity_mhc") + for i in range(2 * config.layers) + ) + + def _record(self, x, update, recursion, layer, branch, matrix=None): + if self.diagnostic_records is None: + return + xf, uf = x.detach().float(), update.detach().float() + if self.residual_kind == "single": + mean, contrast = xf, xf.new_zeros(()) + else: + mean = xf.mean(-2) + contrast = (xf - mean.unsqueeze(-2)).square().mean() + record = dict( + loop=recursion + 1, + layer=layer, + branch=branch, + mean_square=float(mean.square().mean()), + coordinate_variance=float(mean.var(-1, unbiased=False).mean()), + stream_contrast_square=float(contrast), + update_square=float(uf.square().mean()), + ) + if matrix is not None: + a = matrix.detach().float() + previous = getattr(self, "diagnostic_product", None) + product = a if previous is None else previous @ a + self.diagnostic_product = product + record.update( + max_row_error=float((a.sum(-1) - 1).abs().max()), + max_column_error=float((a.sum(-2) - 1).abs().max()), + max_spectral_norm=float(torch.linalg.matrix_norm(a, ord=2).max()), + product_max_row_error=float((product.sum(-1) - 1).abs().max()), + product_max_column_error=float((product.sum(-2) - 1).abs().max()), + product_max_spectral_norm=float(torch.linalg.matrix_norm(product, ord=2).max()), + ) + self.diagnostic_records.append(record) + + def _connection(self, x, sublayer, connection, recursion, layer, branch): + pre, post, matrix = connection.coefficients(x) + with torch.autocast(x.device.type, enabled=False): + contracted = (pre[..., None] * x.float()).sum(-2) + y = sublayer(contracted.to(x.dtype)) + with torch.autocast(x.device.type, enabled=False): + residual = x.float() if matrix is None else residual_mix(x.float(), matrix) + update = post[..., None] * (self.gamma * y.float()).unsqueeze(-2) + output = residual + update + self._record(output, update, recursion, layer, branch, matrix) + return output.to(x.dtype) + + def forward(self, tokens, positions=None, repeats=None): + count = self.repeats if repeats is None else _positive_integer(repeats, "repeats") + if self.residual_kind == "single" and self.gamma == 1 and self.diagnostic_records is None: + return super().forward(tokens, positions, count) + length = tokens.shape[1] + if length > self.config.context: + raise ValueError("Input exceeds mask context") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(length, device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + if self.residual_kind != "single": + x = x.unsqueeze(-2).expand(*x.shape[:-1], 4, x.shape[-1]) + causal = self.shared_causal_mask[:length, :length] + joined_mask = torch.cat((causal, causal), dim=-1) + shared = [] + for recursion in range(count): + for layer, block in enumerate(self.blocks): + + def attention_branch(state, block=block, recursion=recursion, layer=layer): + z = block.ln1(state) + batch, size, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, size, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + q, k, v = (t.transpose(1, 2) for t in (q, k, v)) + if recursion == 0: + shared.append((k, v)) + if recursion == 0 or self.memory_arm == "local" or self.disable_shared: + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=p) + else: + first_k, first_v = (k, v) if self.duplicate_current else shared[layer] + y = F.scaled_dot_product_attention( + q, + torch.cat((first_k, k), dim=-2), + torch.cat((first_v, v), dim=-2), + attn_mask=joined_mask, + dropout_p=p, + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, size, width)) + return F.dropout(y, p=p, training=self.training) + + def mlp_branch(state, block=block): + return F.dropout(block.mlp(block.ln2(state)), p=p, training=self.training) + + if self.residual_kind == "single": + for branch, sublayer in [("attention", attention_branch), ("mlp", mlp_branch)]: + update = self.gamma * sublayer(x) + x = x + update + self._record(x, update, recursion, layer, branch) + else: + x = self._connection( + x, + attention_branch, + self.connections[2 * layer], + recursion, + layer, + "attention", + ) + x = self._connection( + x, mlp_branch, self.connections[2 * layer + 1], recursion, layer, "mlp" + ) + if self.residual_kind != "single": + x = x.mean(-2) + 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 construct(spec, device): + reference = ordinary_construct(spec, "cpu") + torch.manual_seed(spec["initialization"]) + return ResidualCacheGPT( + reference.config, + spec["repeats"], + spec["dropout"], + spec.get("memory_arm", "local"), + spec.get("window", 2), + spec.get("residual_kind", "single"), + spec.get("gamma", 1), + spec.get("controller_initialization_seed", 107260751), + ).to(device) + + +def make_optimizer(model, lr, weight_decay): + if model.residual_kind == "single": + return ordinary_optimizer(model, lr, weight_decay) + decay, no_decay = [], [] + for name, parameter in model.named_parameters(): + # res_bias is a matrix but, like the other controller biases, has no decay. + group = no_decay if parameter.ndim < 2 or name.endswith(".res_bias") else decay + group.append(parameter) + return torch.optim.AdamW( + [{"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0}], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + fused=True, + capturable=True, + ) + + +def executed_flops(config, repeats, batch, sequence, arm, kind, output_positions=9, backward=True): + """Historical matmul ledger plus controller projections and stream mixing. + + Sinkhorn and elementwise operations are excluded and measured in wall time. + The inherited three-forward backward convention is an approximation. + """ + base = cache_flops(config, repeats, batch, sequence, arm, output_positions, backward) + if kind == "single": + return base + n, d = 4, config.width + count = 2 * n + (n * n if kind == "mhc" else 0) + controllers = 2 * config.layers * repeats + per_token = 2 * n * d * count + (2 * n * n * d if kind == "mhc" else 0) + return base + batch * sequence * controllers * per_token * (3 if backward else 1) + + +def install_training_adapter(spec): + from . import latent_scaling as latent + + latent.construct = construct + latent.make_optimizer = make_optimizer + latent.flops = lambda config, repeats, batch, sequence, output_positions=9, backward=True: ( + executed_flops( + config, + repeats, + batch, + sequence, + spec.get("memory_arm", "local"), + spec.get("residual_kind", "single"), + output_positions, + backward, + ) + ) + return latent diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/sequential_data.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/sequential_data.py new file mode 100644 index 0000000000000000000000000000000000000000..dbd398e9973bad820eec8616d2c30ce3b7dd0626 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/sequential_data.py @@ -0,0 +1,379 @@ +"""Deterministic, source-grounded splits for sequential knowledge acquisition. + +The source examples are existing audited 2Wiki adaptations. We change only their +training availability, never their facts, names, answers, or tokenization. +""" + +from __future__ import annotations + +import copy +from collections import Counter, defaultdict +from dataclasses import asdict, dataclass + +from .realworld_composition_data import normalize_answer, order + + +@dataclass(frozen=True) +class SplitSettings: + split: str + bb_count: int = 64 + train_count: int = 512 + evaluation_count: int = 64 + max_shared_b_fact: int = 4 + + +def chain_key(row): + return tuple(tuple(edge) for edge in row["edges"]) + + +def operation(row): + return tuple(edge[1] for edge in row["edges"]) + + +def entities(row): + return {value for edge in row["edges"] for value in (edge[0], edge[2])} + + +def balanced_order(rows, salt): + """Round-robin relation pairs rather than favor the largest answer families.""" + groups = defaultdict(list) + for row in rows: + groups[operation(row)].append(row) + for group in groups.values(): + group.sort(key=lambda row: order(row["id"], salt)) + pairs = sorted(groups, key=lambda pair: order(pair, salt)) + for position in range(max(map(len, groups.values()), default=0)): + for pair in pairs: + if position < len(groups[pair]): + yield groups[pair][position] + + +def safe_atom_ids(atoms, b_ids): + """Exclude exact answer-equivalent addresses and explicit inverse facts. + + This guards known label leakage, not every possible real-world inference. + Entity names may appear in unrelated facts, as required for name familiarity. + """ + direct = {(atoms[key]["edge"][0], atoms[key]["edge"][2]) for key in b_ids} + inverse = set() + for key in b_ids: + head, relation, tail = atoms[key]["edge"] + if relation == "spouse": + inverse.add((tail, "spouse", head)) + elif relation in {"father", "mother"}: + inverse.add((tail, "child", head)) + elif relation == "child": + inverse.update({(tail, "father", head), (tail, "mother", head)}) + return { + key + for key, row in atoms.items() + if key not in b_ids + and (row["edge"][0], row["edge"][2]) not in direct + and tuple(row["edge"]) not in inverse + } + + +def build_split(source, settings, labels=None): + """Select BB first, reserve real A witnesses, then add A-only practice.""" + atoms = {row["id"]: row for row in source["atoms"]} + incident = defaultdict(set) + for key, row in atoms.items(): + for entity in (row["edge"][0], row["edge"][2]): + incident[entity].add(key) + label_owners = defaultdict(set) + for entity, label in (labels or {}).items(): + label_owners[normalize_answer(label)].add(entity) + + def unambiguous(row): + return all( + len(label_owners[normalize_answer(labels[entity])]) == 1 + for entity in entities(row) + if labels and entity in labels + ) + + unique = {} + for row in source["train_compositions"] + source["evaluation_compositions"]: + if row.get("structural_errors") or row.get("known_direct_shortcut"): + continue + if not unambiguous(row): + continue + key = chain_key(row) + if key not in unique or row["id"] < unique[key]["id"]: + unique[key] = row + rows = list(unique.values()) + counts = Counter(operation(row) for row in rows) + candidates = [ + row + for row in rows + if counts[operation(row)] >= 12 + and all(incident[entity] - set(row["atom_ids"]) for entity in entities(row)) + ] + b_ids, witness_ids, selected_bb = set(), set(), [] + b_uses = Counter() + for row in balanced_order(candidates, settings.split + ":bb:"): + proposed = b_ids | set(row["atom_ids"]) + if proposed & witness_ids: + continue + if any(b_uses[key] >= settings.max_shared_b_fact for key in row["atom_ids"]): + continue + safe = safe_atom_ids(atoms, proposed) + if not witness_ids <= safe: + continue + witnesses = set() + for entity in entities(row): + options = incident[entity] & safe + if not options: + break + # Reuse an existing witness when possible; otherwise use a fixed hash. + options = (options & witness_ids) or options + witnesses.add(min(options, key=lambda key: order(key, settings.split + ":witness:"))) + else: + b_ids = proposed + witness_ids |= witnesses + selected_bb.append(row) + b_uses.update(row["atom_ids"]) + if len(selected_bb) == settings.bb_count: + break + if len(selected_bb) < settings.bb_count: + raise ValueError(f"Only {len(selected_bb)} valid BB chains for {settings.split}") + + safe = safe_atom_ids(atoms, b_ids) + b_head_answers = {(atoms[key]["edge"][0], atoms[key]["edge"][2]) for key in b_ids} + + def admissible_a_chain(row): + return ( + set(row["atom_ids"]) <= safe + and (row["edges"][0][0], row["edges"][1][2]) not in b_head_answers + ) + + aa = [row for row in rows if admissible_a_chain(row)] + available_operations = Counter(operation(row) for row in aa) + required_operations = {operation(row) for row in selected_bb} + if any(available_operations[pair] < 2 for pair in required_operations): + raise ValueError("A target operation lacks A-only training and evaluation examples") + # Reserve held-out AA chains and real training witnesses for both old roles. + # BA/AB likewise require the old constituent to have prior use in that role. + by_first, by_second = defaultdict(list), defaultdict(list) + for row in aa: + by_first[row["atom_ids"][0]].append(row) + by_second[row["atom_ids"][1]].append(row) + chosen_train, train_keys, heldout_keys = [], set(), set() + pools = {"AA": [], "BA": [], "AB": [], "BB": selected_bb} + + def choose_witness(options, forbidden): + options = [row for row in options if chain_key(row) not in forbidden] + if not options: + return None + existing = [row for row in options if chain_key(row) in train_keys] + return min(existing or options, key=lambda row: order(row["id"], settings.split + ":role:")) + + def add_training(row): + key = chain_key(row) + if key not in train_keys: + chosen_train.append(row) + train_keys.add(key) + + heldout_operations = Counter() + for row in balanced_order(aa, settings.split + ":eval:AA"): + key = chain_key(row) + if ( + key in train_keys + or heldout_operations[operation(row)] >= available_operations[operation(row)] - 2 + ): + continue + forbidden = heldout_keys | {key} + first = choose_witness(by_first[row["atom_ids"][0]], forbidden) + second = choose_witness(by_second[row["atom_ids"][1]], forbidden) + if first is None or second is None: + continue + pools["AA"].append(row) + heldout_keys.add(key) + heldout_operations[operation(row)] += 1 + add_training(first) + add_training(second) + if len(pools["AA"]) == settings.evaluation_count: + break + for role in ["BA", "AB"]: + candidates = [ + row + for row in rows + if set(row["atom_ids"]) <= safe | b_ids + and "".join("B" if key in b_ids else "A" for key in row["atom_ids"]) == role + and operation(row) in available_operations + ] + for row in balanced_order(candidates, settings.split + ":eval:" + role): + old_index = 1 if role == "BA" else 0 + index = by_second if old_index else by_first + witness = choose_witness(index[row["atom_ids"][old_index]], heldout_keys) + if witness is None: + continue + pools[role].append(row) + add_training(witness) + if len(pools[role]) == settings.evaluation_count: + break + for role in ["AA", "BA", "AB"]: + if len(pools[role]) < min(8, settings.evaluation_count): + raise ValueError(f"Insufficient role-experienced {role}: {len(pools[role])}") + required_operations |= {operation(row) for pool in pools.values() for row in pool} + operation_support = Counter(operation(row) for row in chosen_train) + for row in balanced_order(aa, settings.split + ":operation-support:"): + pair = operation(row) + target = min(8, max(1, available_operations[pair] // 2)) + if ( + pair in required_operations + and operation_support[pair] < target + and chain_key(row) not in heldout_keys + ): + before = len(chosen_train) + add_training(row) + operation_support[pair] += len(chosen_train) - before + if len(chosen_train) > settings.train_count: + raise ValueError( + f"Training size below required role/operation support: {len(chosen_train)}" + ) + target_entities = {entity for row in selected_bb for entity in entities(row)} + relevant_aa = [row for row in aa if entities(row) & target_entities] + for pool in [relevant_aa, aa]: + if len(chosen_train) == settings.train_count: + break + for row in balanced_order(pool, settings.split + ":train:"): + if chain_key(row) in train_keys | heldout_keys: + continue + add_training(row) + if len(chosen_train) == settings.train_count: + break + trained_operations = {operation(row) for row in chosen_train} + if not required_operations <= trained_operations: + raise ValueError(f"A training lacks operations: {required_operations - trained_operations}") + + a_ids = witness_ids | { + key + for row in chosen_train + [row for pool in pools.values() for row in pool] + for key in row["atom_ids"] + if key not in b_ids + } + final_atoms = [] + for key in sorted(a_ids | b_ids): + row = copy.deepcopy(atoms[key]) + row["subset"] = "A" if key in a_ids else "B" + final_atoms.append(row) + training = copy.deepcopy(chosen_train) + for row in training: + row["sequential_role"] = row["role"] = "AA" + evaluation = [] + for role, pool in pools.items(): + for original in pool: + row = copy.deepcopy(original) + row["sequential_role"] = row["role"] = role + row["all_entities_seen_in_a"] = entities(row) <= { + entity for key in a_ids for entity in (atoms[key]["edge"][0], atoms[key]["edge"][2]) + } + row["operation_seen"] = operation(row) in trained_operations + evaluation.append(row) + data = { + "schema": "sequential-transfer-v1", + "split": settings.split, + "settings": asdict(settings), + "atoms": final_atoms, + "train_compositions": training, + "evaluation_compositions": evaluation, + "stage_a_atom_ids": sorted(a_ids), + "stage_b_atom_ids": sorted(b_ids), + "entity_witness_atom_ids": sorted(witness_ids), + "panels": { + "atomic_A": sorted(a_ids), + "atomic_B": sorted(b_ids), + "train_composition": [row["id"] for row in training], + **{role: [row["id"] for row in pool] for role, pool in pools.items()}, + }, + "selection_audit": { + "source_unique_eligible_chains": len(rows), + "source_known_entity_bb_candidates": len(candidates), + "selection_uses_model_outputs": False, + "selection_uses_original_official_split": False, + "known_entity_definition": "Each entity occurs in at least one real A atomic fact.", + "facts_are_original_source_edges": True, + "training_and_evaluation_use_original_questions": True, + "semantic_scope": ( + "Reuse prior structural/semantic exclusions; not an exhaustive new human review. " + "Exclude exact B head-answer supervision and explicit spouse/parent inverses. " + "Other possible real-world inferences are not ruled out." + ), + }, + } + data["audit"] = audit_split(data) + return data + + +def audit_split(data): + atoms = {row["id"]: row for row in data["atoms"]} + a_ids, b_ids = set(data["stage_a_atom_ids"]), set(data["stage_b_atom_ids"]) + if a_ids & b_ids or a_ids | b_ids != set(atoms): + raise ValueError("Atomic A/B partition is not disjoint and exhaustive") + a_entities = { + entity for key in a_ids for entity in (atoms[key]["edge"][0], atoms[key]["edge"][2]) + } + trains = data["train_compositions"] + evaluations = data["evaluation_compositions"] + train_keys = {chain_key(row) for row in trains} + if train_keys & {chain_key(row) for row in evaluations}: + raise ValueError("A held-out semantic chain appears in composition training") + if not all(set(row["atom_ids"]) <= a_ids for row in trains): + raise ValueError("B fact leaked through A composition training") + if not a_ids <= safe_atom_ids(atoms, b_ids): + raise ValueError("An equivalent or explicit inverse B fact leaked into A") + b_answers = {(atoms[key]["edge"][0], atoms[key]["edge"][2]) for key in b_ids} + if any((row["edges"][0][0], row["edges"][1][2]) in b_answers for row in trains): + raise ValueError("A composition label directly teaches a B head-answer pair") + train_operations = {operation(row) for row in trains} + trained_first = {row["atom_ids"][0] for row in trains} + trained_second = {row["atom_ids"][1] for row in trains} + for row in trains + evaluations: + if not set(row["atom_ids"]) <= set(atoms): + raise ValueError("Missing required atomic knowledge") + if [atoms[key]["edge"] for key in row["atom_ids"]] != row["edges"]: + raise ValueError("Atom IDs disagree with the real evidence chain") + for row in evaluations: + role = "".join("A" if key in a_ids else "B" for key in row["atom_ids"]) + if role != row["sequential_role"]: + raise ValueError("Incorrect sequential role") + if operation(row) not in train_operations: + raise ValueError("An evaluation operation was not trained on A") + if role[0] == "A" and row["atom_ids"][0] not in trained_first: + raise ValueError("An old first-hop fact lacks prior composition use") + if role[1] == "A" and row["atom_ids"][1] not in trained_second: + raise ValueError("An old second-hop fact lacks prior composition use") + if role == "BB" and not entities(row) <= a_entities: + raise ValueError("BB contains an entity absent from A") + counts = Counter(row["sequential_role"] for row in evaluations) + return { + "passed": True, + "atomic_A": len(a_ids), + "atomic_B": len(b_ids), + "train_compositions": len(trains), + "evaluation_counts": dict(counts), + "bb_all_entities_seen_in_a": all( + entities(row) <= a_entities for row in evaluations if row["sequential_role"] == "BB" + ), + "b_fact_composition_training_overlap": 0, + "heldout_semantic_chain_training_overlap": 0, + "all_evaluation_a_facts_have_prior_role_experience": True, + "relation_pairs": { + role: dict( + Counter( + " -> ".join(operation(row)) + for row in evaluations + if row["sequential_role"] == role + ) + ) + for role in counts + }, + "bb_unique_atomic_facts": len( + { + key + for row in evaluations + if row["sequential_role"] == "BB" + for key in row["atom_ids"] + } + ), + } diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/sequential_transfer.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/sequential_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..865c5a8343f84fdb340f7961bca649b71b1efd76 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/sequential_transfer.py @@ -0,0 +1,629 @@ +"""Sequential acquisition of source-grounded facts in a complete Transformer. + +All histories train from random initialization. The joint history is an exact +permutation of the sequential-composition training-example multiset. Evaluation +questions, including every chain containing a B fact, never enter that stream. +""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch +from transformers import GPT2TokenizerFast + +from .grok_depth import utc +from .realworld_composition import ( + aggregate, + construct, + evaluate, + model_digest, + optimizer_for, + update, +) +from .realworld_composition_data import atomic_question, encode_example, sha256, write_json + +HISTORIES = ( + "sequential_composition", + "sequential_atomic", + "joint", + "sequential_composition_sham", +) + + +def validate_data(data): + """Reject leakage or a missing evaluation role before model allocation.""" + atoms = {row["id"]: row for row in data["atoms"]} + if len(atoms) != len(data["atoms"]): + raise ValueError("Duplicate atomic IDs") + a = {key for key, row in atoms.items() if row["subset"] == "A"} + b = {key for key, row in atoms.items() if row["subset"] == "B"} + if not a or not b or a | b != set(atoms): + raise ValueError("Every atom must belong to a nonempty A or B partition") + for key, expected in (("stage_a_atom_ids", a), ("stage_b_atom_ids", b)): + if key in data and set(data[key]) != expected: + raise ValueError(f"{key} differs from atomic subset fields") + train = data["train_compositions"] + evaluation = data["evaluation_compositions"] + train_ids = {row["id"] for row in train} + evaluation_ids = {row["id"] for row in evaluation} + if not train or train_ids & evaluation_ids: + raise ValueError("Training chains must be nonempty and held-out IDs disjoint") + if len(train_ids) != len(train) or len(evaluation_ids) != len(evaluation): + raise ValueError("Duplicate composition IDs") + if (train_ids | evaluation_ids) & set(atoms): + raise ValueError("Atom and composition IDs must be globally unique") + train_chains = {tuple(row["atom_ids"]) for row in train} + if any(not set(row["atom_ids"]) <= a for row in train): + raise ValueError("A training chain includes a held-out B fact") + roles = set() + for row in evaluation: + if len(row["atom_ids"]) != 2 or not set(row["atom_ids"]) <= set(atoms): + raise ValueError("Every chain needs exactly two known atomic IDs") + role = "".join(atoms[key]["subset"] for key in row["atom_ids"]) + if row.get("sequential_role") != role: + raise ValueError("Evaluation role does not match its constituent facts") + if tuple(row["atom_ids"]) in train_chains: + raise ValueError("Evaluation chain identity occurs in training") + roles.add(role) + if roles != {"AA", "BA", "AB", "BB"}: + raise ValueError("All four fixed evaluation roles must be nonempty") + return atoms + + +def _sample_cycles(ids, count, rng): + """Balanced random epochs, preserving every requested sample slot.""" + ids = np.asarray(ids, dtype=np.int32) + if count < 0 or not len(ids): + raise ValueError("Sampling requires a nonempty pool and nonnegative count") + if not count: + return np.empty(0, dtype=np.int32) + chunks = [rng.permutation(ids) for _ in range(math.ceil(count / len(ids)))] + return np.concatenate(chunks)[:count] + + +def training_plan(data, spec): + """Materialize deterministic example IDs; histories differ only as declared.""" + validate_data(data) + history = spec["history"] + if history not in HISTORIES: + raise ValueError(f"Unknown training history: {history}") + records = data["atoms"] + data["train_compositions"] + index = {row["id"]: i for i, row in enumerate(records)} + a = [index[row["id"]] for row in data["atoms"] if row["subset"] == "A"] + b = [index[row["id"]] for row in data["atoms"] if row["subset"] == "B"] + c = [index[row["id"]] for row in data["train_compositions"]] + batch = int(spec["batch_size"]) + sa, sb = int(spec["stage_a_steps"]), int(spec["stage_b_steps"]) + if batch < 2 or sa < 1 or sb < 1: + raise ValueError("Need batch>=2 and positive budgets in both stages") + rng = np.random.default_rng(spec["sampling_seed"]) + # Exactly half (rounded down) of A slots contain composition examples; + # exactly half of B slots contain genuinely new atomic examples. + ca = int(spec.get("stage_a_composition_per_batch", batch // 2)) + nb = int(spec.get("stage_b_new_per_batch", batch // 2)) + if not (0 < ca < batch and 0 < nb < batch): + raise ValueError("Both stage mixtures need positive constituent counts") + first = np.concatenate( + ( + _sample_cycles(a, sa * (batch - ca), rng).reshape(sa, batch - ca), + _sample_cycles(c, sa * ca, rng).reshape(sa, ca), + ), + axis=1, + ) + second = np.concatenate( + ( + _sample_cycles(a, sb * (batch - nb), rng).reshape(sb, batch - nb), + _sample_cycles(b, sb * nb, rng).reshape(sb, nb), + ), + axis=1, + ) + # Seeded replacement streams are generated for every history, so selecting + # a history cannot affect either the common A exposure or B sampling. + atomic_replacement = _sample_cycles(a, sa * ca, rng).reshape(sa, ca) + sham_replacement = _sample_cycles(a, sb * nb, rng).reshape(sb, nb) + if history == "sequential_atomic": + first[:, batch - ca :] = atomic_replacement + elif history == "sequential_composition_sham": + second[:, batch - nb :] = sham_replacement + plan = np.concatenate((first, second), axis=0) + if history == "joint": + plan = rng.permutation(plan.reshape(-1)).reshape(plan.shape) + return records, plan + + +def plan_manifest(records, plan, spec): + counts = np.bincount(plan.reshape(-1), minlength=len(records)) + return { + "history": spec["history"], + "shape": list(plan.shape), + "plan_sha256": hashlib.sha256(plan.tobytes()).hexdigest(), + "multiset_sha256": hashlib.sha256(counts.tobytes()).hexdigest(), + "examples": int(counts.sum()), + "supervised_tokens": sum( + int(n) * len(row["encoded"]["target"]) for row, n in zip(records, counts, strict=True) + ), + "input_tokens": sum( + int(n) * len(row["encoded"]["input"]) for row, n in zip(records, counts, strict=True) + ), + "counts": {row["id"]: int(n) for row, n in zip(records, counts, strict=True)}, + } + + +def learning_rate(spec, step): + """Same staged cosine by global update index for *all* histories.""" + boundary = spec["stage_a_steps"] + length = boundary if step <= boundary else spec["stage_b_steps"] + local = step if step <= boundary else step - boundary + warmup = min(spec.get("warmup_steps", 200), length) + peak = spec["learning_rate"] + if warmup and local <= warmup: + return peak * local / warmup + progress = (local - warmup) / max(1, length - warmup) + floor = spec.get("minimum_lr_fraction", 0.1) + return peak * (floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * progress))) + + +def evaluation_groups(data, full): + atoms = {row["id"]: row for row in data["atoms"]} + chains = {row["id"]: row for row in data["evaluation_compositions"]} + panels = data.get("panels", {}) + selected = ( + list(chains.values()) + if full + else [chains[key] for role in ("AA", "BA", "AB", "BB") for key in panels.get(role, [])] + ) + if not selected: + selected = list(chains.values()) + needed = {key for row in selected for key in row["atom_ids"]} + atom_ids = ( + set(atoms) + if full + else needed | set(panels.get("atomic_A", [])) | set(panels.get("atomic_B", [])) + ) + groups = { + "atomic_A": [row for key, row in atoms.items() if key in atom_ids and row["subset"] == "A"], + "atomic_B": [row for key, row in atoms.items() if key in atom_ids and row["subset"] == "B"], + "train_composition": data["train_compositions"] + if full + else [ + row + for row in data["train_compositions"] + if row["id"] in set(panels.get("train_composition", [])) + ], + } + for role in ("AA", "BA", "AB", "BB"): + groups[role] = [row for row in selected if row["sequential_role"] == role] + return groups + + +def evaluate_transfer(model, data, tokenizer, device, *, full=False, autonomous=False, batch=32): + groups = evaluation_groups(data, full) + metrics, predictions = {}, {} + for name, records in groups.items(): + metrics[name], predictions[name] = ( + evaluate(model, records, tokenizer, device, batch_size=batch) + if records + else (aggregate([]), []) + ) + lookup = {row["id"]: row for name in ("atomic_A", "atomic_B") for row in predictions[name]} + for role in ("AA", "BA", "AB", "BB"): + selected = groups[role] + correct = { + row["id"] for row in selected if all(lookup[key]["alias_em"] for key in row["atom_ids"]) + } + key = role + "_necessary_atoms_correct" + metrics[key] = aggregate([row for row in predictions[role] if row["id"] in correct]) + metrics[key]["coverage"] = len(correct) / len(selected) if selected else None + if not autonomous: + continue + calls, invalid = [], [] + for row in selected: + bridge = lookup[row["atom_ids"][0]]["prediction"] + question = atomic_question(bridge, row["edges"][1][1]) + try: + encoded = encode_example(tokenizer, question, row["answer"]) + except ValueError: + invalid.append(row) + continue + calls.append({**row, "encoded": encoded, "question": question, "bridge": bridge}) + _, raw = evaluate(model, calls, tokenizer, device, batch_size=batch) if calls else ({}, []) + for row, value in zip(calls, raw, strict=True): + value.update(bridge_prediction=row["bridge"], second_question=row["question"]) + raw.extend( + { + "id": row["id"], + "canonical_em": 0.0, + "alias_em": 0.0, + "unambiguous_alias_em": 0.0, + "f1": 0.0, + "nll": None, + "eos": False, + "truncated": True, + "invalid_generated_bridge_length": True, + } + for row in invalid + ) + predictions[role + "_autonomous"] = raw + metrics[role + "_autonomous"] = aggregate(raw) + metrics[role + "_autonomous"]["invalid_bridge_prompts"] = len(invalid) + return metrics, predictions + + +def _setup(spec, device): + torch.set_num_threads(spec.get("cpu_threads", 4)) + device = torch.device(device) + if device.type == "cuda": + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + data_path = Path(spec["data_file"]) + if sha256(data_path) != spec["data_sha256"]: + raise ValueError("Dataset hash differs from frozen spec") + data = json.loads(data_path.read_text()) + validate_data(data) + tokenizer = GPT2TokenizerFast.from_pretrained(spec["tokenizer"], local_files_only=True) + if len(tokenizer) != spec["model"]["vocab_size"]: + raise ValueError("Tokenizer vocabulary and model vocabulary differ") + model = construct(spec["model"], spec, device) + return data, tokenizer, model, device + + +def _sync(device): + if torch.device(device).type == "cuda": + torch.cuda.synchronize(device) + + +def save_checkpoint(path, model, optimizer, step, counts, counters, history, manifest): + path = Path(path) + temporary = path.with_suffix(".tmp") + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "counts": counts, + "counters": counters, + "history": history, + "plan_sha256": manifest["plan_sha256"], + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state() if next(model.parameters()).is_cuda else None, + }, + temporary, + ) + temporary.replace(path) + + +def restore_checkpoint(path, model, optimizer, manifest): + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + if checkpoint["plan_sha256"] != manifest["plan_sha256"]: + raise ValueError("Resume would change the frozen sampling plan") + model.load_state_dict(checkpoint["model"]) + optimizer.load_state_dict(checkpoint["optimizer"]) + torch.set_rng_state(checkpoint["cpu_rng"]) + if checkpoint["cuda_rng"] is not None: + torch.cuda.set_rng_state(checkpoint["cuda_rng"]) + return checkpoint + + +def run(spec, out, device): + """Train one frozen history; an independent audit finalizes completion.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + if json.loads((out / "run.json").read_text())["spec"] != spec: + raise ValueError("Completed run has a different experiment spec") + return json.loads((out / "complete.json").read_text()) + data, tokenizer, model, device = _setup(spec, device) + records, plan = training_plan(data, spec) + manifest = plan_manifest(records, plan, spec) + optimizer = optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + counts = np.zeros(len(records), dtype=np.int64) + counters = { + key: 0 + for key in ( + "examples", + "supervised_tokens", + "effective_input_tokens", + "executed_input_tokens", + "estimated_matmul_training_flops", + ) + } + counters.update(training_seconds=0.0, wall_seconds=0.0) + history, initial_step = [], 0 + if (out / "latest.pt").exists(): + previous = json.loads((out / "run.json").read_text()) + if previous["spec"] != spec: + raise ValueError("Refusing to resume under a changed experiment spec") + state = restore_checkpoint(out / "latest.pt", model, optimizer, manifest) + initial_step, counts, counters, history = ( + state["step"], + state["counts"], + state["counters"], + state["history"], + ) + metadata = {**previous, "pid": os.getpid(), "resumed_from_step": initial_step} + del state + else: + torch.manual_seed(spec.get("dropout_seed", spec["initialization"] + 1)) + metadata = { + "spec": spec, + "phase": spec.get("phase", "development"), + "model": spec["model"], + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else "cpu", + "initial_model_sha256": model_digest(model), + "parameters": sum(p.numel() for p in model.parameters()), + "world_sha256": spec["data_sha256"], + "dtype": "BF16 AMP; FP32 parameters/Adam", + "job_type": "sequential-transfer", + "tracking_group": spec.get("tracking_group"), + "created_utc": utc(), + "sampling_manifest": {key: value for key, value in manifest.items() if key != "counts"}, + } + write_json(out / "sampling-plan.json", manifest) + write_json(out / "run.json", metadata) + write_json(out / "learning.json", history) + nodes = set(spec.get("evaluation_nodes", [])) | {0, spec["stage_a_steps"], len(plan)} + wall_offset, started = counters["wall_seconds"], time.perf_counter() + loss = history[-1].get("loss") if history else None + latest_step = initial_step + for step in range(initial_step, len(plan) + 1): + if step > initial_step: + lr = learning_rate(spec, step) + for group in optimizer.param_groups: + group["lr"] = lr + ids = plan[step - 1] + selected = [records[i] for i in ids] + _sync(device) + began = time.perf_counter() + result = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id) + _sync(device) + counters["training_seconds"] += time.perf_counter() - began + loss = result["loss"] + np.add.at(counts, ids, 1) + counters["examples"] += len(ids) + counters["supervised_tokens"] += sum(len(row["encoded"]["target"]) for row in selected) + for key in ( + "effective_input_tokens", + "executed_input_tokens", + "estimated_matmul_training_flops", + ): + counters[key] += result[key] + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + if step % spec.get("status_interval", 50) == 0: + write_json( + out / "status.json", + { + "state": "training", + "step": step, + "target_step": len(plan), + "loss": loss, + "pid": os.getpid(), + **counters, + "updated_utc": utc(), + }, + ) + if step in nodes and not any(row["step"] == step for row in history): + endpoint = step in {spec["stage_a_steps"], len(plan)} + metrics, raw = evaluate_transfer( + model, + data, + tokenizer, + device, + full=endpoint, + autonomous=endpoint, + batch=spec.get("evaluation_batch_size", 32), + ) + write_json(out / f"predictions-{step:07d}.json", raw) + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + exposure = {} + for name, subset in (("A", "A"), ("B", "B"), ("composition", None)): + indices = [ + i + for i, row in enumerate(records) + if (row.get("subset") == subset if subset else i >= len(data["atoms"])) + ] + exposure[name] = float(counts[indices].mean()) if indices else 0.0 + history.append( + { + "step": step, + "stage": "A" if step <= spec["stage_a_steps"] else "B", + "condition": spec["history"], + "metrics": metrics, + "loss": loss, + "learning_rate": learning_rate(spec, max(step, 1)), + "exposures": exposure, + "atomic_A_epochs": exposure["A"], + "atomic_B_epochs": exposure["B"], + "atomic_epochs": float(counts[: len(data["atoms"])].mean()), + "composition_epochs": exposure["composition"], + **counters, + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "created_utc": utc(), + } + ) + write_json(out / "learning.json", history) + if step == spec["stage_a_steps"]: + save_checkpoint( + out / "stage-a.pt", model, optimizer, step, counts, counters, history, manifest + ) + save_checkpoint( + out / "latest.pt", model, optimizer, step, counts, counters, history, manifest + ) + latest_step = step + print(json.dumps({"step": step, "loss": loss, "metrics": metrics}), flush=True) + elif step > initial_step and step % spec.get("checkpoint_interval", 500) == 0: + save_checkpoint( + out / "latest.pt", model, optimizer, step, counts, counters, history, manifest + ) + latest_step = step + if latest_step != len(plan): + save_checkpoint( + out / "latest.pt", model, optimizer, len(plan), counts, counters, history, manifest + ) + final = next(row for row in history if row["step"] == len(plan)) + write_json(out / "endpoint.json", final["metrics"]) + result = { + "state": "trained_pending_independent_reload", + "step": len(plan), + "pid": os.getpid(), + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + "plan_sha256": manifest["plan_sha256"], + **counters, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + return result + + +def audit(out, device): + """Reload in a separate process and reproduce the full generated endpoint.""" + out = Path(out) + metadata = json.loads((out / "run.json").read_text()) + trained = json.loads((out / "trained.json").read_text()) + if trained["pid"] == os.getpid(): + raise ValueError("Endpoint audit requires a different process") + if sha256(out / "latest.pt") != trained["checkpoint_sha256"]: + raise ValueError("Checkpoint differs from recorded endpoint") + spec = metadata["spec"] + data, tokenizer, model, device = _setup(spec, device) + state = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + if state["step"] != trained["step"] or model_digest(model) != trained["model_sha256"]: + raise ValueError("Loaded model or update count differs") + records, plan = training_plan(data, spec) + manifest = plan_manifest(records, plan, spec) + if manifest["plan_sha256"] != trained["plan_sha256"]: + raise ValueError("Sampling plan changed") + expected_counts = np.bincount(plan.reshape(-1), minlength=len(records)) + if not np.array_equal(state["counts"], expected_counts): + raise ValueError("Observed example exposures differ from frozen plan") + metrics, raw = evaluate_transfer( + model, + data, + tokenizer, + device, + full=True, + autonomous=True, + batch=spec.get("evaluation_batch_size", 32), + ) + expected_raw = json.loads((out / f"predictions-{trained['step']:07d}.json").read_text()) + if raw != expected_raw or metrics != json.loads((out / "endpoint.json").read_text()): + raise AssertionError("Independent endpoint generations/scores failed exact reproduction") + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "model_sha256": trained["model_sha256"], + "checkpoint_sha256": trained["checkpoint_sha256"], + "predictions_recomputed": sum(map(len, raw.values())), + "exposures_exact": True, + "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": trained["step"], "independently_reloaded": True}, + ) + return result + + +def preflight(spec, out, device): + """Actual updates, fresh-model reload and exact optimizer/RNG continuation.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + data, tokenizer, model, device = _setup(spec, device) + records, plan = training_plan(data, spec) + optimizer = optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + times, losses = [], [] + for ids in plan[:8]: + _sync(device) + started = time.perf_counter() + result = update( + model, optimizer, [records[i] for i in ids], spec, device, tokenizer.eos_token_id + ) + _sync(device) + times.append(time.perf_counter() - started) + losses.append(result["loss"]) + saved_model = copy.deepcopy(model.state_dict()) + saved_optimizer = copy.deepcopy(optimizer.state_dict()) + cpu_rng = torch.get_rng_state() + gpu_rng = torch.cuda.get_rng_state() if device.type == "cuda" else None + # The next update uses the exact same record order, Adam moments and RNG. + next_records = [records[i] for i in plan[min(8, len(plan) - 1)]] + update(model, optimizer, next_records, spec, device, tokenizer.eos_token_id) + expected = model_digest(model) + restored = construct(spec["model"], spec, device) + restored.load_state_dict(saved_model) + restored_optimizer = optimizer_for(restored, spec["learning_rate"], spec["weight_decay"]) + restored_optimizer.load_state_dict(saved_optimizer) + torch.set_rng_state(cpu_rng) + if gpu_rng is not None: + torch.cuda.set_rng_state(gpu_rng) + update(restored, restored_optimizer, next_records, spec, device, tokenizer.eos_token_id) + if model_digest(restored) != expected: + raise AssertionError("Preflight optimizer/RNG continuation failed exact reproduction") + generation_metrics, predictions = evaluate( + restored, next_records[:4], tokenizer, device, batch_size=4 + ) + result = { + "passed": True, + "updates": len(times), + "continuation_check_updates": 2, + "optimizer_rng_restore_exact": True, + "generated_predictions": predictions, + "generation_metrics": generation_metrics, + "losses": losses, + "seconds_per_update_after_warmup": sum(times[2:]) / max(1, len(times) - 2), + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "parameters": sum(p.numel() for p in model.parameters()), + "created_utc": utc(), + } + write_json(out / "preflight.json", result) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path) + parser.add_argument("--run") + parser.add_argument("--out", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--audit", action="store_true") + parser.add_argument("--preflight", action="store_true") + args = parser.parse_args() + if args.audit: + if not args.out: + parser.error("--audit requires --out") + result = audit(args.out, args.device) + else: + if not args.config or not args.run: + parser.error("Training/preflight requires --config and --run") + config = json.loads(args.config.read_text()) + selected = next(row for row in config["runs"] if row["name"] == args.run) + spec = {**config.get("defaults", {}), **selected} + out = args.out or Path(config["results_root"]) / "runs" / args.run + result = (preflight if args.preflight else run)(spec, out, args.device) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/shared_cache.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/shared_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf5aec02ab0270e60a6c41882c24bdd4b3d34cc --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/shared_cache.py @@ -0,0 +1,133 @@ +"""First-recursion KV access in the historical closed-book LoopGPT backbone. + +Only attention access changes. Each layer retains its own first-pass K/V; +embeddings, normalization, residuals, MLPs and supervision are unchanged. +""" + +from __future__ import annotations + +from numbers import Integral + +import torch +from torch.nn import functional as F + +from .grok_loop_model import LoopGPT, _positive_integer +from .grok_loop_model import flops as ordinary_flops +from .latent_scaling import construct as ordinary_construct + +ARMS = ("local", "shared_full", "shared_window", "shared_detached") + + +class SharedCacheGPT(LoopGPT): + def __init__(self, config, repeats, dropout=0.0, arm="shared_full", window=2): + if arm not in ARMS: + raise ValueError(f"Unknown memory arm: {arm}") + if isinstance(window, bool) or not isinstance(window, Integral) or window < 0: + raise ValueError("window counts nonnegative preceding local positions") + super().__init__(config, repeats, dropout, "legacy_unique") + self.memory_arm, self.window = arm, int(window) + self.disable_shared = False + self.duplicate_current = False # engineering identity control only + positions = torch.arange(config.context) + causal = positions[None, :] <= positions[:, None] + local = causal & (positions[None, :] >= positions[:, None] - self.window) + self.register_buffer("shared_causal_mask", causal, persistent=False) + self.register_buffer("local_window_mask", local, persistent=False) + + def forward(self, tokens, positions=None, repeats=None): + count = self.repeats if repeats is None else _positive_integer(repeats, "repeats") + if self.memory_arm == "local" or count == 1: + return super().forward(tokens, positions, count) + length = tokens.shape[1] + if length > self.config.context: + raise ValueError("Input exceeds mask context") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(length, device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + causal = self.shared_causal_mask[:length, :length] + local_mask = ( + self.local_window_mask[:length, :length] + if self.memory_arm == "shared_window" + else causal + ) + joined_mask = torch.cat((causal, local_mask), dim=-1) + shared = [] + for recursion in range(count): + for layer, block in enumerate(self.blocks): + z = block.ln1(x) + batch, size, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, size, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + q, k, v = (t.transpose(1, 2) for t in (q, k, v)) + if recursion == 0: + shared.append((k, v)) + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=p) + elif self.disable_shared: + y = F.scaled_dot_product_attention(q, k, v, attn_mask=local_mask, dropout_p=p) + else: + first_k, first_v = (k, v) if self.duplicate_current else shared[layer] + if self.memory_arm == "shared_detached": + first_k, first_v = first_k.detach(), first_v.detach() + y = F.scaled_dot_product_attention( + q, + torch.cat((first_k, k), dim=-2), + torch.cat((first_v, v), dim=-2), + attn_mask=joined_mask, + dropout_p=p, + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, size, 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 construct(spec, device): + if "memory_arm" not in spec: + return ordinary_construct(spec, device) + reference = ordinary_construct(spec, "cpu") + torch.manual_seed(spec["initialization"]) + return SharedCacheGPT( + reference.config, spec["repeats"], spec["dropout"], spec["memory_arm"], spec["window"] + ).to(device) + + +def executed_flops(config, repeats, batch, sequence, arm, output_positions=9, backward=True): + """Executed dense matmul shapes, including masked work; excludes elementwise ops. + + Concatenated attention has twice the key dimension, even for a small window. + The ordinary estimate counts QK and AV over a square sequence, not only the + visible causal entries. Backward follows the historical 3-forward convention. + Detachment changes true backward work; this common estimate is approximate. + """ + base = ordinary_flops(config, repeats, batch, sequence, output_positions, backward) + if arm == "local": + return base + extra = 4 * batch * config.layers * (repeats - 1) * sequence**2 * config.width + return base + extra * (3 if backward else 1) + + +def cached_positions(layers, repeats, length, arm, window): + """Analytic decoding history slots, not measured training allocation.""" + if arm in {"local", "shared_full", "shared_detached"}: + return layers * repeats * length + return layers * (length + (repeats - 1) * min(window, length)) + + +def install_training_adapter(spec): + """Reuse the unchanged historical sampler, optimizer, scorer and audit.""" + from . import latent_scaling as latent + + latent.construct = construct + latent.flops = lambda config, repeats, batch, sequence, output_positions=9, backward=True: ( + executed_flops( + config, repeats, batch, sequence, spec["memory_arm"], output_positions, backward + ) + ) + return latent diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/small_lm_composition.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/small_lm_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..f7bc9b1ea8e7d825eb5f27c33bb4d7e38bb7bcc1 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/small_lm_composition.py @@ -0,0 +1,543 @@ +"""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 hashlib +import json +import math +import re +import shutil +import time +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +import transformers +from 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) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/small_lm_followup.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/small_lm_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..4c986ea475b4f0abe83ea3d0411a049344ac0e08 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/small_lm_followup.py @@ -0,0 +1,558 @@ +"""Small full-Qwen development: matched rehearsal, pairing, and factual updates.""" + +from __future__ import annotations + +import copy +import itertools +import json +import math +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import transformers +from 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) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/storage_composition.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/storage_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..094211c26edecbed2a534bad16c84c42b2cdebd0 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/storage_composition.py @@ -0,0 +1,424 @@ +"""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, and +all non-padding next tokens contribute to the training loss. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .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 result diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/storage_frontier.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/storage_frontier.py new file mode 100644 index 0000000000000000000000000000000000000000..db36e560aed8b173bb72c836b3d02dc8381bbcc5 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/storage_frontier.py @@ -0,0 +1,262 @@ +"""Stable training and nested fact loads in ordinary GPT/Loop architectures. + +The historical storage_composition implementation is reused without changing its +frozen sources, truth, tokenizer, architecture or full-generation score. +""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .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 result diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/text_loss_source.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/text_loss_source.py new file mode 100644 index 0000000000000000000000000000000000000000..6f9377848d4673a2937273cf26a33f8e859874d0 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/text_loss_source.py @@ -0,0 +1,256 @@ +"""Factorial loss-source interventions on an unchanged text-pretraining stream.""" + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, write_json +from .grok_loop_model import flops +from .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"), + ), + ) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/text_pretrain.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/text_pretrain.py new file mode 100644 index 0000000000000000000000000000000000000000..2682a0925a00e0e8b0eef3781521830d891ef9d7 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/text_pretrain.py @@ -0,0 +1,401 @@ +"""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 in +supervision. This is controlled template-language pretraining, not a pretrained +natural-language model or a replication of the original bioS scale. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, GraphStep, make_optimizer, write_json +from .grok_loop_model import LoopGPT, flops + +WORDS = [ + "", + "", + "", + "'s", + "is", + ".", + "This", + "record", + "has", + "no", + "additional", + "fact", + "here", + "mentor", + "advisor", + "coach", + "supervisor", + "city", + "district", + "region", + "campus", +] +LENGTH = 26 +PAD, EOS, BOS = 0, 1, 2 + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def vocabulary(spec): + return ( + WORDS + + [f"Person{i:03d}" for i in range(spec["heads_n"])] + + [f"Expert{i:03d}" for i in range(spec["bridges_n"])] + + [f"Place{i:03d}" for i in range(spec["tails_n"])] + ) + + +def atomic_sentence(row): + h, r, t = map(int, row) + return [BOS, h, 3, r, 4, t, 5, EOS] + + +def composite_sentence(row): + h, r1, _b, r2, t = map(int, row) + return [BOS, h, 3, r1, 3, r2, 4, t, 5, EOS] + + +def pack_documents(documents, groups): + """Reset positions per record in every arm; BOS is an exogenous boundary. + + All remaining next-token targets, including names, relations and EOS, are + supervised. The next record's BOS and padding are never prediction targets. + """ + seq, positions, segments = [], [], [] + for doc, group in zip(documents, groups, strict=True): + seq.extend(doc) + positions.extend(range(len(doc))) + segments.extend([group] * len(doc)) + if len(seq) > LENGTH: + raise ValueError("Record exceeds fixed context") + n = len(seq) + seq += [PAD] * (LENGTH - n) + positions += [0] * (LENGTH - n) + segments += list(range(100, 100 + LENGTH - n)) + labels = np.asarray(seq[1:], dtype=np.int64) + labels[(labels == BOS) | (labels == PAD)] = -100 + seg = np.asarray(segments[:-1]) + mask = (seg[:, None] == seg[None, :]) & np.tri(LENGTH - 1, dtype=bool) + return ( + np.asarray(seq[:-1], dtype=np.int64), + np.asarray(positions[:-1], dtype=np.int64), + mask[None], + labels, + ) + + +def build_world(spec): + """One supplied world; complete head-tail pairs held out before rendering.""" + rng = np.random.default_rng(spec["world"]) + hn, bn, tn = spec["heads_n"], spec["bridges_n"], spec["tails_n"] + hs = np.arange(len(WORDS), len(WORDS) + hn) + bs = np.arange(hs[-1] + 1, hs[-1] + 1 + bn) + ts = np.arange(bs[-1] + 1, bs[-1] + 1 + tn) + first = np.array([(h, r, rng.choice(bs)) for h in hs for r in range(13, 17)]) + second = np.array([(b, r, rng.choice(ts)) for b in bs for r in range(17, 21)]) + lookup = {(int(h), int(r)): int(t) for h, r, t in second} + paths = np.array( + [(h, r1, b, r2, lookup[int(b), r2]) for h, r1, b in first for r2 in range(17, 21)], + dtype=np.int64, + ) + reserved = rng.random((hn, tn)) < spec["holdout_fraction"] + held = reserved[paths[:, 0] - hs[0], paths[:, 4] - ts[0]] + background = paths[:, 0] < hs[0] + hn // 2 + groups = { + "atomic_first": first, + "atomic_second": second, + "background_train": paths[background & ~held], + "background_test": paths[background & held], + "target_train": paths[~background & ~held], + "target_test": paths[~background & held], + } + for key, rows in groups.items(): + if not len(rows): + raise ValueError(f"Empty world stratum {key}; do not silently reroll") + train_pairs = {tuple(r[[0, 4]]) for r in paths[~held]} + test_pairs = {tuple(r[[0, 4]]) for r in paths[held]} + assert not train_pairs & test_pairs + # Typed atomics can never expose a head and a tail together. + assert not set(first[:, 0]) & set(second[:, 0]) + assert not set(first[:, 2]) & set(second[:, 2]) + groups["atomic"] = np.concatenate([first, second]) + groups["all_paths"] = paths + return groups + + +def training_table(world, arm): + if arm not in ("P0", "P1", "P2"): + raise ValueError(arm) + packed = [pack_documents([atomic_sentence(r)], [0]) for r in world["atomic"]] + base_end = len(packed) + packed.extend(pack_documents([composite_sentence(r)], [0]) for r in world["background_train"]) + background_end = len(packed) + neutral = [BOS, 6, 7, 8, 9, 10, 11, 12, 5, EOS] + for row in world["target_train"]: + h, r1, b, r2, t = row + third = composite_sentence(row) if arm == "P2" else neutral + packed.append( + pack_documents( + [atomic_sentence([h, r1, b]), atomic_sentence([b, r2, t]), third], + [0, 1, 2] if arm == "P0" else [0, 0, 2], + ) + ) + table = tuple(np.stack([row[i] for row in packed]) for i in range(4)) + return table, [0, base_end, background_end, len(packed)] + + +class TextGPT(LoopGPT): + def forward(self, tokens, position_ids=None, attention_mask=None, patch=None, cache=None): + if position_ids is None: + position_ids = torch.arange(tokens.shape[1], device=tokens.device)[None] + p = self.dropout if self.training else 0.0 + x = F.dropout(self.token(tokens) + self.position(position_ids), p=p, training=self.training) + for layer, block in enumerate(self.iter_blocks()): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=attention_mask, + is_causal=attention_mask is None, + dropout_p=p, + ) + attn = F.dropout( + a.proj(y.transpose(1, 2).reshape(batch, length, width)), p=p, training=self.training + ) + mlp = F.dropout(block.mlp(block.ln2(x + attn)), p=p, training=self.training) + if cache is not None: + cache[layer] = { + "attention": attn.detach(), + "mlp": mlp.detach(), + "full": (x + attn + mlp).detach(), + } + if patch is not None and layer == patch["layer"]: + pos, value, component = patch["position"], patch["value"], patch["component"] + if component == "full": + x = x + attn + mlp + x = x.clone() + x[:, pos] = value + continue + if component == "attention": + attn = attn.clone() + attn[:, pos] = value + elif component == "mlp": + mlp = mlp.clone() + mlp[:, pos] = value + else: + raise ValueError(component) + x = x + attn + mlp + return F.linear(self.ln_final(x), self.token.weight) + + +class TextGraphStep(GraphStep): + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, positions, mask, labels = (t[self.index] for t in self.table) + logits = self.model(x, position_ids=positions, attention_mask=mask) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def construct(spec, device): + torch.manual_seed(spec["initialization"]) + cfg = ModelConfig( + vocab_size=len(vocabulary(spec)), + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=LENGTH, + ) + return TextGPT(cfg, repeats=spec["repeats"], dropout=spec["dropout"]).to(device) + + +@torch.inference_mode() +def evaluate(model, rows, device, composite=False, patch=None, batch_size=256): + model.eval() + encode = composite_sentence if composite else atomic_sentence + prompts = np.asarray([encode(r)[:-3] for r in rows], dtype=np.int64) + answers, stops, probs = [], [], [] + for start in range(0, len(rows), batch_size): + x = torch.as_tensor(prompts[start : start + batch_size], device=device) + intervention = ( + None if patch is None else dict(patch, value=patch["value"][start : start + batch_size]) + ) + logits = model(x, patch=intervention)[:, -1] + target = torch.as_tensor(rows[start : start + batch_size, -1], device=device) + probs.extend(logits.softmax(-1).gather(1, target[:, None]).squeeze(1).tolist()) + prediction = logits.argmax(-1) + answers.extend(prediction.tolist()) + x = torch.cat([x, prediction[:, None]], dim=1) + period = model(x, patch=intervention)[:, -1].argmax(-1) + x = torch.cat([x, period[:, None]], dim=1) + eos = model(x, patch=intervention)[:, -1].argmax(-1) + stops.extend(torch.stack([period, eos], dim=1).tolist()) + ans, stop, probability = np.asarray(answers), np.asarray(stops), np.asarray(probs) + correct = ans == rows[:, -1] + full = correct & (stop[:, 0] == 5) & (stop[:, 1] == EOS) + return dict( + n=len(rows), + answer_accuracy=float(correct.mean()), + accuracy=float(full.mean()), + answer_probability=float(probability.mean()), + ), dict(answer=ans, stops=stop, probability=probability, target=rows[:, -1]) + + +def run(spec, output, device): + output = Path(output) + if (output / "complete.json").exists(): + return json.loads((output / "complete.json").read_text()) + output.mkdir(parents=True, exist_ok=True) + lock = json.loads(Path(spec["source_lock"]).read_text()) + for file, expected in lock["sources"].items(): + assert sha(file) == expected, file + assert lock["config_sha256"] == sha(spec["config_path"]) + torch.set_num_threads(2) + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_per_process_memory_fraction(0.08, device) + world = build_world(spec) + cpu_table, bounds = training_table(world, spec["arm"]) + np.savez_compressed(output / "world.npz", **world) + np.savez_compressed( + output / "training-table.npz", + **{k: v for k, v in zip(("tokens", "positions", "mask", "labels"), cpu_table, strict=True)}, + ) + write_json(output / "spec.json", spec) + write_json(output / "vocabulary.json", vocabulary(spec)) + model = construct(spec, device) + opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"]) + table = tuple(torch.as_tensor(t, device=device) for t in cpu_table) + streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(3)] + latest = output / "latest.pt" + start, elapsed, histories = 0, 0.0, [] + if latest.exists(): + state = torch.load(latest, map_location=device, weights_only=False) + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + for stream, saved in zip(streams, state["streams"], strict=True): + stream.load_state_dict(saved) + start, elapsed, histories = state["step"], state["seconds"], state["histories"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + counts = spec["batch_parts"] + supervised_per_step = sum(n * tokens for n, tokens in zip(counts, [7, 9, 23], strict=True)) + step_flops = flops( + model.config, spec["repeats"], sum(counts), LENGTH - 1, output_positions=LENGTH - 1 + ) + + def checkpoint(step, seconds): + metrics, predictions = {}, {} + for split in ( + "atomic", + "background_train", + "background_test", + "target_train", + "target_test", + ): + metrics[split], preds = evaluate( + model, world[split], device, composite=split != "atomic" + ) + predictions.update({split + "_" + k: v for k, v in preds.items()}) + atomic_ok = predictions["atomic_answer"] == world["atomic"][:, -1] + knowledge = { + (int(h), int(r)): bool(ok) + for (h, r, _t), ok in zip(world["atomic"], atomic_ok, strict=True) + } + eligible = np.array( + [ + knowledge[int(h), int(r1)] and knowledge[int(b), int(r2)] + for h, r1, b, r2, _t in world["target_test"] + ] + ) + target_ok = predictions["target_test_answer"] == world["target_test"][:, -1] + metrics["target_atomic_correct"] = dict( + n=int(eligible.sum()), + coverage=float(eligible.mean()), + answer_accuracy=float(target_ok[eligible].mean()) if eligible.any() else None, + ) + record = dict( + step=step, + seconds=seconds, + supervised_tokens=step * supervised_per_step, + estimated_flops=step * step_flops, + metrics=metrics, + ) + histories.append(record) + np.savez_compressed(output / f"predictions-{step:06d}.npz", **predictions) + write_json(output / "learning.json", histories) + model.train() + state = dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + step=step, + seconds=seconds, + histories=histories, + spec=spec, + streams=[s.state_dict() for s in streams], + cpu_rng=torch.get_rng_state(), + cuda_rng=torch.cuda.get_rng_state(device), + ) + tmp = output / "latest.tmp" + torch.save(state, tmp) + tmp.replace(latest) + if step in spec["weight_nodes"]: + torch.save( + dict(model=state["model"], step=step, spec=spec), output / f"weights-{step:06d}.pt" + ) + print(json.dumps(dict(run=output.name, **record)), flush=True) + + if start == 0: + checkpoint(0, elapsed) + model.train() + graph = TextGraphStep(model, opt, table, sum(counts)) + tick = time.monotonic() + for step in range(start + 1, spec["steps"] + 1): + idx = np.concatenate( + [ + stream.take(n) + offset + for stream, n, offset in zip(streams, counts, bounds[:-1], strict=True) + ] + ) + for group in opt.param_groups: + group["lr"].fill_(spec["lr"] * min(1.0, step / spec["warmup"])) + graph(torch.as_tensor(idx, device=device)) + if step in spec["nodes"]: + torch.cuda.synchronize() + elapsed += time.monotonic() - tick + checkpoint(step, elapsed) + tick = time.monotonic() + result = dict( + status="complete", + final=histories[-1], + parameters=sum(p.numel() for p in model.parameters()), + source_lock_sha256=sha(spec["source_lock"]), + world_sha256=sha(output / "world.npz"), + peak_memory_bytes=torch.cuda.max_memory_allocated(device), + ) + write_json(output / "complete.json", result) + return result diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/text_structure.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/text_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c74f97848144e288267dedd2df039a1f8c1a52 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/text_structure.py @@ -0,0 +1,432 @@ +"""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 and +bridges are disjoint from background; answer values are deliberately shared. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .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 result diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/twohop_depth.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/twohop_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..19b9a4b76eadef68acf7603b8434567145244311 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/twohop_depth.py @@ -0,0 +1,362 @@ +"""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 contextlib +import hashlib +import json +import os +from pathlib import Path + +import numpy as np +import torch +from 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}" diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/write_target_editing.py b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/write_target_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f395611444591e300b48869efe3a3840054e582 --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/src/llm_memory_editability/write_target_editing.py @@ -0,0 +1,628 @@ +"""Does writing the same new entity into the early state restore its later use? + +The three objectives use identical atomic labels, replay, shared-MLP parameters, +and update counts. Only the objective weights change. Graph-only strict first-hop +cases and the full-pool evaluator are inherited from the established edit study. +No downstream relation or composed answer is passed to the optimizer. +""" + +from __future__ import annotations + +import copy +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import interface_editing as ie +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import data_digest, file_hash + +OBJECTIVES = ("final_ce", "early_ce", "early_ce_align") + + +def objective(model, target_batch, replay_batch, parent_log, kind, spec): + """All early supervision is the exact entity label of the atomic answer.""" + if kind not in OBJECTIVES: + raise ValueError(f"Unknown writing objective: {kind}") + if parent_log.requires_grad: + raise ValueError("Replay reference must be detached") + logits, state = model(target_batch[0], positions=target_batch[1], return_bridge=True) + final_ce = F.cross_entropy(logits.flatten(0, 1), target_batch[2].flatten()) + entity = target_batch[2][:, 0] + early_logits = F.linear(model.ln_final(state), model.token.weight) + early_ce = F.cross_entropy(early_logits, entity) + canonical = model.token(entity).detach() + alignment = ( + (F.normalize(state, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1).mean() + ) + replay = model(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + kl = F.kl_div(replay, parent_log, log_target=True, reduction="none").sum(-1).mean() + # Compute the same graph in all arms, including the zero-weight components. + early_weight = spec.get("early_weight", 0.3) if kind != "final_ce" else 0.0 + alignment_weight = spec.get("alignment_weight", 0.3) if kind == "early_ce_align" else 0.0 + loss = ( + final_ce + + spec.get("replay_weight", 1.0) * kl + + early_weight * early_ce + + alignment_weight * alignment + ) + return loss, { + "final_ce": final_ce, + "replay_kl": kl, + "early_ce": early_ce, + "alignment": alignment, + } + + +@torch.no_grad() +def early_readout(model, case, device): + """Read the causal first-block state without fitting a probe or using D.""" + rows = np.asarray([case["new_fact"]], dtype=np.int64) + tokens, positions, _ = ie.answer_batch(rows, device) + _, state = model(tokens, positions=positions, return_bridge=True) + logits = F.linear(model.ln_final(state), model.token.weight) + old, new = int(case["old_fact"][2]), int(case["new_fact"][2]) + probabilities = logits.softmax(-1) + old_embedding = model.token.weight[old : old + 1] + new_embedding = model.token.weight[new : new + 1] + prediction = int(logits.argmax(-1).item()) + metrics = { + "n": 1, + "new_entity_accuracy": float(prediction == new), + "old_entity_accuracy": float(prediction == old), + "new_entity_probability": float(probabilities[0, new]), + "old_entity_probability": float(probabilities[0, old]), + "new_entity_nll": float(-logits.log_softmax(-1)[0, new]), + "new_direction_cosine": float(F.cosine_similarity(state, new_embedding).item()), + "old_direction_cosine": float(F.cosine_similarity(state, old_embedding).item()), + "state_norm": float(state.norm()), + } + raw = { + "early__state": state.cpu().numpy(), + "early__entity_prediction": np.asarray([prediction], dtype=np.int64), + "early__entity_probabilities": probabilities[:, [old, new]].cpu().numpy(), + } + return metrics, raw + + +def selected_cases(parent_spec, spec): + cases, qualification = ie.graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780101), + per_cell=spec.get("per_cell", 4), + replay_n=spec.get("replay_n", 32), + ) + cases = [case for case in cases if case["role"] == "first" and case["stratum"] == "strict"] + if "case_ids" in spec: + wanted = set(spec["case_ids"]) + if not wanted or not wanted <= {case["case_id"] for case in cases}: + raise ValueError("Only graph-selected strict first-hop cases are permitted") + cases = [case for case in cases if case["case_id"] in wanted] + return cases, qualification + + +def _evaluate(model, case, tasks, originals, parent_correct, device, batch_size): + metrics, raw = ie.evaluate_case( + model, tasks, originals, parent_correct, "first", device, batch_size + ) + metrics["early"], early_raw = early_readout(model, case, device) + raw.update(early_raw) + return metrics, raw + + +def _restore(parent, tensor_path, scope="mlp", block_index=0): + state = torch.load(tensor_path, map_location="cpu", weights_only=True) + model = copy.deepcopy(parent).eval() + selected = ie.editable_parameters(model, scope, block_index) + if set(state["edited_tensors"]) != set(selected): + raise AssertionError("Saved edit changes an unexpected parameter scope") + merged = model.state_dict() + merged.update(state["edited_tensors"]) + model.load_state_dict(merged) + if model_digest(model) != state["model_sha256"]: + raise AssertionError("Saved exact tensors do not reconstruct their model digest") + return model + + +def diagnostics(existing_dir, out, device="cuda:0"): + """Reload existing final-answer edits before any new training; never mutate them.""" + device, existing_dir, out = ie._configure(device), Path(existing_dir), Path(out) + if out.exists(): + raise FileExistsError(out) + manifest = json.loads((existing_dir / "run.json").read_text()) + spec = manifest["spec"] + parent, _world, parent_spec = ie._load_parent(spec["parent_dir"], device) + if model_digest(parent) != manifest["parent_model_sha256"]: + raise AssertionError("Historical parent digest changed") + cases, _ = ie.graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + cases = {c["case_id"]: c for c in cases if c["role"] == "first" and c["stratum"] == "strict"} + records = [] + summary = json.loads((existing_dir / "complete.json").read_text()) + for branch in summary["branches"]: + if branch["case_id"] not in cases: + continue + case = cases[branch["case_id"]] + directory = existing_dir / branch["path"] + parent_metrics, parent_raw = early_readout(parent, case, device) + for record in json.loads((directory / "learning.json").read_text()): + tensor_path = directory / f"tensors-{record['step']:06d}.pt" + model = _restore(parent, tensor_path, spec.get("parameter_scope", "mlp")) + if model_digest(model) != record["model_sha256"]: + raise AssertionError("Historical trajectory digest changed") + values, raw = early_readout(model, case, device) + values["state_delta_l2"] = float( + np.linalg.norm(raw["early__state"] - parent_raw["early__state"]) + ) + records.append( + { + "case_id": case["case_id"], + "arm": branch["arm"], + "step": record["step"], + "early": values, + "parent_early": parent_metrics, + "E_new": record["metrics"]["E_new"], + "E_old": record["metrics"]["E_old"], + "tensor_file_sha256": file_hash(tensor_path), + "model_sha256": model_digest(model), + } + ) + if not records: + raise ValueError("Historical run contains no strict first-hop edit nodes") + result = { + "status": "complete", + "training_updates": 0, + "existing_dir": str(existing_dir), + "parent_model_sha256": manifest["parent_model_sha256"], + "source_run_sha256": file_hash(existing_dir / "run.json"), + "records": records, + "finished_utc": utc(), + } + write_json(out, result) + return result + + +def _validate(spec): + nodes = spec.get("nodes", [0, 32, 128, 512]) + if not nodes or nodes[0] != 0 or nodes != sorted(set(nodes)) or nodes[-1] <= 0: + raise ValueError("Nodes must increase from zero to a positive fixed endpoint") + kinds = spec.get("objectives", list(OBJECTIVES)) + if not kinds or len(set(kinds)) != len(kinds) or set(kinds) - set(OBJECTIVES): + raise ValueError("Unknown or repeated objective") + if spec.get("lr", 1e-5) <= 0 or "learning_rates" in spec: + raise ValueError("Use one fixed positive learning rate") + if spec.get("parameter_scope", "mlp") != "mlp" or spec.get("block_index", 0) != 0: + raise ValueError("This comparison edits the same first shared MLP only") + return nodes, kinds + + +def run(spec, out, device="cuda:0"): + """One parent and one or more fixed objectives, each with all edit/sham pairs.""" + device, out = ie._configure(device), Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite an existing attempt: {out}") + nodes, kinds = _validate(spec) + parent, world, parent_spec = ie._load_parent(spec["parent_dir"], device) + parent_file_hash = file_hash(Path(spec["parent_dir"]) / "model.pt") + if spec.get("parent_checkpoint_sha256", parent_file_hash) != parent_file_hash: + raise AssertionError("Preselected parent checkpoint hash changed") + if parent_spec["layers"] != 1 or parent_spec["repeats"] != 2: + raise ValueError("Use the established two-execution shared GPT parent") + parent_hash = model_digest(parent) + cases, qualification = selected_cases(parent_spec, spec) + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "cases": cases, + "qualification": qualification, + "case_sha256": ie._hash_json(cases), + "parent_file_sha256": parent_file_hash, + "parent_model_sha256": parent_hash, + "initial_model_sha256": parent_hash, + "world_sha256": data_digest(world), + "created_utc": utc(), + "dtype": "float32", + "allow_tf32": True, + "pid": os.getpid(), + "gpu": device.index if device.type == "cuda" else None, + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else "CPU", + "branches": len(cases) * len(kinds) * 2, + "planned_updates": len(cases) * len(kinds) * 2 * nodes[-1], + "learning_step_unit": "evaluation_index", + "status_step_unit": "completed_branches", + "early_state": "first executed block at first relation token, position 3", + "scope_warning": "Selected MLP parameters are shared across both executions", + "supervision": "same atomic entity label; no second relation or composed answer", + } + write_json(out / "run.json", manifest) + write_json(out / "learning.json", []) + write_json(out / "cases.json", cases) + np.savez_compressed(out / "world.npz", **world) + if spec.get("diagnostic_existing_dir"): + diagnostic = diagnostics( + spec["diagnostic_existing_dir"], out / "existing-edit-diagnostics.json", device + ) + if diagnostic["parent_model_sha256"] != parent_hash: + raise AssertionError("Diagnostic and training parent must be identical") + root_learning, summaries = [], [] + completed_updates, early_presentations, alignment_presentations = 0, 0, 0 + started, training_seconds = time.perf_counter(), 0.0 + batch_size = spec.get("eval_batch_size", 512) + for case in cases: + tasks, originals = ie.case_tasks(world, case) + masks = ie._parent_masks(parent, originals, device, batch_size) + parent_metrics, parent_raw = _evaluate( + parent, case, tasks, originals, masks, device, batch_size + ) + case_out = out / case["case_id"] + case_out.mkdir() + write_json(case_out / "parent-metrics.json", parent_metrics) + np.savez_compressed(case_out / "parent-predictions.npz", **parent_raw) + np.savez_compressed(case_out / "tasks.npz", **tasks) + replay = ie.answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + reference = parent(replay[0], positions=replay[1]).log_softmax(-1).detach() + for kind in kinds: + for arm in ("edit", "sham"): + directory = case_out / f"{kind}-{arm}" + directory.mkdir() + model = copy.deepcopy(parent).eval() + selected = ie.editable_parameters(model) + parameters = dict(model.named_parameters()) + optimizer = torch.optim.Adam( + [parameters[n] for n in selected], lr=spec.get("lr", 1e-5) + ) + target_name = "E_new" if arm == "edit" else "E_old" + target = ie.answer_batch(tasks[target_name], device) + write_json( + directory / "run.json", + { + "case_id": case["case_id"], + "objective": kind, + "arm": arm, + "editable_parameters": selected, + "parent_model_sha256": parent_hash, + "target_batch_sha256": ie._batch_hash(target), + "replay_batch_sha256": ie._batch_hash(replay), + "parent_reference_sha256": ie._batch_hash((reference,)), + "optimizer": "Adam, fresh state, zero weight decay", + "sampling": "same fixed full replay batch every update; no dropout", + "nodes": nodes, + }, + ) + history, losses, step = [], [], 0 + for node in nodes: + if device.type == "cuda": + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, components = objective(model, target, replay, reference, kind, spec) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite loss at {case['case_id']}/{step}") + loss.backward() + norm = torch.nn.utils.clip_grad_norm_( + [parameters[n] for n in selected], spec.get("clip_norm", 1.0) + ) + optimizer.step() + step += 1 + losses.append( + { + "step": step, + "loss": float(loss.detach()), + "gradient_norm": float(norm), + **{key: float(value.detach()) for key, value in components.items()}, + } + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + metrics, predictions = _evaluate( + model, case, tasks, originals, masks, device, batch_size + ) + digest = model_digest(model) + record = { + "step": step, + "model_sha256": digest, + "metrics": metrics, + "loss": losses[-1] if losses else None, + } + history.append(record) + write_json(directory / "learning.json", history) + write_json(directory / "losses.json", losses) + np.savez_compressed(directory / f"predictions-{step:06d}.npz", **predictions) + torch.save( + { + "edited_tensors": { + n: parameters[n].detach().cpu().clone() for n in selected + }, + "model_sha256": digest, + "step": step, + }, + directory / f"tensors-{step:06d}.pt", + ) + updates = completed_updates + step + root_learning.append( + { + "step": len(root_learning), + "branch_step": step, + "optimizer_updates": updates, + "case_id": case["case_id"], + "condition": kind, + "arm": arm, + "metrics": metrics, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": updates * (1 + len(tasks["R_atomic"])), + "target_supervised_tokens": updates * 3, + "replay_distillation_positions": updates * len(tasks["R_atomic"]) * 3, + "early_target_presentations": early_presentations + + step * (kind != "final_ce"), + "alignment_target_presentations": alignment_presentations + + step * (kind == "early_ce_align"), + } + ) + write_json(out / "learning.json", root_learning) + write_json( + out / "status.json", + { + "state": "running", + "step": len(summaries), + "optimizer_updates": updates, + "budget": manifest["branches"], + "case_id": case["case_id"], + "objective": kind, + "arm": arm, + }, + ) + print( + json.dumps( + { + "case": case["case_id"], + "objective": kind, + "arm": arm, + "step": step, + "E": metrics[target_name]["accuracy"], + "early_new": metrics["early"]["new_entity_accuracy"], + "D": metrics["D_first_strict"]["accuracy"], + } + ), + flush=True, + ) + changed = [ + n + for n, value in model.state_dict().items() + if not torch.equal(value, parent.state_dict()[n]) + ] + if set(changed) - set(selected) or model_digest(parent) != parent_hash: + raise AssertionError("A frozen parameter or the parent changed") + complete = { + "case_id": case["case_id"], + "role": "first", + "stratum": "strict", + "objective": kind, + "arm": arm, + "path": str(directory.relative_to(out)), + "metrics": metrics, + "steps": step, + "changed_tensors": changed, + "parent_model_sha256": parent_hash, + "final_model_sha256": digest, + "delta_l2": float( + torch.sqrt( + sum( + (parameters[n] - dict(parent.named_parameters())[n]).square().sum() + for n in selected + ) + ).detach() + ), + "tensor_file_sha256": file_hash(directory / f"tensors-{step:06d}.pt"), + } + write_json(directory / "complete.json", complete) + summaries.append(complete) + completed_updates += step + early_presentations += step * (kind != "final_ce") + alignment_presentations += step * (kind == "early_ce_align") + result = { + "status": "complete", + "branches": summaries, + "updates": completed_updates, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "finished_utc": utc(), + "case_sha256": manifest["case_sha256"], + } + write_json(out / "complete.json", result) + write_json( + out / "status.json", + { + "state": "complete", + "step": len(summaries), + "optimizer_updates": completed_updates, + "budget": manifest["branches"], + }, + ) + return result + + +def audit(out, device="cuda:0"): + """Independently reconstruct every branch/node and compare stored predictions.""" + device, out = ie._configure(device), Path(out) + manifest = json.loads((out / "run.json").read_text()) + spec = manifest["spec"] + nodes, kinds = _validate(spec) + parent, world, parent_spec = ie._load_parent(spec["parent_dir"], device) + if ( + model_digest(parent) != manifest["parent_model_sha256"] + or file_hash(Path(spec["parent_dir"]) / "model.pt") != manifest["parent_file_sha256"] + ): + raise AssertionError("Parent changed") + cases, qualification = selected_cases(parent_spec, spec) + if ( + cases != manifest["cases"] + or qualification != manifest["qualification"] + or data_digest(world) != manifest["world_sha256"] + ): + raise AssertionError("Graph cases or world changed") + result = json.loads((out / "complete.json").read_text()) + branches = result["branches"] + expected = [ + (case["case_id"], kind, arm) for case in cases for kind in kinds for arm in ("edit", "sham") + ] + if [(b["case_id"], b["objective"], b["arm"]) for b in branches] != expected: + raise AssertionError("Incomplete paired objective matrix") + learning = json.loads((out / "learning.json").read_text()) + if len(learning) != len(expected) * len(nodes) or [r["step"] for r in learning] != list( + range(len(learning)) + ): + raise AssertionError("Root evaluation indices changed") + early_count, alignment_count = 0, 0 + for index, row in enumerate(learning): + branch_index, node_index = divmod(index, len(nodes)) + case_id, kind, arm = expected[branch_index] + node = nodes[node_index] + updates = branch_index * nodes[-1] + node + if (row["case_id"], row["condition"], row["arm"], row["branch_step"]) != ( + case_id, + kind, + arm, + node, + ): + raise AssertionError("Root branch ordering changed") + wanted = { + "optimizer_updates": updates, + "target_supervised_tokens": updates * 3, + "replay_distillation_positions": updates * spec.get("replay_n", 32) * 3, + "early_target_presentations": early_count + node * (kind != "final_ce"), + "alignment_target_presentations": alignment_count + node * (kind == "early_ce_align"), + } + if any(row[key] != value for key, value in wanted.items()): + raise AssertionError("Optimizer or exposure accounting changed") + if node_index == len(nodes) - 1: + early_count += node * (kind != "final_ce") + alignment_count += node * (kind == "early_ce_align") + checked, max_error = 0, 0.0 + batch_size = spec.get("eval_batch_size", 512) + for case in cases: + tasks, originals = ie.case_tasks(world, case) + masks = ie._parent_masks(parent, originals, device, batch_size) + replay = ie.answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + reference = parent(replay[0], positions=replay[1]).log_softmax(-1) + for branch in branches: + if branch["case_id"] != case["case_id"]: + continue + directory = out / branch["path"] + branch_spec = json.loads((directory / "run.json").read_text()) + target = ie.answer_batch(tasks["E_new" if branch["arm"] == "edit" else "E_old"], device) + hashes = { + "target_batch_sha256": ie._batch_hash(target), + "replay_batch_sha256": ie._batch_hash(replay), + "parent_reference_sha256": ie._batch_hash((reference,)), + } + if any(branch_spec[key] != value for key, value in hashes.items()): + raise AssertionError("Supervision or replay provenance changed") + history = json.loads((directory / "learning.json").read_text()) + if [r["step"] for r in history] != nodes: + raise AssertionError("Saved node matrix incomplete") + if ( + branch["metrics"] != history[-1]["metrics"] + or branch["final_model_sha256"] != history[-1]["model_sha256"] + ): + raise AssertionError("Final summary differs from audited trajectory") + if file_hash(directory / f"tensors-{nodes[-1]:06d}.pt") != branch["tensor_file_sha256"]: + raise AssertionError("Final tensor hash changed") + for record in history: + model = _restore(parent, directory / f"tensors-{record['step']:06d}.pt") + if model_digest(model) != record["model_sha256"]: + raise AssertionError("Recorded model digest changed") + metrics, raw = _evaluate(model, case, tasks, originals, masks, device, batch_size) + with np.load(directory / f"predictions-{record['step']:06d}.npz") as saved: + if set(saved.files) != set(raw): + raise AssertionError("Prediction keys changed") + for name, values in raw.items(): + if values.dtype.kind == "f": + np.testing.assert_allclose(values, saved[name], rtol=1e-5, atol=1e-5) + if values.size: + max_error = max( + max_error, float(np.max(np.abs(values - saved[name]))) + ) + else: + np.testing.assert_array_equal(values, saved[name]) + for name, values in metrics.items(): + for key, value in values.items(): + expected_value = record["metrics"][name][key] + if isinstance(value, float): + np.testing.assert_allclose(value, expected_value, rtol=1e-5, atol=1e-5) + elif value != expected_value: + raise AssertionError(f"Metric changed: {name}/{key}") + checked += 1 + result = { + "passed": True, + "nodes": checked, + "max_float_error": max_error, + "case_sha256": manifest["case_sha256"], + "finished_utc": utc(), + } + write_json(out / "audit.json", result) + return result + + +def development_decision(run_dirs): + """Operational calibration reads only E and independent atomic retention. + + This is an admissibility check for the fixed recipe, not selection using + downstream propagation. Early readout success is recorded, not an exclusion. + """ + records, observed = [], set() + for directory in map(Path, run_dirs): + manifest = json.loads((directory / "run.json").read_text()) + if manifest["spec"].get("phase") not in {"development", "engineering"}: + raise ValueError("Calibration may read development runs only") + if json.loads((directory / "audit.json").read_text()).get("passed") is not True: + raise ValueError("Calibration requires independent reload audit") + result = json.loads((directory / "complete.json").read_text()) + for branch in result["branches"]: + observed.add(branch["objective"]) + metrics = branch["metrics"] + target = "E_new" if branch["arm"] == "edit" else "E_old" + records.append( + { + "run": str(directory), + "case_id": branch["case_id"], + "objective": branch["objective"], + "arm": branch["arm"], + "target_accuracy": metrics[target]["accuracy"], + "U_atomic_accuracy": metrics["U_atomic"]["accuracy"], + "necessary_atomic_accuracy": metrics["necessary_atomic"]["accuracy"], + "early_target_accuracy": metrics["early"][ + "new_entity_accuracy" if branch["arm"] == "edit" else "old_entity_accuracy" + ], + } + ) + if observed != set(OBJECTIVES): + raise ValueError("Calibration requires all three objectives") + passed = bool(records) and all( + r["target_accuracy"] == 1 + and r["U_atomic_accuracy"] >= 0.95 + and r["necessary_atomic_accuracy"] >= 0.95 + for r in records + ) + return { + "operational_gate_passed": passed, + "decision_rule": "Every edit/sham E=1; U_atomic and necessary_atomic >=.95; no D access", + "configuration_search": False, + "records": records, + "created_utc": utc(), + } diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/tests/test_sequential_data.py b/docs/development-artifacts/sequential-transfer-development-v1/source/tests/test_sequential_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c37e32f3d0cede6ced08c8274eb6e4261fe81ede --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/tests/test_sequential_data.py @@ -0,0 +1,108 @@ +import copy + +import pytest + +from llm_memory_editability.sequential_data import ( + SplitSettings, + audit_split, + build_split, + safe_atom_ids, +) + + +def source_graph(size=40): + atoms = {} + for head in range(size): + for relation, distance in [("r1", 1), ("r2", 3)]: + key = f"{head}:{relation}" + atoms[key] = { + "id": key, + "edge": [f"e{head}", relation, f"e{(head + distance) % size}"], + "question": key, + "answer": f"e{(head + distance) % size}", + "aliases": [], + "encoded": {"prefix": [1], "target": [2, 0], "input": [1, 2]}, + } + chains = [] + for first in atoms.values(): + bridge = int(first["edge"][2][1:]) + for relation in ["r1", "r2"]: + second = atoms[f"{bridge}:{relation}"] + chains.append( + { + "id": first["id"] + "/" + second["id"], + "atom_ids": [first["id"], second["id"]], + "edges": [first["edge"], second["edge"]], + "question": first["id"] + "/" + relation, + "answer": second["answer"], + "aliases": [], + "encoded": {"prefix": [1], "target": [2, 0], "input": [1, 2]}, + } + ) + return { + "atoms": list(atoms.values()), + "train_compositions": chains, + "evaluation_compositions": [], + } + + +@pytest.fixture +def dataset(): + return build_split(source_graph(), SplitSettings("test", 4, 32, 2)) + + +def test_split_is_reproducible_source_preserving_and_name_familiar(dataset): + source = source_graph() + assert dataset == build_split(source, SplitSettings("test", 4, 32, 2)) + assert dataset["audit"]["passed"] + assert dataset["audit"]["bb_all_entities_seen_in_a"] + assert dataset["audit"]["evaluation_counts"] == {"AA": 2, "BA": 2, "AB": 2, "BB": 4} + source_atoms = {row["id"]: row for row in source["atoms"]} + for row in dataset["atoms"]: + assert {key: value for key, value in row.items() if key != "subset"} == source_atoms[ + row["id"] + ] + + +def test_alias_variant_of_heldout_chain_cannot_enter_training(dataset): + changed = copy.deepcopy(dataset) + row = copy.deepcopy(changed["evaluation_compositions"][0]) + row["id"] = "alternate-question-id" + row["question"] = "An alternative wording for the same evidence chain" + changed["train_compositions"].append(row) + with pytest.raises(ValueError, match="held-out semantic chain"): + audit_split(changed) + + +def test_a_composition_cannot_expose_new_atom(dataset): + changed = copy.deepcopy(dataset) + original = next( + row + for row in source_graph()["train_compositions"] + if set(row["atom_ids"]) & set(dataset["stage_b_atom_ids"]) + and row["id"] not in {item["id"] for item in dataset["evaluation_compositions"]} + ) + changed["train_compositions"].append(original) + with pytest.raises(ValueError, match="B fact leaked"): + audit_split(changed) + + +def test_explicit_inverse_and_equivalent_answers_are_excluded(): + atoms = { + "b": {"edge": ["person", "father", "dad"]}, + "inverse": {"edge": ["dad", "child", "person"]}, + "same_answer": {"edge": ["person", "parent", "dad"]}, + "safe": {"edge": ["person", "country", "place"]}, + } + assert safe_atom_ids(atoms, {"b"}) == {"safe"} + + +def test_evaluation_role_and_truth_are_checked(dataset): + changed = copy.deepcopy(dataset) + changed["evaluation_compositions"][-1]["sequential_role"] = "AA" + with pytest.raises(ValueError, match="Incorrect sequential role"): + audit_split(changed) + changed = copy.deepcopy(dataset) + changed["evaluation_compositions"][0]["edges"][0][2] = "false-bridge" + with pytest.raises(ValueError, match="disagree"): + audit_split(changed) diff --git a/docs/development-artifacts/sequential-transfer-development-v1/source/tests/test_sequential_transfer.py b/docs/development-artifacts/sequential-transfer-development-v1/source/tests/test_sequential_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..b94f8c1282d3d71c6f5f52ebdf8323e023466d0f --- /dev/null +++ b/docs/development-artifacts/sequential-transfer-development-v1/source/tests/test_sequential_transfer.py @@ -0,0 +1,222 @@ +"""Scientific contracts for learning order, held-out knowledge and restoration.""" + +import copy +import json +from collections import Counter +from types import SimpleNamespace + +import numpy as np +import pytest +import torch + +from llm_memory_editability import sequential_transfer as st +from llm_memory_editability.realworld_composition import ( + construct, + model_digest, + optimizer_for, + update, +) + + +def fixture_data(): + def row(key, subset=None, atoms=None, role=None): + value = { + "id": key, + "answer": "answer", + "question": "question", + "encoded": {"prefix": [1, 2], "target": [3, 30], "input": [1, 2, 3]}, + } + if subset: + value["subset"] = subset + if atoms: + value.update(atom_ids=atoms, sequential_role=role) + return value + + atoms = [row("a0", "A"), row("a1", "A"), row("a2", "A"), row("b0", "B"), row("b1", "B")] + chains = [row("train", atoms=["a0", "a1"], role="AA")] + evaluation = [ + row("test-aa", atoms=["a1", "a2"], role="AA"), + row("test-ba", atoms=["b0", "a0"], role="BA"), + row("test-ab", atoms=["a0", "b1"], role="AB"), + row("test-bb", atoms=["b0", "b1"], role="BB"), + ] + return { + "atoms": atoms, + "train_compositions": chains, + "evaluation_compositions": evaluation, + "panels": { + "atomic_A": ["a0"], + "atomic_B": [], + "train_composition": ["train"], + **{r["sequential_role"]: [r["id"]] for r in evaluation}, + }, + } + + +def spec(history="sequential_composition"): + return { + "history": history, + "stage_a_steps": 7, + "stage_b_steps": 5, + "batch_size": 6, + "microbatch_size": 6, + "sampling_seed": 17, + "initialization": 23, + "unique_layers": 2, + "repeats": 1, + "learning_rate": 0.001, + "weight_decay": 0.1, + "warmup_steps": 2, + } + + +def test_joint_is_exact_example_and_supervision_multiset(): + data = fixture_data() + records, sequential = st.training_plan(data, spec()) + _, joint = st.training_plan(data, spec("joint")) + assert Counter(sequential.flatten()) == Counter(joint.flatten()) + assert not np.array_equal(sequential, joint) + a = st.plan_manifest(records, sequential, spec()) + b = st.plan_manifest(records, joint, spec("joint")) + for key in ("multiset_sha256", "supervised_tokens", "input_tokens", "counts", "examples"): + assert a[key] == b[key] + assert a["plan_sha256"] != b["plan_sha256"] + + +def test_new_facts_and_all_B_combinations_absent_from_A(): + records, plan = st.training_plan(fixture_data(), spec()) + assert all(records[i].get("subset") != "B" for i in plan[:7].flatten()) + assert all(records[i].get("subset") in {"A", "B"} for i in plan[7:].flatten()) + assert all(not row["id"].startswith("test") for row in records) + assert all("B" not in row.get("sequential_role", "") for row in records) + + +def test_atomic_control_has_identical_new_fact_and_replay_stream(): + records, original = st.training_plan(fixture_data(), spec()) + _, control = st.training_plan(fixture_data(), spec("sequential_atomic")) + np.testing.assert_array_equal(original[7:], control[7:]) + assert all(records[i].get("subset") == "A" for i in control[:7].flatten()) + np.testing.assert_array_equal(original[:7, :3], control[:7, :3]) + + +def test_sham_has_identical_parent_and_only_A_continuation(): + records, original = st.training_plan(fixture_data(), spec()) + _, sham = st.training_plan(fixture_data(), spec("sequential_composition_sham")) + np.testing.assert_array_equal(original[:7], sham[:7]) + np.testing.assert_array_equal(original[7:, :3], sham[7:, :3]) + assert all(records[i].get("subset") == "A" for i in sham[7:].flatten()) + + +def test_evaluation_panel_includes_every_necessary_atom(): + groups = st.evaluation_groups(fixture_data(), full=False) + available = {row["id"] for name in ("atomic_A", "atomic_B") for row in groups[name]} + needed = { + key for role in ("AA", "BA", "AB", "BB") for row in groups[role] for key in row["atom_ids"] + } + assert needed <= available + assert {row["id"] for row in groups["BB"]} == {"test-bb"} + + +@pytest.mark.parametrize("leak", ("new_fact", "heldout_chain", "wrong_role")) +def test_data_contract_rejects_leakage(leak): + data = fixture_data() + if leak == "new_fact": + data["train_compositions"][0]["atom_ids"] = ["a0", "b0"] + elif leak == "heldout_chain": + data["evaluation_compositions"][0]["atom_ids"] = ["a0", "a1"] + else: + data["evaluation_compositions"][0]["sequential_role"] = "BB" + with pytest.raises(ValueError): + st.validate_data(data) + + +def test_learning_rate_has_same_global_history_and_explicit_stage_reset(): + for step in range(1, 13): + assert len({st.learning_rate(spec(history), step) for history in st.HISTORIES}) == 1 + assert st.learning_rate(spec(), 7) == pytest.approx(0.0001) + assert st.learning_rate(spec(), 8) == pytest.approx(0.0005) + assert st.learning_rate(spec(), 12) == pytest.approx(0.0001) + + +def test_resume_restores_optimizer_rng_and_next_update(tmp_path): + torch.set_num_threads(1) + model_config = dict(vocab_size=31, positions=32, hidden_size=8, attention_heads=2, dropout=0.1) + run_spec = spec() + records, plan = st.training_plan(fixture_data(), run_spec) + manifest = st.plan_manifest(records, plan, run_spec) + model = construct(model_config, run_spec, "cpu") + optimizer = optimizer_for(model, 0.001, 0.1) + update(model, optimizer, [records[i] for i in plan[0]], run_spec, "cpu", 30) + counts = np.zeros(len(records), dtype=np.int64) + np.add.at(counts, plan[0], 1) + st.save_checkpoint( + tmp_path / "resume.pt", model, optimizer, 1, counts, {"examples": 6}, [], manifest + ) + update(model, optimizer, [records[i] for i in plan[1]], run_spec, "cpu", 30) + expected = model_digest(model) + restored = construct(model_config, run_spec, "cpu") + restored_optimizer = optimizer_for(restored, 0.001, 0.1) + state = st.restore_checkpoint(tmp_path / "resume.pt", restored, restored_optimizer, manifest) + assert state["step"] == 1 and state["counts"].sum() == 6 + update(restored, restored_optimizer, [records[i] for i in plan[1]], run_spec, "cpu", 30) + assert model_digest(restored) == expected + changed = copy.deepcopy(manifest) + changed["plan_sha256"] = "wrong" + with pytest.raises(ValueError, match="sampling plan"): + st.restore_checkpoint(tmp_path / "resume.pt", restored, restored_optimizer, changed) + + +def test_training_worker_resumes_without_repeating_or_skipping_updates(tmp_path, monkeypatch): + torch.set_num_threads(1) + run_spec = { + **spec(), + "stage_a_steps": 2, + "stage_b_steps": 2, + "model": dict(vocab_size=31, positions=32, hidden_size=8, attention_heads=2, dropout=0.1), + "data_sha256": "unit-test", + "evaluation_nodes": [0, 2, 4], + } + data = fixture_data() + + def setup(value, device): + return ( + data, + SimpleNamespace(eos_token_id=30), + construct(value["model"], value, device), + torch.device(device), + ) + + monkeypatch.setattr(st, "_setup", setup) + monkeypatch.setattr( + st, + "evaluate_transfer", + lambda model, *args, **kwargs: ( + {"fixture": {"n": 1, "digest": model_digest(model)}}, + {}, + ), + ) + uninterrupted = st.run(run_spec, tmp_path / "uninterrupted", "cpu") + original_update = st.update + calls = 0 + + def interrupt(*args, **kwargs): + nonlocal calls + calls += 1 + if calls == 3: + raise RuntimeError("simulated interruption after saved stage A") + return original_update(*args, **kwargs) + + monkeypatch.setattr(st, "update", interrupt) + with pytest.raises(RuntimeError, match="simulated interruption"): + st.run(run_spec, tmp_path / "resumed", "cpu") + monkeypatch.setattr(st, "update", original_update) + resumed = st.run(run_spec, tmp_path / "resumed", "cpu") + assert resumed["model_sha256"] == uninterrupted["model_sha256"] + assert resumed["examples"] == uninterrupted["examples"] == 24 + left = torch.load(tmp_path / "uninterrupted/latest.pt", weights_only=False) + right = torch.load(tmp_path / "resumed/latest.pt", weights_only=False) + np.testing.assert_array_equal(left["counts"], right["counts"]) + history = json.loads((tmp_path / "resumed/learning.json").read_text()) + assert [row["step"] for row in history] == [0, 2, 4] + assert history[1]["atomic_B_epochs"] == 0 + assert history[-1]["atomic_B_epochs"] > 0 diff --git a/docs/development-artifacts/shared-cache-branch-v1/execution-lock.json b/docs/development-artifacts/shared-cache-branch-v1/execution-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..ecf0c5399ffb5435f8b29d31434b658f64e00b5e --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/execution-lock.json @@ -0,0 +1,3 @@ +{ + "config_sha256": "ae187a03510b884bb5354d2c21c0e2705e1c005766811b4937a44f8bdbd20273" +} diff --git a/docs/development-artifacts/shared-cache-branch-v1/frozen-config.json b/docs/development-artifacts/shared-cache-branch-v1/frozen-config.json new file mode 100644 index 0000000000000000000000000000000000000000..e6c49d14a0e94635efc9042f291bc1d5c126fcf7 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/frozen-config.json @@ -0,0 +1,6017 @@ +{ + "batch": "shared-cache-branch-v1", + "source_root": "/ossfs/workspace/llm-memory-editability/docs/development-artifacts/shared-cache-branch-v1/source", + "source": { + "src/llm_memory_editability/__init__.py": "84e6bb4a97b68f67f3256135c2b5fc35d9a83ceb04914a6cf3d38d926b015f7f", + "src/llm_memory_editability/__main__.py": "0af76e0612dd46d8097cd06d02bcd6220d89354be49910110a80b9942fdb71b3", + "src/llm_memory_editability/alignment_coverage.py": "152b868b836ff3ae18d8bb572ffe6ce956ea26edde1d283726b82215125736ff", + "src/llm_memory_editability/architecture_bridge.py": "777fe51d98b09275f487386660106e93c6c8b49e25b94e804510ed968c2df04c", + "src/llm_memory_editability/architecture_bridge_toy.py": "320d859c4d11b68299266d3f9bdb9a7e6867d635eb3d347827be082c60f0ffca", + "src/llm_memory_editability/bios_analysis.py": "41d836fc201b9ae4f1988e0cdda3dc3be4ebc3ca898ab2ff69ca8445212407ff", + "src/llm_memory_editability/bios_branch.py": "f5b0f0ae79f84d64e33862e40fffbc4bd9a8fd102414995e8a2d41560009c09d", + "src/llm_memory_editability/bios_capacity.py": "a9c306f0e326a8b97eccc4c0b404d45a3e3d8697186092ac562f645b4b370ba4", + "src/llm_memory_editability/bios_causal_paths.py": "10ea265743293fff64cc2201b7b49f5a22dd3bc3ff6a320f469948c233e65620", + "src/llm_memory_editability/bios_confirmation_stats.py": "e40f0347bd44e8602c18fc2fbee9647010d509d6f6dc7bc3c5cb8e98036e9c9b", + "src/llm_memory_editability/bios_context_control.py": "9205a7f8d25e0f1311d78c73638b97466f425886e62165166ba104f53050a40d", + "src/llm_memory_editability/bios_context_gradient.py": "8376dec9883b1d2c3ef06e5e04ad01fec6a1b9eceaa5cd74db02a79629bc536f", + "src/llm_memory_editability/bios_cross.py": "47b8f55adbe13d9bc6e1c5c9170cc95e382261ffb1f31980706ac95be03623bf", + "src/llm_memory_editability/bios_cross_continue.py": "e6fd3a86157566559ab0e0571fbefcc1a28f22ec7add66da2105ea81d63cdaf8", + "src/llm_memory_editability/bios_cross_scale.py": "a1be3c598403b72661b9b2df642b2b1236ae1df6fdf46d982d4d89d19487f658", + "src/llm_memory_editability/bios_cross_train.py": "0106cae29be447319be2e7f6f0e1f5b60cc6224282331906f43ebc65ab795f38", + "src/llm_memory_editability/bios_data.py": "d5568901f2042a6d89d447f47eddae9764eced0a9e71e3ea5adc0038a7e636d6", + "src/llm_memory_editability/bios_direction.py": "1240f83f5ee558101bbf6f808522fa6c37ffe09dc2296749bd5e685eff8aa41d", + "src/llm_memory_editability/bios_direction_cross.py": "66cf337b3a52508e82da6190ea01916662f1fe6fddef036844f9d1be2c179888", + "src/llm_memory_editability/bios_direction_formation.py": "e2b19c17c6b7ebb7a884782f2c7750a7c65b935c17694d4424d354c62d0a24ed", + "src/llm_memory_editability/bios_direction_refresh.py": "4f80060d4232ec3bf4fb5d99b0823d20ee759e088aeedf4bd49ab841357d0127", + "src/llm_memory_editability/bios_edit.py": "dbbbc01ce57acef79d5cc46bcd39e301b256fa1e8c9eff7b1ce5ece693f86f2f", + "src/llm_memory_editability/bios_followup.py": "06b4ffd3bbb65e2ff4df0f68e3fbf9f368257196bd4ef36eb1ffb0f7b15ee43b", + "src/llm_memory_editability/bios_measure.py": "8c275b658c5c99316a19e2328eb53952f26b8a858b591784509391780ead3267", + "src/llm_memory_editability/bios_mechanism_causal.py": "41aeed0ba09eba1b869e74dc29236aaa2abf142a596916dc06316754c7f21d8a", + "src/llm_memory_editability/bios_mechanism_causal_v2.py": "bc37408e458014e746c061c65b4672e67e30adee2b5a85b325a0282fbec00dfe", + "src/llm_memory_editability/bios_mechanism_edit.py": "ca9351ef08189c643a5b0a009af3e52b2578d5ae6265510f603cb78b229667dd", + "src/llm_memory_editability/bios_mechanism_interventions.py": "190c75e0a2779fe96936bff38d13a03e17e0dfd9faba3d2909ffc4a65265d96f", + "src/llm_memory_editability/bios_model.py": "99efb7feeeb15f33dd3f08174c1190f4aa470e3877d8ac6692b2d43fed4c5f4d", + "src/llm_memory_editability/bios_organization.py": "42f714473695da4c8543f666fd15a7eab7cef1e571429b25f81818b5505bd9d5", + "src/llm_memory_editability/bios_organization_train.py": "833426232b693495711e38101553e8bff370c837c722d76e7f9f5f2d2ed3cad6", + "src/llm_memory_editability/bios_original_data.py": "092689c2a05aad564ff8a7c6e1ac669d7e0475908e525766cf70922037cd2488", + "src/llm_memory_editability/bios_original_diagnostics.py": "6dd51ead7d16c1960740716fb73cb4409828666ac0332baae4c14730e39dd120", + "src/llm_memory_editability/bios_original_model.py": "8a52e58d343320ccce9e2f1b43674cc6765b840bd4feebed4813f78296ab29a9", + "src/llm_memory_editability/bios_original_report.py": "3483f72d479a861a4513f0a1a5dc7cbf53bcbace6a652d39f389b46ffb82286e", + "src/llm_memory_editability/bios_original_train.py": "86b2ef1be03223dff26bc7997b91143be81fb46fd29ab8650a9cde8a39eb6891", + "src/llm_memory_editability/bios_path_diagnostics.py": "7d95f31f9fa9099d6b05666b9a638f880aa83a88554d934c3ff05e86880d0f7e", + "src/llm_memory_editability/bios_path_minimal.py": "6fe8f0f6dd0950adfbbc5ad0524c1fe7e96b5c054d04338c046728535257a12e", + "src/llm_memory_editability/bios_path_transfer.py": "2a079c54c2778e9bcb8fb36ebea4f90c43ac7bb7135e6d61e8a91a250ae3a0e1", + "src/llm_memory_editability/bios_readout_control.py": "545260dcaeac15766857271cbe8646ed3f096e445215064790b4ad62b6425afe", + "src/llm_memory_editability/bios_relation_response.py": "56a21f6b7cd028aff011f99c9222518d0ef04bb803eda79a176e355cd735e0ca", + "src/llm_memory_editability/bios_shortcut_confirmation.py": "92306cd8d88e0329916b52d9aadb992db286fae4ad7cf72cd846ab2b9a22553e", + "src/llm_memory_editability/bios_shortcut_confirmation_sets.py": "063d867951c621f8110c5c2547458aa5039899d64e44c199b86a45b4661e142e", + "src/llm_memory_editability/bios_shortcut_control.py": "a9369b1a042ef644b231763e2b62ac2b12451c3a526ccf121fd476a72fa27325", + "src/llm_memory_editability/bios_shortcut_edit.py": "68c4980269249cbb1acf787fe5679bfad762460487f4a0cfc8e5e7f728ed8a68", + "src/llm_memory_editability/bios_shortcut_edit_v2.py": "55ee452c248a44e0abb50f9806a00772dc6e72b683541db6cc17ffd1ac18e899", + "src/llm_memory_editability/bios_shortcut_matched_edit.py": "a8bba1a538fe4b3d5739a2ec4d223daf54b3988d74a7aa86854af3971acd4123", + "src/llm_memory_editability/bios_train.py": "c1d84d38aa1853815075041535ae3fa9890f5cf1f9f5d9019136c79521033046", + "src/llm_memory_editability/bridge_reencoding.py": "128c02424642e2a479b8a439bd0342c89f77bf3befe3783a5fef9ebe01375ae5", + "src/llm_memory_editability/bridge_workspace.py": "fe8f98ff6348d879c0b3c6db6b24f18eaabe03692729f0b0c967fe8d3b5a124a", + "src/llm_memory_editability/capacity_controls.py": "dc0b6ea601216b0997c45271a2ce8e02121148f37c88649e68d8960c9a6f1796", + "src/llm_memory_editability/capacity_scaling.py": "5ee176e8d16e6e2a7becca7b89109712f940e21ead6b73a61a2ae974435e8678", + "src/llm_memory_editability/cli.py": "01c814b9644988be1bf2ab660b2010ad5e7beab99067116c2afb2b6957f9fd3b", + "src/llm_memory_editability/composition_curves.py": "520c4503f3d1525612432dd2c0b9fbf56d2e39ee5d6dff9f1484f19a7bfae8ec", + "src/llm_memory_editability/curve_tracking.py": "50cc8a1d652c44ef14d42b4a44cc800fb15e2ed72f4b83c4848870d76ab56fec", + "src/llm_memory_editability/depth_step.py": "bd69879d5ec6124c05ca28a62c2c2459734e5b4b17d32ae92005308de63b8279", + "src/llm_memory_editability/depth_step_edit_calibration.py": "2dd20b15ae1f92eb6f685eca1e914923ff349a6a94277cfd3a5a74ad9155b4b8", + "src/llm_memory_editability/depth_step_mechanism.py": "546ce23095e755959d8114ed2bcf3f3f0d70f4a8e38e5c9b5d98c7a28ea7c5a6", + "src/llm_memory_editability/experiment_tracking.py": "2afe9e767123bee16cf56f59c6c2953a100338ecf1f971945c4968a064551866", + "src/llm_memory_editability/experiments.py": "e575aceb2e3804956655d91710809818aec04c0b16a22edb441f5757629371d1", + "src/llm_memory_editability/grok_depth.py": "7d6d5af38a5dc4438b1e7ff44df8e833169d500f0d60d8933932bdb8822aca26", + "src/llm_memory_editability/grok_depth_bridge.py": "414a0dbf17c369ad6d15714c2c026aafc4fb12bb1813a3c056efe8035fe2773d", + "src/llm_memory_editability/grok_depth_data.py": "c1451a0647ef7c25567398efd63848dbb44fdf066d07718c02f7e556e6c8b94a", + "src/llm_memory_editability/grok_depth_extension.py": "f91923d3a7f154c7432e4763a0a90c0863eb75b7b35c8742838c9949795ab9f6", + "src/llm_memory_editability/grok_loop_data.py": "504de57da94618578cf792a3963f99e2dac587424d74ceae6b4c02c1d9680a8e", + "src/llm_memory_editability/grok_loop_mechanism.py": "aa11f58d3aa378741218eee29106b55da5601e1ff9bc3ac7e39ae55f26e613e2", + "src/llm_memory_editability/grok_loop_model.py": "07e84388997a1710e5c821e54cf6d23726e4289aab178347761e060851fea6cc", + "src/llm_memory_editability/grok_loop_same_bridge.py": "06538ab83312484367f84eefdf4944bddc8f3f45507dfcb96e005cb3017a3349", + "src/llm_memory_editability/grok_loop_same_bridge_eval.py": "dea9ebb3130a0d7816b11cd01ac6d105f09e3aa4a051857b71693da261632410", + "src/llm_memory_editability/grok_loop_supervision.py": "a24661453cb82764f81d631b9a1fb4642df0fc7181c5adf7cd6ac46960c9f9b7", + "src/llm_memory_editability/grok_loop_train.py": "4931606ee614aaadebbc3460c9ad9a86fbb12b5b6a1bbda9f3714f81424ff142", + "src/llm_memory_editability/grok_multihop.py": "67ed1f37b04fbef7031f208e5ca140aea1b6158adb64ec8b0fe12217eb53cdbc", + "src/llm_memory_editability/grok_multihop_data.py": "d417b4d39e70cfa4010a8cd737a362d8159d73c2377330b04bf471a5079da851", + "src/llm_memory_editability/grok_usage_data.py": "cfce0e5835665933ee1a1561ee681ffa6520c564be7e2292d9206399f86e7ced", + "src/llm_memory_editability/grok_usage_train.py": "5509ab6b2ad0c93e185cdfc211a7ee5afef45a5021a74aa8ce8bce520f694f70", + "src/llm_memory_editability/grokking_dynamics_mechanism.py": "713470c8432ea27c602208cf0625452859924b83f8c62927c81894070815432c", + "src/llm_memory_editability/grokking_reproduction.py": "7e3a89d96f6fef7bd4665ac46dd1acb6e7cb461c6878647ecc7c6f425ac31117", + "src/llm_memory_editability/hebbian_data.py": "f2f5458d624fc4a49781a557641de7388937e90fda846ab03f7e17a3f455dd0e", + "src/llm_memory_editability/hebbian_followup.py": "752244bd78c5b02ba1d37a276e0547a5ff5bcf7a47986d64642f0db36cc4f4aa", + "src/llm_memory_editability/hebbian_future.py": "9fa7d88102e5b79e91735f530fe98fdd2bba20fad146238cde4f6eb591cf7105", + "src/llm_memory_editability/hebbian_interface.py": "a1ead4b413aef8f3082dcd569318fd132b64ed1a1ddb0c0c3a3aae4686589198", + "src/llm_memory_editability/hebbian_learning.py": "3dd0317b90943a22aabb80dcdc24eb38199623c5fb84a67641c3acd5de6a650e", + "src/llm_memory_editability/hebbian_model.py": "e0413d8288a679800f3f7bafc8ef072a0d6d5b29fc49de417077569eec49cc3e", + "src/llm_memory_editability/hebbian_statistics.py": "8c3a37806bed9661666c55bcb7c727ab78d9f4b2a1b384323f6a33c51d0a11f8", + "src/llm_memory_editability/hebbian_train.py": "71ca785eafbe3438da45c4f5fa543a62424f1fd5176b04b317b0c78e7c96ecbf", + "src/llm_memory_editability/interface_editing.py": "f5a9aba43a4c03373bfb59510322a9be800de53af4c3f87e967c7e03f648e0a0", + "src/llm_memory_editability/interface_tracking.py": "7b7c252998c3eb764c8eaeb389cf9aab8a1da45d97200911d9e7455e59ec3c55", + "src/llm_memory_editability/latent_scaling.py": "231050e859da58c52b9ea47d09fb5de91271df0d24cbab42dead3f911adc6119", + "src/llm_memory_editability/latent_support.py": "71e2483f8b5eb7e447594bf04def731add89f4cf140954fe87f793a69cb440a3", + "src/llm_memory_editability/low_rank.py": "e1ddb5714d492311a43af2d5fd3dd5f578d8144db0b3d860ca71e3b603d018e1", + "src/llm_memory_editability/memory_reuse.py": "e95814cd98de22adc54e458f0b5933f2c3f13a0640c0c71a841780a9b1b52e57", + "src/llm_memory_editability/multihop_scaling.py": "cbb60954b2738d17a1fce125087f87ee203fe98c5d462d14ad22ccff5790c7c6", + "src/llm_memory_editability/natural_composition_confirmation.py": "e13986431617be78b05db8c1f84f522f5cf4b6af7cd1b2e9d89345423be977e2", + "src/llm_memory_editability/natural_composition_confirmation_v2.py": "9bfa6540da812d4e6e2a21d2a8942dd73908269ce46aff15915b1782382dee75", + "src/llm_memory_editability/neural.py": "f0df4d9bbb47b1febf0baf76d53b58319e598b6bbb29d31abca575e2dd13e025", + "src/llm_memory_editability/neural_data.py": "8812cb49f223dff57ac2fbbeb8055aa3017302e0450c194ecc984eaefcc3596e", + "src/llm_memory_editability/neural_models.py": "c5ecb2fd69aa205a22688c95049750a7b8a0fd58b7c888a026252273b3af9091", + "src/llm_memory_editability/parametric_architecture.py": "b19ebaa377705f582fef367163312f74c2b3d2cc0451d8df03f47eff16e37a19", + "src/llm_memory_editability/parametric_architecture_train.py": "232d2a9e1c3db2023cafd15cf107e57a6f37fc8139d8c81a45e5a3121ef31c5d", + "src/llm_memory_editability/qwen_constraints.py": "1b371c02d59becde87d61f3e8db20c9064588ff1908be66c06570ed2c5b1ab6f", + "src/llm_memory_editability/qwen_path_learning.py": "d62080bf19605df02e9a140332c8981094a6e65b4c84a14b35734248e278a231", + "src/llm_memory_editability/qwen_path_train.py": "09f03b01179a2cef8d98f803f61cea7e48ce636259222e394b0248d6744aec9d", + "src/llm_memory_editability/realworld_composition.py": "323f1cdb0f3c25a085e95b6f85fe352b1a91274aa5b3bbaca4e0686fdb4510c0", + "src/llm_memory_editability/realworld_composition_data.py": "7208e0d0789f0287963b6e36d2646171e334f40ee365af13af79944f81e221be", + "src/llm_memory_editability/realworld_confirmation.py": "e160fa1ab79580281753752b3e8f39584e5f2ba6a3b5d27abece6c99a291efe2", + "src/llm_memory_editability/realworld_confirmation_analysis.py": "c8a89a57f913e034d7fd2c805fc4567900cd1c4881d5b66e8ac0f44deee75802", + "src/llm_memory_editability/recurrence_use.py": "144fb9561ead5dbce0589ee986b6452af31405b1ff4fd30aae36a72076b62469", + "src/llm_memory_editability/representation_alignment.py": "9794218f052a19019a5cb6427b84877a5174de3c0485bad441cdaed0ec7bd6b6", + "src/llm_memory_editability/shared_cache.py": "c207467bf357887be09e8cf5235ffbcbbd93762eb201027fc666c032e6d187cd", + "src/llm_memory_editability/small_lm_composition.py": "93796eee05e305ad538a498f013463d6bcde4a03de720eff6f4bfedf903f21d1", + "src/llm_memory_editability/small_lm_followup.py": "90fdbbc5c1509d30e0e369c201b5caccac0c063636ad99101f9e3ea603ce7780", + "src/llm_memory_editability/storage_composition.py": "fa4d8b073ecb3ac69a3204ee446a4bc1ecf0c36f9d8dd1dcd0b6835c245e4c5a", + "src/llm_memory_editability/storage_frontier.py": "2a1adcbbb0439ed771e17090878b9f7c9861d2fef4544172a88c35bd037d4a22", + "src/llm_memory_editability/text_loss_source.py": "579471a04def8a11e9cc072fcb909d6e84c3b61c8d901d0d029e126f14a6d3fe", + "src/llm_memory_editability/text_pretrain.py": "cd777a56ba270d3c71ed3260f68501ee0685d4cc58a4f7b952719236adf874cb", + "src/llm_memory_editability/text_structure.py": "9c8e3f00b263a62d53868a6224830e702dcb4348c05d52cc438c1e37e365287d", + "src/llm_memory_editability/twohop_depth.py": "870ad9f1f3a3736b77b1b0781d25961803d9d2e1df9aed1c709a669691b76def", + "scripts/run_shared_cache_branch.py": "9230d184923b5a4eb527952174397ec0954ecf96c45e2787c48c62230077e816", + "scripts/report_shared_cache_branch.py": "bad1245592c557cef6d88c99dfb0c24690626d86aa292743380bedb1251f6088", + "tests/test_shared_cache.py": "cf4edf00a9a3952bf7d14f1abbe95e22d1dd648b0b0c7c095e62b1f2260969a4", + "configs/latent-scaling-v1.json": "0942faa37aef384ccd830754b544d671c840be68c6816cff12cb3d36d5176968", + "configs/experiment-tracking-defaults.json": "41d4b73b9d2f57f71fe51dd8500275f2c9fb3476ec24a9eeee3a8deadb5ecaa2", + "docs/development-artifacts/shared-cache-branch-v1/protocol.md": "af6a8af5898bf5d3614c50eda617e7b7b7241ee323f5429be906be7ed74986f2" + }, + "specs": [ + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 2, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "development", + "memory_arm": "local", + "window": 2, + "name": "w730011-local-r2", + "job_type": "training", + "matched_compute_step": 128000, + "reference_compute_budget": 2398045077504000, + "per_step_flops": 18734727168, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9" + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 127350, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 127350, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 2, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "development", + "memory_arm": "shared_full", + "window": 2, + "name": "w730011-shared_full-r2", + "job_type": "training", + "matched_compute_step": 127350, + "reference_compute_budget": 2398045077504000, + "per_step_flops": 18830278656, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9" + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 127350, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 127350, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 2, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "development", + "memory_arm": "shared_window", + "window": 2, + "name": "w730011-shared_window-r2", + "job_type": "training", + "matched_compute_step": 127350, + "reference_compute_budget": 2398045077504000, + "per_step_flops": 18830278656, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9" + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 127350, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 127350, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 2, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "development", + "memory_arm": "shared_detached", + "window": 2, + "name": "w730011-shared_detached-r2", + "job_type": "training", + "matched_compute_step": 127350, + "reference_compute_budget": 2398045077504000, + "per_step_flops": 18830278656, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9" + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "development", + "memory_arm": "local", + "window": 2, + "name": "w730011-local-r4", + "job_type": "training", + "matched_compute_step": 128000, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9" + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 126967, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 126967, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "development", + "memory_arm": "shared_full", + "window": 2, + "name": "w730011-shared_full-r4", + "job_type": "training", + "matched_compute_step": 126967, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35519938560, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9" + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 126967, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 126967, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "development", + "memory_arm": "shared_window", + "window": 2, + "name": "w730011-shared_window-r4", + "job_type": "training", + "matched_compute_step": 126967, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35519938560, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9" + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 126967, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 126967, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "development", + "memory_arm": "shared_detached", + "window": 2, + "name": "w730011-shared_detached-r4", + "job_type": "training", + "matched_compute_step": 126967, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35519938560, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9" + }, + { + "world": 107260711, + "initialization": 107260721, + "stream_seed": 107260731, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "w107260711-local-r4", + "job_type": "training", + "matched_compute_step": 128000, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "2d13e53d5f40d1a853118d004878c4f3978af8eebf3f685a777dd788cc825b5a", + "parameters": 1011072, + "data_sha256": "c4da338291380c843d33ca8e10bcf8f49b48b33e6931700c299cd3376e74bfe4" + }, + { + "world": 107260711, + "initialization": 107260721, + "stream_seed": 107260731, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 126967, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 126967, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "w107260711-shared_full-r4", + "job_type": "training", + "matched_compute_step": 126967, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35519938560, + "initial_model_sha256": "2d13e53d5f40d1a853118d004878c4f3978af8eebf3f685a777dd788cc825b5a", + "parameters": 1011072, + "data_sha256": "c4da338291380c843d33ca8e10bcf8f49b48b33e6931700c299cd3376e74bfe4" + }, + { + "world": 107260711, + "initialization": 107260721, + "stream_seed": 107260731, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 126967, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 126967, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "confirmation", + "memory_arm": "shared_window", + "window": 2, + "name": "w107260711-shared_window-r4", + "job_type": "training", + "matched_compute_step": 126967, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35519938560, + "initial_model_sha256": "2d13e53d5f40d1a853118d004878c4f3978af8eebf3f685a777dd788cc825b5a", + "parameters": 1011072, + "data_sha256": "c4da338291380c843d33ca8e10bcf8f49b48b33e6931700c299cd3376e74bfe4" + }, + { + "world": 107260711, + "initialization": 107260721, + "stream_seed": 107260731, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 126967, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 126967, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "confirmation", + "memory_arm": "shared_detached", + "window": 2, + "name": "w107260711-shared_detached-r4", + "job_type": "training", + "matched_compute_step": 126967, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35519938560, + "initial_model_sha256": "2d13e53d5f40d1a853118d004878c4f3978af8eebf3f685a777dd788cc825b5a", + "parameters": 1011072, + "data_sha256": "c4da338291380c843d33ca8e10bcf8f49b48b33e6931700c299cd3376e74bfe4" + }, + { + "world": 107260712, + "initialization": 107260721, + "stream_seed": 107260731, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "w107260712-local-r4", + "job_type": "training", + "matched_compute_step": 128000, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "2d13e53d5f40d1a853118d004878c4f3978af8eebf3f685a777dd788cc825b5a", + "parameters": 1011072, + "data_sha256": "ca65e732832b5728534b0a5a8c4f3e0fc89215ed1a4c84fcbe04401e3523312c" + }, + { + "world": 107260712, + "initialization": 107260721, + "stream_seed": 107260731, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 126967, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 126967, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "w107260712-shared_full-r4", + "job_type": "training", + "matched_compute_step": 126967, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35519938560, + "initial_model_sha256": "2d13e53d5f40d1a853118d004878c4f3978af8eebf3f685a777dd788cc825b5a", + "parameters": 1011072, + "data_sha256": "ca65e732832b5728534b0a5a8c4f3e0fc89215ed1a4c84fcbe04401e3523312c" + }, + { + "world": 107260712, + "initialization": 107260721, + "stream_seed": 107260731, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 126967, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 126967, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "confirmation", + "memory_arm": "shared_window", + "window": 2, + "name": "w107260712-shared_window-r4", + "job_type": "training", + "matched_compute_step": 126967, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35519938560, + "initial_model_sha256": "2d13e53d5f40d1a853118d004878c4f3978af8eebf3f685a777dd788cc825b5a", + "parameters": 1011072, + "data_sha256": "ca65e732832b5728534b0a5a8c4f3e0fc89215ed1a4c84fcbe04401e3523312c" + }, + { + "world": 107260712, + "initialization": 107260721, + "stream_seed": 107260731, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 126967, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 126967, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "confirmation", + "memory_arm": "shared_detached", + "window": 2, + "name": "w107260712-shared_detached-r4", + "job_type": "training", + "matched_compute_step": 126967, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35519938560, + "initial_model_sha256": "2d13e53d5f40d1a853118d004878c4f3978af8eebf3f685a777dd788cc825b5a", + "parameters": 1011072, + "data_sha256": "ca65e732832b5728534b0a5a8c4f3e0fc89215ed1a4c84fcbe04401e3523312c" + }, + { + "world": 107260713, + "initialization": 107260721, + "stream_seed": 107260731, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "w107260713-local-r4", + "job_type": "training", + "matched_compute_step": 128000, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "2d13e53d5f40d1a853118d004878c4f3978af8eebf3f685a777dd788cc825b5a", + "parameters": 1011072, + "data_sha256": "e0f9372d9b2c8054330ca38cb6e2cb3f35e4a2fca460f8620d03f8bfd4be6e98" + }, + { + "world": 107260713, + "initialization": 107260721, + "stream_seed": 107260731, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 126967, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 126967, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "w107260713-shared_full-r4", + "job_type": "training", + "matched_compute_step": 126967, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35519938560, + "initial_model_sha256": "2d13e53d5f40d1a853118d004878c4f3978af8eebf3f685a777dd788cc825b5a", + "parameters": 1011072, + "data_sha256": "e0f9372d9b2c8054330ca38cb6e2cb3f35e4a2fca460f8620d03f8bfd4be6e98" + }, + { + "world": 107260713, + "initialization": 107260721, + "stream_seed": 107260731, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 126967, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 126967, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "confirmation", + "memory_arm": "shared_window", + "window": 2, + "name": "w107260713-shared_window-r4", + "job_type": "training", + "matched_compute_step": 126967, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35519938560, + "initial_model_sha256": "2d13e53d5f40d1a853118d004878c4f3978af8eebf3f685a777dd788cc825b5a", + "parameters": 1011072, + "data_sha256": "e0f9372d9b2c8054330ca38cb6e2cb3f35e4a2fca460f8620d03f8bfd4be6e98" + }, + { + "world": 107260713, + "initialization": 107260721, + "stream_seed": 107260731, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 126967, + 128000 + ], + "repeat_nodes": [ + 128000 + ], + "checkpoint_nodes": [ + 0, + 32000, + 126967, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 4, + 8 + ], + "phase": "confirmation", + "memory_arm": "shared_detached", + "window": 2, + "name": "w107260713-shared_detached-r4", + "job_type": "training", + "matched_compute_step": 126967, + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35519938560, + "initial_model_sha256": "2d13e53d5f40d1a853118d004878c4f3978af8eebf3f685a777dd788cc825b5a", + "parameters": 1011072, + "data_sha256": "e0f9372d9b2c8054330ca38cb6e2cb3f35e4a2fca460f8620d03f8bfd4be6e98" + } + ], + "editing_specs": [ + { + "name": "edit-w730011-local-r4", + "job_type": "editing", + "phase": "development", + "world": 730011, + "memory_arm": "local", + "parent_name": "w730011-local-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w730011-local-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 29, + 13, + 1100 + ], + "new_fact": [ + 29, + 13, + 1078 + ], + "replay_indices": [ + 7, + 24, + 28, + 30, + 63, + 79, + 85, + 106, + 135, + 193, + 205, + 234, + 275, + 328, + 361, + 387, + 505, + 508, + 540, + 552, + 641, + 652, + 703, + 730, + 740, + 756, + 813, + 860, + 881, + 922, + 954, + 983 + ], + "affected_untrained_n": { + "D_first_familiar": 2, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 2, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 2 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1124 + ], + "new_fact": [ + 89, + 16, + 1130 + ], + "replay_indices": [ + 128, + 147, + 166, + 168, + 200, + 206, + 207, + 222, + 236, + 281, + 332, + 363, + 367, + 415, + 456, + 462, + 560, + 608, + 633, + 644, + 705, + 730, + 733, + 765, + 773, + 783, + 849, + 915, + 918, + 967, + 985, + 1006 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1083, + 19, + 1645 + ], + "new_fact": [ + 1083, + 19, + 1684 + ], + "replay_indices": [ + 16, + 65, + 165, + 176, + 227, + 296, + 375, + 394, + 416, + 539, + 556, + 578, + 629, + 633, + 647, + 668, + 678, + 694, + 716, + 757, + 761, + 787, + 794, + 824, + 825, + 838, + 859, + 879, + 914, + 933, + 964, + 993 + ], + "affected_untrained_n": { + "D_second_familiar": 2, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 2, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1136, + 19, + 1560 + ], + "new_fact": [ + 1136, + 19, + 1559 + ], + "replay_indices": [ + 12, + 74, + 89, + 112, + 123, + 173, + 272, + 295, + 299, + 315, + 347, + 378, + 416, + 521, + 528, + 535, + 547, + 589, + 599, + 654, + 691, + 760, + 777, + 778, + 782, + 787, + 803, + 823, + 875, + 951, + 1021, + 1022 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 7, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 179, + "eligible_addresses": 179, + "eligible_replacements": 11208, + "untrained_queries": 261 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 168, + "eligible_addresses": 168, + "eligible_replacements": 20664, + "untrained_queries": 261 + }, + "second_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 15744, + "untrained_queries": 512 + } + }, + "case_sha256": "af900cf5af10eba236deeb41354138e08551bb9054df621114b8481815eab409" + }, + { + "name": "edit-w730011-shared_full-r4", + "job_type": "editing", + "phase": "development", + "world": 730011, + "memory_arm": "shared_full", + "parent_name": "w730011-shared_full-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w730011-shared_full-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 29, + 13, + 1100 + ], + "new_fact": [ + 29, + 13, + 1078 + ], + "replay_indices": [ + 7, + 24, + 28, + 30, + 63, + 79, + 85, + 106, + 135, + 193, + 205, + 234, + 275, + 328, + 361, + 387, + 505, + 508, + 540, + 552, + 641, + 652, + 703, + 730, + 740, + 756, + 813, + 860, + 881, + 922, + 954, + 983 + ], + "affected_untrained_n": { + "D_first_familiar": 2, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 2, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 2 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1124 + ], + "new_fact": [ + 89, + 16, + 1130 + ], + "replay_indices": [ + 128, + 147, + 166, + 168, + 200, + 206, + 207, + 222, + 236, + 281, + 332, + 363, + 367, + 415, + 456, + 462, + 560, + 608, + 633, + 644, + 705, + 730, + 733, + 765, + 773, + 783, + 849, + 915, + 918, + 967, + 985, + 1006 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1083, + 19, + 1645 + ], + "new_fact": [ + 1083, + 19, + 1684 + ], + "replay_indices": [ + 16, + 65, + 165, + 176, + 227, + 296, + 375, + 394, + 416, + 539, + 556, + 578, + 629, + 633, + 647, + 668, + 678, + 694, + 716, + 757, + 761, + 787, + 794, + 824, + 825, + 838, + 859, + 879, + 914, + 933, + 964, + 993 + ], + "affected_untrained_n": { + "D_second_familiar": 2, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 2, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1136, + 19, + 1560 + ], + "new_fact": [ + 1136, + 19, + 1559 + ], + "replay_indices": [ + 12, + 74, + 89, + 112, + 123, + 173, + 272, + 295, + 299, + 315, + 347, + 378, + 416, + 521, + 528, + 535, + 547, + 589, + 599, + 654, + 691, + 760, + 777, + 778, + 782, + 787, + 803, + 823, + 875, + 951, + 1021, + 1022 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 7, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 179, + "eligible_addresses": 179, + "eligible_replacements": 11208, + "untrained_queries": 261 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 168, + "eligible_addresses": 168, + "eligible_replacements": 20664, + "untrained_queries": 261 + }, + "second_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 15744, + "untrained_queries": 512 + } + }, + "case_sha256": "af900cf5af10eba236deeb41354138e08551bb9054df621114b8481815eab409" + }, + { + "name": "edit-w730011-shared_window-r4", + "job_type": "editing", + "phase": "development", + "world": 730011, + "memory_arm": "shared_window", + "parent_name": "w730011-shared_window-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w730011-shared_window-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 29, + 13, + 1100 + ], + "new_fact": [ + 29, + 13, + 1078 + ], + "replay_indices": [ + 7, + 24, + 28, + 30, + 63, + 79, + 85, + 106, + 135, + 193, + 205, + 234, + 275, + 328, + 361, + 387, + 505, + 508, + 540, + 552, + 641, + 652, + 703, + 730, + 740, + 756, + 813, + 860, + 881, + 922, + 954, + 983 + ], + "affected_untrained_n": { + "D_first_familiar": 2, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 2, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 2 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1124 + ], + "new_fact": [ + 89, + 16, + 1130 + ], + "replay_indices": [ + 128, + 147, + 166, + 168, + 200, + 206, + 207, + 222, + 236, + 281, + 332, + 363, + 367, + 415, + 456, + 462, + 560, + 608, + 633, + 644, + 705, + 730, + 733, + 765, + 773, + 783, + 849, + 915, + 918, + 967, + 985, + 1006 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1083, + 19, + 1645 + ], + "new_fact": [ + 1083, + 19, + 1684 + ], + "replay_indices": [ + 16, + 65, + 165, + 176, + 227, + 296, + 375, + 394, + 416, + 539, + 556, + 578, + 629, + 633, + 647, + 668, + 678, + 694, + 716, + 757, + 761, + 787, + 794, + 824, + 825, + 838, + 859, + 879, + 914, + 933, + 964, + 993 + ], + "affected_untrained_n": { + "D_second_familiar": 2, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 2, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1136, + 19, + 1560 + ], + "new_fact": [ + 1136, + 19, + 1559 + ], + "replay_indices": [ + 12, + 74, + 89, + 112, + 123, + 173, + 272, + 295, + 299, + 315, + 347, + 378, + 416, + 521, + 528, + 535, + 547, + 589, + 599, + 654, + 691, + 760, + 777, + 778, + 782, + 787, + 803, + 823, + 875, + 951, + 1021, + 1022 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 7, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 179, + "eligible_addresses": 179, + "eligible_replacements": 11208, + "untrained_queries": 261 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 168, + "eligible_addresses": 168, + "eligible_replacements": 20664, + "untrained_queries": 261 + }, + "second_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 15744, + "untrained_queries": 512 + } + }, + "case_sha256": "af900cf5af10eba236deeb41354138e08551bb9054df621114b8481815eab409" + }, + { + "name": "edit-w730011-shared_detached-r4", + "job_type": "editing", + "phase": "development", + "world": 730011, + "memory_arm": "shared_detached", + "parent_name": "w730011-shared_detached-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w730011-shared_detached-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 29, + 13, + 1100 + ], + "new_fact": [ + 29, + 13, + 1078 + ], + "replay_indices": [ + 7, + 24, + 28, + 30, + 63, + 79, + 85, + 106, + 135, + 193, + 205, + 234, + 275, + 328, + 361, + 387, + 505, + 508, + 540, + 552, + 641, + 652, + 703, + 730, + 740, + 756, + 813, + 860, + 881, + 922, + 954, + 983 + ], + "affected_untrained_n": { + "D_first_familiar": 2, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 2, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 2 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1124 + ], + "new_fact": [ + 89, + 16, + 1130 + ], + "replay_indices": [ + 128, + 147, + 166, + 168, + 200, + 206, + 207, + 222, + 236, + 281, + 332, + 363, + 367, + 415, + 456, + 462, + 560, + 608, + 633, + 644, + 705, + 730, + 733, + 765, + 773, + 783, + 849, + 915, + 918, + 967, + 985, + 1006 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1083, + 19, + 1645 + ], + "new_fact": [ + 1083, + 19, + 1684 + ], + "replay_indices": [ + 16, + 65, + 165, + 176, + 227, + 296, + 375, + 394, + 416, + 539, + 556, + 578, + 629, + 633, + 647, + 668, + 678, + 694, + 716, + 757, + 761, + 787, + 794, + 824, + 825, + 838, + 859, + 879, + 914, + 933, + 964, + 993 + ], + "affected_untrained_n": { + "D_second_familiar": 2, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 2, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1136, + 19, + 1560 + ], + "new_fact": [ + 1136, + 19, + 1559 + ], + "replay_indices": [ + 12, + 74, + 89, + 112, + 123, + 173, + 272, + 295, + 299, + 315, + 347, + 378, + 416, + 521, + 528, + 535, + 547, + 589, + 599, + 654, + 691, + 760, + 777, + 778, + 782, + 787, + 803, + 823, + 875, + 951, + 1021, + 1022 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 7, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 179, + "eligible_addresses": 179, + "eligible_replacements": 11208, + "untrained_queries": 261 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 168, + "eligible_addresses": 168, + "eligible_replacements": 20664, + "untrained_queries": 261 + }, + "second_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 15744, + "untrained_queries": 512 + } + }, + "case_sha256": "af900cf5af10eba236deeb41354138e08551bb9054df621114b8481815eab409" + }, + { + "name": "edit-w107260711-local-r4", + "job_type": "editing", + "phase": "confirmation", + "world": 107260711, + "memory_arm": "local", + "parent_name": "w107260711-local-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w107260711-local-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 65, + 13, + 1100 + ], + "new_fact": [ + 65, + 13, + 1075 + ], + "replay_indices": [ + 10, + 17, + 30, + 43, + 57, + 147, + 153, + 173, + 179, + 193, + 216, + 265, + 300, + 311, + 374, + 447, + 477, + 544, + 590, + 606, + 616, + 680, + 770, + 773, + 806, + 814, + 825, + 847, + 880, + 913, + 947, + 979 + ], + "affected_untrained_n": { + "D_first_familiar": 1, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 1, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 3 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 93, + 15, + 1139 + ], + "new_fact": [ + 93, + 15, + 1119 + ], + "replay_indices": [ + 48, + 76, + 90, + 119, + 130, + 196, + 263, + 303, + 311, + 334, + 378, + 432, + 460, + 486, + 490, + 634, + 655, + 679, + 682, + 696, + 705, + 763, + 766, + 847, + 856, + 872, + 908, + 919, + 928, + 951, + 966, + 1017 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1049, + 18, + 1597 + ], + "new_fact": [ + 1049, + 18, + 1676 + ], + "replay_indices": [ + 51, + 69, + 105, + 152, + 166, + 192, + 248, + 312, + 315, + 332, + 360, + 374, + 396, + 419, + 432, + 515, + 555, + 558, + 588, + 589, + 599, + 604, + 623, + 642, + 711, + 719, + 878, + 890, + 927, + 975, + 992, + 1012 + ], + "affected_untrained_n": { + "D_second_familiar": 1, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 1, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1110, + 19, + 1678 + ], + "new_fact": [ + 1110, + 19, + 1584 + ], + "replay_indices": [ + 1, + 41, + 63, + 65, + 142, + 164, + 207, + 246, + 338, + 460, + 469, + 473, + 543, + 571, + 575, + 578, + 654, + 660, + 735, + 756, + 783, + 796, + 859, + 866, + 869, + 873, + 895, + 915, + 931, + 946, + 953, + 1011 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 2, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 177, + "eligible_addresses": 177, + "eligible_replacements": 11081, + "untrained_queries": 258 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 156, + "eligible_addresses": 156, + "eligible_replacements": 19188, + "untrained_queries": 258 + }, + "second_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 15744, + "untrained_queries": 512 + } + }, + "case_sha256": "3cf77794bea89500570afd10c93a959667311b6da27c5aa5fed17e5e8e1fa4de" + }, + { + "name": "edit-w107260711-shared_full-r4", + "job_type": "editing", + "phase": "confirmation", + "world": 107260711, + "memory_arm": "shared_full", + "parent_name": "w107260711-shared_full-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w107260711-shared_full-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 65, + 13, + 1100 + ], + "new_fact": [ + 65, + 13, + 1075 + ], + "replay_indices": [ + 10, + 17, + 30, + 43, + 57, + 147, + 153, + 173, + 179, + 193, + 216, + 265, + 300, + 311, + 374, + 447, + 477, + 544, + 590, + 606, + 616, + 680, + 770, + 773, + 806, + 814, + 825, + 847, + 880, + 913, + 947, + 979 + ], + "affected_untrained_n": { + "D_first_familiar": 1, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 1, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 3 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 93, + 15, + 1139 + ], + "new_fact": [ + 93, + 15, + 1119 + ], + "replay_indices": [ + 48, + 76, + 90, + 119, + 130, + 196, + 263, + 303, + 311, + 334, + 378, + 432, + 460, + 486, + 490, + 634, + 655, + 679, + 682, + 696, + 705, + 763, + 766, + 847, + 856, + 872, + 908, + 919, + 928, + 951, + 966, + 1017 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1049, + 18, + 1597 + ], + "new_fact": [ + 1049, + 18, + 1676 + ], + "replay_indices": [ + 51, + 69, + 105, + 152, + 166, + 192, + 248, + 312, + 315, + 332, + 360, + 374, + 396, + 419, + 432, + 515, + 555, + 558, + 588, + 589, + 599, + 604, + 623, + 642, + 711, + 719, + 878, + 890, + 927, + 975, + 992, + 1012 + ], + "affected_untrained_n": { + "D_second_familiar": 1, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 1, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1110, + 19, + 1678 + ], + "new_fact": [ + 1110, + 19, + 1584 + ], + "replay_indices": [ + 1, + 41, + 63, + 65, + 142, + 164, + 207, + 246, + 338, + 460, + 469, + 473, + 543, + 571, + 575, + 578, + 654, + 660, + 735, + 756, + 783, + 796, + 859, + 866, + 869, + 873, + 895, + 915, + 931, + 946, + 953, + 1011 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 2, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 177, + "eligible_addresses": 177, + "eligible_replacements": 11081, + "untrained_queries": 258 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 156, + "eligible_addresses": 156, + "eligible_replacements": 19188, + "untrained_queries": 258 + }, + "second_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 15744, + "untrained_queries": 512 + } + }, + "case_sha256": "3cf77794bea89500570afd10c93a959667311b6da27c5aa5fed17e5e8e1fa4de" + }, + { + "name": "edit-w107260711-shared_window-r4", + "job_type": "editing", + "phase": "confirmation", + "world": 107260711, + "memory_arm": "shared_window", + "parent_name": "w107260711-shared_window-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w107260711-shared_window-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 65, + 13, + 1100 + ], + "new_fact": [ + 65, + 13, + 1075 + ], + "replay_indices": [ + 10, + 17, + 30, + 43, + 57, + 147, + 153, + 173, + 179, + 193, + 216, + 265, + 300, + 311, + 374, + 447, + 477, + 544, + 590, + 606, + 616, + 680, + 770, + 773, + 806, + 814, + 825, + 847, + 880, + 913, + 947, + 979 + ], + "affected_untrained_n": { + "D_first_familiar": 1, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 1, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 3 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 93, + 15, + 1139 + ], + "new_fact": [ + 93, + 15, + 1119 + ], + "replay_indices": [ + 48, + 76, + 90, + 119, + 130, + 196, + 263, + 303, + 311, + 334, + 378, + 432, + 460, + 486, + 490, + 634, + 655, + 679, + 682, + 696, + 705, + 763, + 766, + 847, + 856, + 872, + 908, + 919, + 928, + 951, + 966, + 1017 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1049, + 18, + 1597 + ], + "new_fact": [ + 1049, + 18, + 1676 + ], + "replay_indices": [ + 51, + 69, + 105, + 152, + 166, + 192, + 248, + 312, + 315, + 332, + 360, + 374, + 396, + 419, + 432, + 515, + 555, + 558, + 588, + 589, + 599, + 604, + 623, + 642, + 711, + 719, + 878, + 890, + 927, + 975, + 992, + 1012 + ], + "affected_untrained_n": { + "D_second_familiar": 1, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 1, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1110, + 19, + 1678 + ], + "new_fact": [ + 1110, + 19, + 1584 + ], + "replay_indices": [ + 1, + 41, + 63, + 65, + 142, + 164, + 207, + 246, + 338, + 460, + 469, + 473, + 543, + 571, + 575, + 578, + 654, + 660, + 735, + 756, + 783, + 796, + 859, + 866, + 869, + 873, + 895, + 915, + 931, + 946, + 953, + 1011 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 2, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 177, + "eligible_addresses": 177, + "eligible_replacements": 11081, + "untrained_queries": 258 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 156, + "eligible_addresses": 156, + "eligible_replacements": 19188, + "untrained_queries": 258 + }, + "second_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 15744, + "untrained_queries": 512 + } + }, + "case_sha256": "3cf77794bea89500570afd10c93a959667311b6da27c5aa5fed17e5e8e1fa4de" + }, + { + "name": "edit-w107260711-shared_detached-r4", + "job_type": "editing", + "phase": "confirmation", + "world": 107260711, + "memory_arm": "shared_detached", + "parent_name": "w107260711-shared_detached-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w107260711-shared_detached-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 65, + 13, + 1100 + ], + "new_fact": [ + 65, + 13, + 1075 + ], + "replay_indices": [ + 10, + 17, + 30, + 43, + 57, + 147, + 153, + 173, + 179, + 193, + 216, + 265, + 300, + 311, + 374, + 447, + 477, + 544, + 590, + 606, + 616, + 680, + 770, + 773, + 806, + 814, + 825, + 847, + 880, + 913, + 947, + 979 + ], + "affected_untrained_n": { + "D_first_familiar": 1, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 1, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 3 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 93, + 15, + 1139 + ], + "new_fact": [ + 93, + 15, + 1119 + ], + "replay_indices": [ + 48, + 76, + 90, + 119, + 130, + 196, + 263, + 303, + 311, + 334, + 378, + 432, + 460, + 486, + 490, + 634, + 655, + 679, + 682, + 696, + 705, + 763, + 766, + 847, + 856, + 872, + 908, + 919, + 928, + 951, + 966, + 1017 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1049, + 18, + 1597 + ], + "new_fact": [ + 1049, + 18, + 1676 + ], + "replay_indices": [ + 51, + 69, + 105, + 152, + 166, + 192, + 248, + 312, + 315, + 332, + 360, + 374, + 396, + 419, + 432, + 515, + 555, + 558, + 588, + 589, + 599, + 604, + 623, + 642, + 711, + 719, + 878, + 890, + 927, + 975, + 992, + 1012 + ], + "affected_untrained_n": { + "D_second_familiar": 1, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 1, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1110, + 19, + 1678 + ], + "new_fact": [ + 1110, + 19, + 1584 + ], + "replay_indices": [ + 1, + 41, + 63, + 65, + 142, + 164, + 207, + 246, + 338, + 460, + 469, + 473, + 543, + 571, + 575, + 578, + 654, + 660, + 735, + 756, + 783, + 796, + 859, + 866, + 869, + 873, + 895, + 915, + 931, + 946, + 953, + 1011 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 2, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 177, + "eligible_addresses": 177, + "eligible_replacements": 11081, + "untrained_queries": 258 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 156, + "eligible_addresses": 156, + "eligible_replacements": 19188, + "untrained_queries": 258 + }, + "second_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 15744, + "untrained_queries": 512 + } + }, + "case_sha256": "3cf77794bea89500570afd10c93a959667311b6da27c5aa5fed17e5e8e1fa4de" + }, + { + "name": "edit-w107260712-local-r4", + "job_type": "editing", + "phase": "confirmation", + "world": 107260712, + "memory_arm": "local", + "parent_name": "w107260712-local-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w107260712-local-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 33, + 14, + 1108 + ], + "new_fact": [ + 33, + 14, + 1104 + ], + "replay_indices": [ + 21, + 29, + 51, + 60, + 80, + 180, + 196, + 204, + 293, + 321, + 364, + 378, + 489, + 495, + 504, + 506, + 536, + 538, + 573, + 589, + 590, + 620, + 624, + 768, + 784, + 831, + 834, + 942, + 957, + 968, + 1009, + 1010 + ], + "affected_untrained_n": { + "D_first_familiar": 2, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 2, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 2 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 87, + 13, + 1117 + ], + "new_fact": [ + 87, + 13, + 1121 + ], + "replay_indices": [ + 0, + 69, + 78, + 90, + 102, + 117, + 145, + 179, + 245, + 270, + 284, + 311, + 347, + 379, + 401, + 423, + 455, + 472, + 503, + 509, + 540, + 568, + 579, + 586, + 598, + 599, + 631, + 655, + 702, + 714, + 828, + 933 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1075, + 17, + 1647 + ], + "new_fact": [ + 1075, + 17, + 1628 + ], + "replay_indices": [ + 32, + 38, + 56, + 57, + 110, + 243, + 268, + 284, + 311, + 341, + 364, + 401, + 412, + 415, + 486, + 535, + 547, + 607, + 612, + 631, + 659, + 667, + 679, + 704, + 709, + 754, + 772, + 796, + 851, + 950, + 953, + 966 + ], + "affected_untrained_n": { + "D_second_familiar": 2, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 2, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1114, + 19, + 1665 + ], + "new_fact": [ + 1114, + 19, + 1585 + ], + "replay_indices": [ + 21, + 70, + 124, + 159, + 177, + 231, + 267, + 340, + 359, + 372, + 405, + 432, + 437, + 464, + 476, + 571, + 576, + 603, + 677, + 696, + 752, + 771, + 776, + 815, + 839, + 868, + 906, + 911, + 938, + 954, + 956, + 977 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 2, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 172, + "eligible_addresses": 172, + "eligible_replacements": 10801, + "untrained_queries": 262 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 173, + "eligible_addresses": 173, + "eligible_replacements": 21625, + "untrained_queries": 262 + }, + "second_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 16000, + "untrained_queries": 512 + } + }, + "case_sha256": "f9a159797e1297b352228f79ceb2638bfda24143553a6fd1a808de10c28f7f58" + }, + { + "name": "edit-w107260712-shared_full-r4", + "job_type": "editing", + "phase": "confirmation", + "world": 107260712, + "memory_arm": "shared_full", + "parent_name": "w107260712-shared_full-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w107260712-shared_full-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 33, + 14, + 1108 + ], + "new_fact": [ + 33, + 14, + 1104 + ], + "replay_indices": [ + 21, + 29, + 51, + 60, + 80, + 180, + 196, + 204, + 293, + 321, + 364, + 378, + 489, + 495, + 504, + 506, + 536, + 538, + 573, + 589, + 590, + 620, + 624, + 768, + 784, + 831, + 834, + 942, + 957, + 968, + 1009, + 1010 + ], + "affected_untrained_n": { + "D_first_familiar": 2, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 2, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 2 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 87, + 13, + 1117 + ], + "new_fact": [ + 87, + 13, + 1121 + ], + "replay_indices": [ + 0, + 69, + 78, + 90, + 102, + 117, + 145, + 179, + 245, + 270, + 284, + 311, + 347, + 379, + 401, + 423, + 455, + 472, + 503, + 509, + 540, + 568, + 579, + 586, + 598, + 599, + 631, + 655, + 702, + 714, + 828, + 933 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1075, + 17, + 1647 + ], + "new_fact": [ + 1075, + 17, + 1628 + ], + "replay_indices": [ + 32, + 38, + 56, + 57, + 110, + 243, + 268, + 284, + 311, + 341, + 364, + 401, + 412, + 415, + 486, + 535, + 547, + 607, + 612, + 631, + 659, + 667, + 679, + 704, + 709, + 754, + 772, + 796, + 851, + 950, + 953, + 966 + ], + "affected_untrained_n": { + "D_second_familiar": 2, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 2, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1114, + 19, + 1665 + ], + "new_fact": [ + 1114, + 19, + 1585 + ], + "replay_indices": [ + 21, + 70, + 124, + 159, + 177, + 231, + 267, + 340, + 359, + 372, + 405, + 432, + 437, + 464, + 476, + 571, + 576, + 603, + 677, + 696, + 752, + 771, + 776, + 815, + 839, + 868, + 906, + 911, + 938, + 954, + 956, + 977 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 2, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 172, + "eligible_addresses": 172, + "eligible_replacements": 10801, + "untrained_queries": 262 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 173, + "eligible_addresses": 173, + "eligible_replacements": 21625, + "untrained_queries": 262 + }, + "second_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 16000, + "untrained_queries": 512 + } + }, + "case_sha256": "f9a159797e1297b352228f79ceb2638bfda24143553a6fd1a808de10c28f7f58" + }, + { + "name": "edit-w107260712-shared_window-r4", + "job_type": "editing", + "phase": "confirmation", + "world": 107260712, + "memory_arm": "shared_window", + "parent_name": "w107260712-shared_window-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w107260712-shared_window-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 33, + 14, + 1108 + ], + "new_fact": [ + 33, + 14, + 1104 + ], + "replay_indices": [ + 21, + 29, + 51, + 60, + 80, + 180, + 196, + 204, + 293, + 321, + 364, + 378, + 489, + 495, + 504, + 506, + 536, + 538, + 573, + 589, + 590, + 620, + 624, + 768, + 784, + 831, + 834, + 942, + 957, + 968, + 1009, + 1010 + ], + "affected_untrained_n": { + "D_first_familiar": 2, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 2, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 2 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 87, + 13, + 1117 + ], + "new_fact": [ + 87, + 13, + 1121 + ], + "replay_indices": [ + 0, + 69, + 78, + 90, + 102, + 117, + 145, + 179, + 245, + 270, + 284, + 311, + 347, + 379, + 401, + 423, + 455, + 472, + 503, + 509, + 540, + 568, + 579, + 586, + 598, + 599, + 631, + 655, + 702, + 714, + 828, + 933 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1075, + 17, + 1647 + ], + "new_fact": [ + 1075, + 17, + 1628 + ], + "replay_indices": [ + 32, + 38, + 56, + 57, + 110, + 243, + 268, + 284, + 311, + 341, + 364, + 401, + 412, + 415, + 486, + 535, + 547, + 607, + 612, + 631, + 659, + 667, + 679, + 704, + 709, + 754, + 772, + 796, + 851, + 950, + 953, + 966 + ], + "affected_untrained_n": { + "D_second_familiar": 2, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 2, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1114, + 19, + 1665 + ], + "new_fact": [ + 1114, + 19, + 1585 + ], + "replay_indices": [ + 21, + 70, + 124, + 159, + 177, + 231, + 267, + 340, + 359, + 372, + 405, + 432, + 437, + 464, + 476, + 571, + 576, + 603, + 677, + 696, + 752, + 771, + 776, + 815, + 839, + 868, + 906, + 911, + 938, + 954, + 956, + 977 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 2, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 172, + "eligible_addresses": 172, + "eligible_replacements": 10801, + "untrained_queries": 262 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 173, + "eligible_addresses": 173, + "eligible_replacements": 21625, + "untrained_queries": 262 + }, + "second_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 16000, + "untrained_queries": 512 + } + }, + "case_sha256": "f9a159797e1297b352228f79ceb2638bfda24143553a6fd1a808de10c28f7f58" + }, + { + "name": "edit-w107260712-shared_detached-r4", + "job_type": "editing", + "phase": "confirmation", + "world": 107260712, + "memory_arm": "shared_detached", + "parent_name": "w107260712-shared_detached-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w107260712-shared_detached-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 33, + 14, + 1108 + ], + "new_fact": [ + 33, + 14, + 1104 + ], + "replay_indices": [ + 21, + 29, + 51, + 60, + 80, + 180, + 196, + 204, + 293, + 321, + 364, + 378, + 489, + 495, + 504, + 506, + 536, + 538, + 573, + 589, + 590, + 620, + 624, + 768, + 784, + 831, + 834, + 942, + 957, + 968, + 1009, + 1010 + ], + "affected_untrained_n": { + "D_first_familiar": 2, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 2, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 2 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 87, + 13, + 1117 + ], + "new_fact": [ + 87, + 13, + 1121 + ], + "replay_indices": [ + 0, + 69, + 78, + 90, + 102, + 117, + 145, + 179, + 245, + 270, + 284, + 311, + 347, + 379, + 401, + 423, + 455, + 472, + 503, + 509, + 540, + 568, + 579, + 586, + 598, + 599, + 631, + 655, + 702, + 714, + 828, + 933 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1075, + 17, + 1647 + ], + "new_fact": [ + 1075, + 17, + 1628 + ], + "replay_indices": [ + 32, + 38, + 56, + 57, + 110, + 243, + 268, + 284, + 311, + 341, + 364, + 401, + 412, + 415, + 486, + 535, + 547, + 607, + 612, + 631, + 659, + 667, + 679, + 704, + 709, + 754, + 772, + 796, + 851, + 950, + 953, + 966 + ], + "affected_untrained_n": { + "D_second_familiar": 2, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 2, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1114, + 19, + 1665 + ], + "new_fact": [ + 1114, + 19, + 1585 + ], + "replay_indices": [ + 21, + 70, + 124, + 159, + 177, + 231, + 267, + 340, + 359, + 372, + 405, + 432, + 437, + 464, + 476, + 571, + 576, + 603, + 677, + 696, + 752, + 771, + 776, + 815, + 839, + 868, + 906, + 911, + 938, + 954, + 956, + 977 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 2, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 172, + "eligible_addresses": 172, + "eligible_replacements": 10801, + "untrained_queries": 262 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 173, + "eligible_addresses": 173, + "eligible_replacements": 21625, + "untrained_queries": 262 + }, + "second_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 16000, + "untrained_queries": 512 + } + }, + "case_sha256": "f9a159797e1297b352228f79ceb2638bfda24143553a6fd1a808de10c28f7f58" + }, + { + "name": "edit-w107260713-local-r4", + "job_type": "editing", + "phase": "confirmation", + "world": 107260713, + "memory_arm": "local", + "parent_name": "w107260713-local-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w107260713-local-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 75, + 16, + 1105 + ], + "new_fact": [ + 75, + 16, + 1060 + ], + "replay_indices": [ + 2, + 7, + 32, + 174, + 205, + 278, + 298, + 367, + 407, + 509, + 518, + 557, + 584, + 597, + 599, + 618, + 630, + 652, + 673, + 724, + 728, + 732, + 777, + 828, + 836, + 883, + 910, + 925, + 930, + 946, + 976, + 990 + ], + "affected_untrained_n": { + "D_first_familiar": 1, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 1, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 3 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 99, + 13, + 1124 + ], + "new_fact": [ + 99, + 13, + 1127 + ], + "replay_indices": [ + 15, + 24, + 28, + 48, + 95, + 190, + 192, + 195, + 210, + 259, + 310, + 325, + 348, + 353, + 357, + 385, + 408, + 445, + 476, + 500, + 543, + 589, + 597, + 682, + 701, + 719, + 768, + 779, + 853, + 907, + 978, + 995 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1085, + 17, + 1669 + ], + "new_fact": [ + 1085, + 17, + 1597 + ], + "replay_indices": [ + 0, + 20, + 74, + 78, + 164, + 293, + 315, + 335, + 348, + 408, + 418, + 426, + 429, + 513, + 517, + 553, + 608, + 620, + 645, + 648, + 661, + 712, + 717, + 731, + 770, + 781, + 867, + 923, + 931, + 957, + 976, + 1003 + ], + "affected_untrained_n": { + "D_second_familiar": 2, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 2, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 4 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1138, + 20, + 1667 + ], + "new_fact": [ + 1138, + 20, + 1645 + ], + "replay_indices": [ + 19, + 42, + 122, + 164, + 173, + 190, + 198, + 229, + 230, + 235, + 320, + 345, + 373, + 383, + 409, + 416, + 536, + 567, + 631, + 646, + 665, + 708, + 726, + 728, + 780, + 842, + 880, + 882, + 886, + 907, + 954, + 979 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 1, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 175, + "eligible_addresses": 175, + "eligible_replacements": 10975, + "untrained_queries": 260 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 172, + "eligible_addresses": 172, + "eligible_replacements": 21844, + "untrained_queries": 260 + }, + "second_strict": { + "candidate_addresses": 124, + "eligible_addresses": 124, + "eligible_replacements": 15748, + "untrained_queries": 512 + } + }, + "case_sha256": "d731bc450ab0bfbb8bf5cc2f60c1b8b2e87e0e4c8853e7a63fe89a45ca27e5d6" + }, + { + "name": "edit-w107260713-shared_full-r4", + "job_type": "editing", + "phase": "confirmation", + "world": 107260713, + "memory_arm": "shared_full", + "parent_name": "w107260713-shared_full-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w107260713-shared_full-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 75, + 16, + 1105 + ], + "new_fact": [ + 75, + 16, + 1060 + ], + "replay_indices": [ + 2, + 7, + 32, + 174, + 205, + 278, + 298, + 367, + 407, + 509, + 518, + 557, + 584, + 597, + 599, + 618, + 630, + 652, + 673, + 724, + 728, + 732, + 777, + 828, + 836, + 883, + 910, + 925, + 930, + 946, + 976, + 990 + ], + "affected_untrained_n": { + "D_first_familiar": 1, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 1, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 3 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 99, + 13, + 1124 + ], + "new_fact": [ + 99, + 13, + 1127 + ], + "replay_indices": [ + 15, + 24, + 28, + 48, + 95, + 190, + 192, + 195, + 210, + 259, + 310, + 325, + 348, + 353, + 357, + 385, + 408, + 445, + 476, + 500, + 543, + 589, + 597, + 682, + 701, + 719, + 768, + 779, + 853, + 907, + 978, + 995 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1085, + 17, + 1669 + ], + "new_fact": [ + 1085, + 17, + 1597 + ], + "replay_indices": [ + 0, + 20, + 74, + 78, + 164, + 293, + 315, + 335, + 348, + 408, + 418, + 426, + 429, + 513, + 517, + 553, + 608, + 620, + 645, + 648, + 661, + 712, + 717, + 731, + 770, + 781, + 867, + 923, + 931, + 957, + 976, + 1003 + ], + "affected_untrained_n": { + "D_second_familiar": 2, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 2, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 4 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1138, + 20, + 1667 + ], + "new_fact": [ + 1138, + 20, + 1645 + ], + "replay_indices": [ + 19, + 42, + 122, + 164, + 173, + 190, + 198, + 229, + 230, + 235, + 320, + 345, + 373, + 383, + 409, + 416, + 536, + 567, + 631, + 646, + 665, + 708, + 726, + 728, + 780, + 842, + 880, + 882, + 886, + 907, + 954, + 979 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 1, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 175, + "eligible_addresses": 175, + "eligible_replacements": 10975, + "untrained_queries": 260 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 172, + "eligible_addresses": 172, + "eligible_replacements": 21844, + "untrained_queries": 260 + }, + "second_strict": { + "candidate_addresses": 124, + "eligible_addresses": 124, + "eligible_replacements": 15748, + "untrained_queries": 512 + } + }, + "case_sha256": "d731bc450ab0bfbb8bf5cc2f60c1b8b2e87e0e4c8853e7a63fe89a45ca27e5d6" + }, + { + "name": "edit-w107260713-shared_window-r4", + "job_type": "editing", + "phase": "confirmation", + "world": 107260713, + "memory_arm": "shared_window", + "parent_name": "w107260713-shared_window-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w107260713-shared_window-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 75, + 16, + 1105 + ], + "new_fact": [ + 75, + 16, + 1060 + ], + "replay_indices": [ + 2, + 7, + 32, + 174, + 205, + 278, + 298, + 367, + 407, + 509, + 518, + 557, + 584, + 597, + 599, + 618, + 630, + 652, + 673, + 724, + 728, + 732, + 777, + 828, + 836, + 883, + 910, + 925, + 930, + 946, + 976, + 990 + ], + "affected_untrained_n": { + "D_first_familiar": 1, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 1, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 3 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 99, + 13, + 1124 + ], + "new_fact": [ + 99, + 13, + 1127 + ], + "replay_indices": [ + 15, + 24, + 28, + 48, + 95, + 190, + 192, + 195, + 210, + 259, + 310, + 325, + 348, + 353, + 357, + 385, + 408, + 445, + 476, + 500, + 543, + 589, + 597, + 682, + 701, + 719, + 768, + 779, + 853, + 907, + 978, + 995 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1085, + 17, + 1669 + ], + "new_fact": [ + 1085, + 17, + 1597 + ], + "replay_indices": [ + 0, + 20, + 74, + 78, + 164, + 293, + 315, + 335, + 348, + 408, + 418, + 426, + 429, + 513, + 517, + 553, + 608, + 620, + 645, + 648, + 661, + 712, + 717, + 731, + 770, + 781, + 867, + 923, + 931, + 957, + 976, + 1003 + ], + "affected_untrained_n": { + "D_second_familiar": 2, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 2, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 4 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1138, + 20, + 1667 + ], + "new_fact": [ + 1138, + 20, + 1645 + ], + "replay_indices": [ + 19, + 42, + 122, + 164, + 173, + 190, + 198, + 229, + 230, + 235, + 320, + 345, + 373, + 383, + 409, + 416, + 536, + 567, + 631, + 646, + 665, + 708, + 726, + 728, + 780, + 842, + 880, + 882, + 886, + 907, + 954, + 979 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 1, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 175, + "eligible_addresses": 175, + "eligible_replacements": 10975, + "untrained_queries": 260 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 172, + "eligible_addresses": 172, + "eligible_replacements": 21844, + "untrained_queries": 260 + }, + "second_strict": { + "candidate_addresses": 124, + "eligible_addresses": 124, + "eligible_replacements": 15748, + "untrained_queries": 512 + } + }, + "case_sha256": "d731bc450ab0bfbb8bf5cc2f60c1b8b2e87e0e4c8853e7a63fe89a45ca27e5d6" + }, + { + "name": "edit-w107260713-shared_detached-r4", + "job_type": "editing", + "phase": "confirmation", + "world": 107260713, + "memory_arm": "shared_detached", + "parent_name": "w107260713-shared_detached-r4", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w107260713-shared_detached-r4", + "candidate_seed": 107260741, + "per_cell": 1, + "replay_n": 32, + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0, + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 75, + 16, + 1105 + ], + "new_fact": [ + 75, + 16, + 1060 + ], + "replay_indices": [ + 2, + 7, + 32, + 174, + 205, + 278, + 298, + 367, + 407, + 509, + 518, + 557, + 584, + 597, + 599, + 618, + 630, + 652, + 673, + 724, + 728, + 732, + 777, + 828, + 836, + 883, + 910, + 925, + 930, + 946, + 976, + 990 + ], + "affected_untrained_n": { + "D_first_familiar": 1, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 1, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 3 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 99, + 13, + 1124 + ], + "new_fact": [ + 99, + 13, + 1127 + ], + "replay_indices": [ + 15, + 24, + 28, + 48, + 95, + 190, + 192, + 195, + 210, + 259, + 310, + 325, + 348, + 353, + 357, + 385, + 408, + 445, + 476, + 500, + 543, + 589, + 597, + 682, + 701, + 719, + 768, + 779, + 853, + 907, + 978, + 995 + ], + "affected_untrained_n": { + "D_first_familiar": 0, + "S_same_answer_first_familiar": 0, + "D_first_strict": 4, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 0, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "second_familiar-00", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1085, + 17, + 1669 + ], + "new_fact": [ + 1085, + 17, + 1597 + ], + "replay_indices": [ + 0, + 20, + 74, + 78, + 164, + 293, + 315, + 335, + 348, + 408, + 418, + 426, + 429, + 513, + 517, + 553, + 608, + 620, + 645, + 648, + 661, + 712, + 717, + 731, + 770, + 781, + 867, + 923, + 931, + 957, + 976, + 1003 + ], + "affected_untrained_n": { + "D_second_familiar": 2, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 2, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 4 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1138, + 20, + 1667 + ], + "new_fact": [ + 1138, + 20, + 1645 + ], + "replay_indices": [ + 19, + 42, + 122, + 164, + 173, + 190, + 198, + 229, + 230, + 235, + 320, + 345, + 373, + 383, + 409, + 416, + 536, + 567, + 631, + 646, + 665, + 708, + 726, + 728, + 780, + 842, + 880, + 882, + 886, + 907, + 954, + 979 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 1, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "qualification": { + "first_familiar": { + "candidate_addresses": 175, + "eligible_addresses": 175, + "eligible_replacements": 10975, + "untrained_queries": 260 + }, + "first_strict": { + "candidate_addresses": 128, + "eligible_addresses": 128, + "eligible_replacements": 3968, + "untrained_queries": 512 + }, + "second_familiar": { + "candidate_addresses": 172, + "eligible_addresses": 172, + "eligible_replacements": 21844, + "untrained_queries": 260 + }, + "second_strict": { + "candidate_addresses": 124, + "eligible_addresses": 124, + "eligible_replacements": 15748, + "untrained_queries": 512 + } + }, + "case_sha256": "d731bc450ab0bfbb8bf5cc2f60c1b8b2e87e0e4c8853e7a63fe89a45ca27e5d6" + } + ], + "gpus": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "created_utc": "2026-10-06T17:31:50.236427+00:00", + "repository": "/ossfs/workspace/llm-memory-editability", + "runtime": { + "docker_context": "lm-memory", + "image": "sha256:a994f1a1886220693eb26b7ff201147fbd4b49477d335ab2707330cab771063f", + "python": "/opt/conda/bin/python", + "cpus": 2, + "memory": "12g" + }, + "maximum_run_seconds": 3600, + "maximum_edit_seconds": 900, + "maximum_engineering_seconds": 400, + "maximum_gpu_hours": 25, + "updates": 2560000, + "edit_updates": 65536, + "historical_source_differences": [] +} diff --git a/docs/development-artifacts/shared-cache-branch-v1/postprocessing-source/analyze_shared_cache_branch.py b/docs/development-artifacts/shared-cache-branch-v1/postprocessing-source/analyze_shared_cache_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..dd2c7d1bdd8e895dc40451152da643623578cb9d --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/postprocessing-source/analyze_shared_cache_branch.py @@ -0,0 +1,148 @@ +"""Summarize fixed comparisons after the registered matrix and audits finish.""" + +import json +from pathlib import Path + +import numpy as np + +from llm_memory_editability.grok_depth import write_json + +ROOT = Path("/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1") +ARMS = ("local", "shared_full", "shared_window", "shared_detached") + + +def main(): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + summary = json.loads((ROOT / "report/summary.json").read_text()) + assert summary["passed"] and not summary["missing"] + rows = [r for r in summary["endpoints"] if r["phase"] == "confirmation"] + aggregate, edit_rows, intervention_rows = [], [], [] + for arm in ARMS: + selected = [r for r in rows if r["arm"] == arm] + aggregate.append( + dict( + arm=arm, + worlds=3, + **{ + key + "_mean": float(np.mean([r[key] for r in selected])) + for key in ["atomic", "train", "familiar", "strict", "two_calls"] + }, + ) + ) + for stratum in ["familiar", "strict"]: + for role in ["first", "second"]: + selected = [ + r + for r in summary["edit_branches"] + if r["phase"] == "confirmation" + and r["memory_arm"] == arm + and r["stratum"] == stratum + and r["role"] == role + ] + edited = [r for r in selected if r["arm"] == "edit"] + sham = [r for r in selected if r["arm"] == "sham"] + assert len(edited) == len(sham) == 3 + key = f"D_{role}_{stratum}" + edit_rows.append( + dict( + memory_arm=arm, + role=role, + stratum=stratum, + cases=3, + E_new=float(np.mean([r["metrics"]["E_new"]["accuracy"] for r in edited])), + D_new=float(np.mean([r["metrics"][key]["accuracy"] for r in edited])), + D_sham=float(np.mean([r["metrics"][key]["accuracy"] for r in sham])), + D_old=float( + np.mean([r["metrics"][key]["old_answer_accuracy"] for r in edited]) + ), + prerequisite_coverage=float( + np.mean( + [r["metrics"][key]["operation_correct_coverage"] for r in edited] + ) + ), + U=float(np.mean([r["metrics"]["U_atomic"]["accuracy"] for r in edited])), + case_metrics=[ + dict(world=r["world"], metrics=r["metrics"][key]) for r in edited + ], + ) + ) + names = {r["name"]: r for r in rows} + for record in summary["inference_interventions"]: + if record["name"] not in names: + continue + spec = names[record["name"]] + normal = record["metrics"]["normal"] + removed = record["metrics"]["shared_off"] + folder = ROOT / "runs" / record["name"] + with ( + np.load(folder / "intervention-normal.npz") as native, + np.load(folder / "intervention-shared_off.npz") as ablated, + ): + common = native["familiar_test_coverage"] & ablated["familiar_test_coverage"] + conditional = dict( + exploratory=True, + n=int(common.sum()), + coverage=float(common.mean()), + normal=float(native["familiar_test_correct"][common].mean()) + if common.any() + else None, + shared_off=float(ablated["familiar_test_correct"][common].mean()) + if common.any() + else None, + limitation="Post-treatment common subset; does not replace full-pool scores.", + ) + intervention_rows.append( + dict( + world=spec["world"], + arm=spec["arm"], + familiar_normal=normal["familiar_test"]["accuracy"], + familiar_shared_off=removed["familiar_test"]["accuracy"], + atomic_shared_off=removed["common_atomic"]["accuracy"], + common_prerequisite_subset=conditional, + ) + ) + result = dict( + passed=True, + confirmation_means=aggregate, + edit_propagation=edit_rows, + inference_interventions=intervention_rows, + weighting="Equal worlds; graph-selected cases are not independent worlds.", + editing_gradient_limit=( + "shared_detached retains detached cache reads during editing too. " + "Its edit comparison combines learned-parent and editing-gradient differences; " + "it cannot isolate pretraining feedback alone." + ), + ) + write_json(ROOT / "report/analysis.json", result) + fig, axes = plt.subplots(1, 3, figsize=(14, 4.5)) + for ax, key in zip(axes, ["E_new", "D_new", "U"], strict=True): + for i, arm in enumerate(ARMS): + values = [ + 100 * r[key] + for r in edit_rows + if r["memory_arm"] == arm and r["stratum"] == "familiar" + ] + ax.bar(i, np.mean(values), alpha=0.65) + ax.scatter([i] * len(values), values, color="black", s=20) + ax.set( + xticks=range(4), + xticklabels=["Local", "Shared", "Window", "Detached"], + ylabel="Full generated answer (%)", + title=key, + ylim=(-2, 103), + ) + ax.grid(axis="y", alpha=0.2) + fig.suptitle("512-step local MLP edits | familiar facts | dots are first/second-role means") + fig.tight_layout() + for ext in ["png", "pdf"]: + fig.savefig(ROOT / "report" / f"edit-propagation.{ext}", dpi=180) + plt.close(fig) + print(json.dumps(result)) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/postprocessing-source/audit_shared_cache_tracking.py b/docs/development-artifacts/shared-cache-branch-v1/postprocessing-source/audit_shared_cache_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..10bf827b461144c77aaf94acc0678ff1d0034bc2 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/postprocessing-source/audit_shared_cache_tracking.py @@ -0,0 +1,45 @@ +"""Read-only verification of final W&B runs against local audited artifacts.""" + +import json +from datetime import datetime, timezone +from pathlib import Path + +import wandb + +ROOT = Path("/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1") + + +def read(path): + return json.loads(path.read_text()) + + +def main(): + state = read(ROOT / "controller-state.json") + assert state["state"] == "complete" and not state["failed"] + assert read(ROOT / "tracking-completion.json")["passed"] + api = wandb.Api(timeout=30) + records = [] + for name in state["completed"]: + local = ROOT / "runs" / name + tracking = read(ROOT / "tracking-wandb" / name / "state.json") + run = api.run(f"zhusq20/llm-memory-editability/{tracking['run_id']}") + last = read(local / "learning.json")[-1]["step"] + assert read(local / "audit.json")["passed"] + assert run.name == name and run.group == "shared-cache-branch-v1" + assert run.state == "finished", (name, run.state) + assert run.summary.get("_step") == last, (name, run.summary.get("_step"), last) + assert run.summary.get("independently_reloaded") is True + assert tracking["last_logged_step"] == last + records.append(dict(name=name, id=run.id, state=run.state, step=last, url=run.url)) + result = dict( + passed=True, + registered_runs=len(records), + runs=records, + utc=datetime.now(timezone.utc).isoformat(), + ) + (ROOT / "cloud-final-audit.json").write_text(json.dumps(result, indent=2) + "\n") + print(json.dumps({"passed": True, "runs": len(records)})) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/postprocessing-source/manifest.json b/docs/development-artifacts/shared-cache-branch-v1/postprocessing-source/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..dbf44612e3a5013b3760de5a06806dfd3257df0f --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/postprocessing-source/manifest.json @@ -0,0 +1,8 @@ +{ + "source": { + "scripts/analyze_shared_cache_branch.py": "4c5427a774f7ad683ca1c33f152e66c861c218ee03c17984848eaf2e08a9bdf6", + "scripts/audit_shared_cache_tracking.py": "f264524bd176b53bbf9345bf4cb5901dafbf7e2ba1fee1ec606c2168b1e5f48d" + }, + "created_utc": "2026-10-06T17:47:11.157448+00:00", + "scope": "Descriptive aggregation of fixed endpoints; shared-off common subset is exploratory; no model tuning." +} diff --git a/docs/development-artifacts/shared-cache-branch-v1/prelaunch-contract-audit.json b/docs/development-artifacts/shared-cache-branch-v1/prelaunch-contract-audit.json new file mode 100644 index 0000000000000000000000000000000000000000..3ae22381d0da6fe18f66154307610dacb05f7685 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/prelaunch-contract-audit.json @@ -0,0 +1,7 @@ +{ + "passed": true, + "training_runs": 20, + "editing_parents": 16, + "paired_worlds": 4, + "utc": "2026-10-06T17:32:24.102347+00:00" +} diff --git a/docs/development-artifacts/shared-cache-branch-v1/protocol.md b/docs/development-artifacts/shared-cache-branch-v1/protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..19ccb8d5c7ff352d077f7c621c3c706f01efa388 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/protocol.md @@ -0,0 +1,39 @@ +# 首轮共享 KV:组合调用与原子编辑传播 + +2026-10-07,用户明确授权开展 shared cache branch 验证。沿用本项目研究原则,先固定研究问题和关键比较,再训练、独立重载和报告全部结果。 + +## 文献与假说 + +已阅读 Monea et al., *The Surprising Effectiveness of Shared Memory in Looped Transformers*, arXiv:2610.02383v1,§3/§4/§6及附录A/C/D/E/F。复用同层首轮KV、共享前缀和本轮窗口参加一个softmax,以及训练期共享读取detach的关键比较。原论文使用Ouro归一化、长上下文自然文本预训练;本批保留既有GPT-2 pre-LN、GELU、学习位置、闭卷符号事实及全非padding词元监督,仅改变KV访问。不是原论文全配方复现。 + +主要问题:在相同参数事实、数据支持和曝光下,显式读取首轮激活是否改善熟悉事实的新组合?次要问题是严格未练习事实组合、跨R稳定性、共享反传和事实参数更新后的传播。收益不预先归因为桥实体编码、MLP独占存储或信息覆盖;cache存的是当前输入激活,非跨问题事实数据库。 + +## 固定比较与预算 + +四个臂:local(原Loop);shared_full(首轮KV+本轮完整因果KV);shared_window(首轮KV+本轮前2位置及当前位置);shared_detached(与shared_full同前向,后续共享读取detach)。每层只读取其自身首轮KV,两个KV分支均按原token位置遮蔽未来。首轮正常执行;残差持续更新;词嵌入仅入口一次;无桥标签、oracle、额外参数或跨样本cache。 + +每轮固定4层、宽128/4头,`legacy_unique`初值,dropout=0;同世界所有臂及R初始张量完全相同。沿用latent-scaling:1024/512/128实体词表、64熟悉+32严格核心实体组、低负载256个背景原子、所有可用组合支持。每批三流各64,lr=.001/wd=.01,warmup200,128k余弦至.1倍,全下一词元CE。所有原子单跳受训;严格事实从无组合练习。主终点使用各自训练R,答案、句点和EOS完整自由生成;答案分数、NLL、必要事实覆盖与自主两次调用另报。 + +开发:历史世界730011、初始化731011、样本流732011,4臂×R2/R4,共8条128k。确认:新世界107260711/12/13,共同初始化107260721、样本流107260731,固定4臂×R4,共12条128k。全部配置、世界和图选编辑案例在读取新模型结果前冻结。确认不按开发收益调参、择臂或改变预算;开发须通过工程和评分有效性检查后执行科学训练。开发均值不并入确认;世界等权,单个世界的题目或编辑不当独立世界。 + +20条新训练、2,560,000更新。每条最长3600秒,不因低分自动延长或重训。每R使用local的128k FLOPs为共同参照,保存向下取整的等矩阵计算节点。拼接KV即使有窗口仍执行2T键长的dense attention,估算包含掩码计算;detach反传用相同3×前向近似,非精确硬件FLOPs。等计算节点继承完整训练的学习率轨迹,另列解释。短序列不声称取得长上下文显存收益。 + +## 推理干预 + +全部20个终点正常和shared_off配对生成,参数不变。shared_full/shared_detached关闭后只读本轮完整KV;shared_window关闭后只读本轮窗口,不能据其下降独立判断纯共享记忆必要性。推理干预可能离开训练状态分布;结合端到端训练比较解释。保存全部逐题预测并在独立进程重载复算。另保存测试R1/2/4/8,主分数不取最高测试R。 + +## 编辑传播(固定附属比较) + +全部16个R4终点各4个图选案例:first/second × familiar/strict各1,无模型成绩筛选;同世界各臂案例、替换值和32个回放事实完全相同。在模型训练前冻结案例哈希。新桥限定同原熟悉/严格组,改写真值必须改变至少一个未训练组合答案。图选条件只保证问题有效,不要求模型预先掌握;前提分数和覆盖完整报告。 + +每个案例从共同父权重分别做edit和旧事实sham,各512更新,节点0/32/128/512;只优化第0独立块MLP全部权重/偏置(在各轮共享),Adam lr1e-4、零wd、新优化器、clip1、无dropout。监督仅目标原子的答案/句点/EOS,另加32原子对父分布KL,权重1。没有组合标签或中间桥监督。有限KL不是严格保持约束。 + +共16父权重×4案例×2臂=128编辑分支,65,536更新,每父编辑任务最长900秒。E_new/E_old、未训练下游D、训练链T、同答案S、必要后继事实、回放R、未参与回放U全部保存;新答案、旧答案滞留、条件子集及覆盖分开。cache每次前向重新计算,编辑后不复用旧参数cache;不是直接修改激活。未成功直接更新时,不归因于传播架构。固定预算主要检验本地编辑配方,不宣称最优可编辑性。全部冻结参数及父权重哈希检查,独立重载所有编辑节点。 + +## 环境与执行 + +显式使用`docker --context lm-memory`和固定镜像`sha256:a994f1a1886220693eb26b7ff201147fbd4b49477d335ab2707330cab771063f`。旧loop、容量曲线、架构、OO归因控制器complete、无活动/排队任务,Docker与nvidia-smi再次核对后使用GPU0–7。每个训练及每父编辑任务独立容器、2CPU/12GiB、只读仓库、独立tmpfs和持久结果。旧实验不修改。工程每卡FP32/BF16矩阵前后向与同步、旧逐题预测复现、最长本批R4共享窗口8步及独立重载,另做2步编辑/sham及重载;工程结果不混入科学分数。 + +理论最大GPU预算:训练20小时+编辑4小时+工程不到1小时,合计25GPU小时;单任务超时保留失败,无静默重启。训练和编辑W&B记录到`zhusq20/llm-memory-editability`、组`shared-cache-branch-v1`;记录曲线、配置、曝光、计算估算、耗时和GPU。云端异常独立记录,不把本地科学完成称为云端核验通过。 + +科学状态读取`results/shared-cache-branch-v1/controller-state.json`;启动记录为同目录`controller-process.json`。冻结入口`source/scripts/run_shared_cache_branch.py`、`frozen-config.json`及`execution-lock.json`。不重复启动已有记录。全矩阵完成后自动报告、CSV、PNG/PDF;保留负结果、失败和原始逐题预测。 diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/configs/experiment-tracking-defaults.json b/docs/development-artifacts/shared-cache-branch-v1/source/configs/experiment-tracking-defaults.json new file mode 100644 index 0000000000000000000000000000000000000000..92273f717dfdee8e79a02a1a3fd47f874f8435f8 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/configs/experiment-tracking-defaults.json @@ -0,0 +1,11 @@ +{ + "enabled": true, + "provider": "wandb", + "sdk_version": "0.30.0", + "entity": "zhusq20", + "project": "llm-memory-editability", + "mode": "online", + "poll_seconds": 15, + "system_metrics": true, + "scope": "Future experiment batches; do not attach to existing frozen runs without a request" +} diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/configs/latent-scaling-v1.json b/docs/development-artifacts/shared-cache-branch-v1/source/configs/latent-scaling-v1.json new file mode 100644 index 0000000000000000000000000000000000000000..03170963e5023ead4d1d36397c4d5f5601ee858e --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/configs/latent-scaling-v1.json @@ -0,0 +1,1437 @@ +{ + "created_utc": "2026-10-01T19:14:29.672063+00:00", + "phase": "development", + "specs": [ + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 128, + "layers": 1, + "repeats": 1, + "composition_count": 64, + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 128, + "layers": 1, + "repeats": 1, + "composition_count": 256, + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 128, + "layers": 1, + "repeats": 1, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 128, + "layers": 1, + "repeats": 2, + "composition_count": 64, + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 128, + "layers": 1, + "repeats": 2, + "composition_count": 256, + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 128, + "layers": 1, + "repeats": 2, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 128, + "layers": 1, + "repeats": 3, + "composition_count": 64, + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 128, + "layers": 1, + "repeats": 3, + "composition_count": 256, + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 128, + "layers": 1, + "repeats": 3, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 256, + "layers": 1, + "repeats": 1, + "composition_count": 64, + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 256, + "layers": 1, + "repeats": 1, + "composition_count": 256, + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 256, + "layers": 1, + "repeats": 1, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 256, + "layers": 1, + "repeats": 2, + "composition_count": 64, + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 256, + "layers": 1, + "repeats": 2, + "composition_count": 256, + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 256, + "layers": 1, + "repeats": 2, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 256, + "layers": 1, + "repeats": 3, + "composition_count": 64, + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 256, + "layers": 1, + "repeats": 3, + "composition_count": 256, + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 256, + "layers": 1, + "repeats": 3, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 128, + "layers": 2, + "repeats": 1, + "composition_count": "all", + "test_repeats": [ + 1 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 256, + "layers": 2, + "repeats": 1, + "composition_count": "all", + "test_repeats": [ + 1 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 256, + "layers": 3, + "repeats": 1, + "composition_count": "all", + "test_repeats": [ + 1 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 64, + "layers": 1, + "repeats": 2, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 128, + "layers": 1, + "repeats": 4, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + }, + { + "world": 730011, + "initialization": 731011, + "stream_seed": 732011, + "heads_n": 1024, + "bridges_n": 512, + "tails_n": 128, + "familiar_n": 64, + "strict_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "anchor_n": 32, + "heads": 4, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 128000, + "nodes": [ + 0, + 256, + 512, + 1000, + 2000, + 4000, + 8000, + 16000, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [ + 8000, + 32000, + 128000 + ], + "checkpoint_nodes": [ + 0, + 8000, + 32000, + 128000 + ], + "width": 128, + "layers": 1, + "repeats": 8, + "composition_count": "all", + "test_repeats": [ + 1, + 2, + 3, + 4, + 6, + 8 + ] + } + ], + "source": { + "src/llm_memory_editability/storage_composition.py": "fa4d8b073ecb3ac69a3204ee446a4bc1ecf0c36f9d8dd1dcd0b6835c245e4c5a", + "src/llm_memory_editability/bios_model.py": "99efb7feeeb15f33dd3f08174c1190f4aa470e3877d8ac6692b2d43fed4c5f4d", + "src/llm_memory_editability/grok_depth.py": "7d6d5af38a5dc4438b1e7ff44df8e833169d500f0d60d8933932bdb8822aca26", + "src/llm_memory_editability/grok_loop_model.py": "07e84388997a1710e5c821e54cf6d23726e4289aab178347761e060851fea6cc", + "src/llm_memory_editability/text_pretrain.py": "cd777a56ba270d3c71ed3260f68501ee0685d4cc58a4f7b952719236adf874cb", + "scripts/run_storage_composition.py": "77f936f88b6000a584b1c9c1a7a0f57e7d3882abc6c726fe4a39fd6e8740615d", + "tests/test_storage_composition.py": "bf28eedcfcd7afeed7f0dd463cf29790309cb981f645f77842c5af161d4349a1", + "src/llm_memory_editability/storage_frontier.py": "2a1adcbbb0439ed771e17090878b9f7c9861d2fef4544172a88c35bd037d4a22", + "scripts/run_storage_frontier.py": "5edd1ccb8d8f4c1085abbc572716e91dfa71eac112a17ed27985af4ce455c9c1", + "tests/test_storage_frontier.py": "ed9ffb2cb33980a38aa2e7c593b36559ea9026b4893aa4da5e3f0eab6f78fadb", + "src/llm_memory_editability/latent_scaling.py": "231050e859da58c52b9ea47d09fb5de91271df0d24cbab42dead3f911adc6119", + "scripts/run_latent_scaling.py": "77551c23127308a1976c759c4cc445e6969edd22b6ae0c9d886f56d6a385f85d", + "tests/test_latent_scaling.py": "a4c0f9a607ffe8451c4e761ddc9fac2b91d56cf7f4fe586859b173f7999bb6e1" + }, + "data_sha256": { + "64": "b567e1f3bc858bb08d0926e86efea3c2c06c109c9572b0aa58beb938650bfed5", + "256": "2b4f62629efb15596584ecd60617ea29b877807452934867a3b27e8585a4185d", + "all": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9" + }, + "composition_examples": { + "64": 64, + "256": 256, + "all": 763 + }, + "primary": "fixed-endpoint and learning curves for held-out full two-hop generation", + "secondary": "single-hop retention, train fit, strict role transfer, fixed-weight R sweep", + "unit": "one independent development world and one paired initialization", + "analysis": "Report curves in updates, supervised tokens, composition epochs and FLOPs. First train>=99%, test>=50% and test>=90% are descriptive crossing times; no forced grokking classification or model selection by best test R.", + "git_commit": "12aa41ee7ce8e61cd2a594e2a1620ce45ed5a1c9" +} diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/docs/development-artifacts/shared-cache-branch-v1/protocol.md b/docs/development-artifacts/shared-cache-branch-v1/source/docs/development-artifacts/shared-cache-branch-v1/protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..19ccb8d5c7ff352d077f7c621c3c706f01efa388 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/docs/development-artifacts/shared-cache-branch-v1/protocol.md @@ -0,0 +1,39 @@ +# 首轮共享 KV:组合调用与原子编辑传播 + +2026-10-07,用户明确授权开展 shared cache branch 验证。沿用本项目研究原则,先固定研究问题和关键比较,再训练、独立重载和报告全部结果。 + +## 文献与假说 + +已阅读 Monea et al., *The Surprising Effectiveness of Shared Memory in Looped Transformers*, arXiv:2610.02383v1,§3/§4/§6及附录A/C/D/E/F。复用同层首轮KV、共享前缀和本轮窗口参加一个softmax,以及训练期共享读取detach的关键比较。原论文使用Ouro归一化、长上下文自然文本预训练;本批保留既有GPT-2 pre-LN、GELU、学习位置、闭卷符号事实及全非padding词元监督,仅改变KV访问。不是原论文全配方复现。 + +主要问题:在相同参数事实、数据支持和曝光下,显式读取首轮激活是否改善熟悉事实的新组合?次要问题是严格未练习事实组合、跨R稳定性、共享反传和事实参数更新后的传播。收益不预先归因为桥实体编码、MLP独占存储或信息覆盖;cache存的是当前输入激活,非跨问题事实数据库。 + +## 固定比较与预算 + +四个臂:local(原Loop);shared_full(首轮KV+本轮完整因果KV);shared_window(首轮KV+本轮前2位置及当前位置);shared_detached(与shared_full同前向,后续共享读取detach)。每层只读取其自身首轮KV,两个KV分支均按原token位置遮蔽未来。首轮正常执行;残差持续更新;词嵌入仅入口一次;无桥标签、oracle、额外参数或跨样本cache。 + +每轮固定4层、宽128/4头,`legacy_unique`初值,dropout=0;同世界所有臂及R初始张量完全相同。沿用latent-scaling:1024/512/128实体词表、64熟悉+32严格核心实体组、低负载256个背景原子、所有可用组合支持。每批三流各64,lr=.001/wd=.01,warmup200,128k余弦至.1倍,全下一词元CE。所有原子单跳受训;严格事实从无组合练习。主终点使用各自训练R,答案、句点和EOS完整自由生成;答案分数、NLL、必要事实覆盖与自主两次调用另报。 + +开发:历史世界730011、初始化731011、样本流732011,4臂×R2/R4,共8条128k。确认:新世界107260711/12/13,共同初始化107260721、样本流107260731,固定4臂×R4,共12条128k。全部配置、世界和图选编辑案例在读取新模型结果前冻结。确认不按开发收益调参、择臂或改变预算;开发须通过工程和评分有效性检查后执行科学训练。开发均值不并入确认;世界等权,单个世界的题目或编辑不当独立世界。 + +20条新训练、2,560,000更新。每条最长3600秒,不因低分自动延长或重训。每R使用local的128k FLOPs为共同参照,保存向下取整的等矩阵计算节点。拼接KV即使有窗口仍执行2T键长的dense attention,估算包含掩码计算;detach反传用相同3×前向近似,非精确硬件FLOPs。等计算节点继承完整训练的学习率轨迹,另列解释。短序列不声称取得长上下文显存收益。 + +## 推理干预 + +全部20个终点正常和shared_off配对生成,参数不变。shared_full/shared_detached关闭后只读本轮完整KV;shared_window关闭后只读本轮窗口,不能据其下降独立判断纯共享记忆必要性。推理干预可能离开训练状态分布;结合端到端训练比较解释。保存全部逐题预测并在独立进程重载复算。另保存测试R1/2/4/8,主分数不取最高测试R。 + +## 编辑传播(固定附属比较) + +全部16个R4终点各4个图选案例:first/second × familiar/strict各1,无模型成绩筛选;同世界各臂案例、替换值和32个回放事实完全相同。在模型训练前冻结案例哈希。新桥限定同原熟悉/严格组,改写真值必须改变至少一个未训练组合答案。图选条件只保证问题有效,不要求模型预先掌握;前提分数和覆盖完整报告。 + +每个案例从共同父权重分别做edit和旧事实sham,各512更新,节点0/32/128/512;只优化第0独立块MLP全部权重/偏置(在各轮共享),Adam lr1e-4、零wd、新优化器、clip1、无dropout。监督仅目标原子的答案/句点/EOS,另加32原子对父分布KL,权重1。没有组合标签或中间桥监督。有限KL不是严格保持约束。 + +共16父权重×4案例×2臂=128编辑分支,65,536更新,每父编辑任务最长900秒。E_new/E_old、未训练下游D、训练链T、同答案S、必要后继事实、回放R、未参与回放U全部保存;新答案、旧答案滞留、条件子集及覆盖分开。cache每次前向重新计算,编辑后不复用旧参数cache;不是直接修改激活。未成功直接更新时,不归因于传播架构。固定预算主要检验本地编辑配方,不宣称最优可编辑性。全部冻结参数及父权重哈希检查,独立重载所有编辑节点。 + +## 环境与执行 + +显式使用`docker --context lm-memory`和固定镜像`sha256:a994f1a1886220693eb26b7ff201147fbd4b49477d335ab2707330cab771063f`。旧loop、容量曲线、架构、OO归因控制器complete、无活动/排队任务,Docker与nvidia-smi再次核对后使用GPU0–7。每个训练及每父编辑任务独立容器、2CPU/12GiB、只读仓库、独立tmpfs和持久结果。旧实验不修改。工程每卡FP32/BF16矩阵前后向与同步、旧逐题预测复现、最长本批R4共享窗口8步及独立重载,另做2步编辑/sham及重载;工程结果不混入科学分数。 + +理论最大GPU预算:训练20小时+编辑4小时+工程不到1小时,合计25GPU小时;单任务超时保留失败,无静默重启。训练和编辑W&B记录到`zhusq20/llm-memory-editability`、组`shared-cache-branch-v1`;记录曲线、配置、曝光、计算估算、耗时和GPU。云端异常独立记录,不把本地科学完成称为云端核验通过。 + +科学状态读取`results/shared-cache-branch-v1/controller-state.json`;启动记录为同目录`controller-process.json`。冻结入口`source/scripts/run_shared_cache_branch.py`、`frozen-config.json`及`execution-lock.json`。不重复启动已有记录。全矩阵完成后自动报告、CSV、PNG/PDF;保留负结果、失败和原始逐题预测。 diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/scripts/report_shared_cache_branch.py b/docs/development-artifacts/shared-cache-branch-v1/source/scripts/report_shared_cache_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..2812fc161cb389f191506495bec12880f325aae3 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/scripts/report_shared_cache_branch.py @@ -0,0 +1,244 @@ +"""Report the frozen shared-cache matrix, including negative and failed branches.""" + +import argparse +import csv +import json +from pathlib import Path + +import numpy as np + +from llm_memory_editability.grok_depth import write_json + +ROOT = Path("/ossfs/workspace/llm-memory-editability") +ARMS = ("local", "shared_full", "shared_window", "shared_detached") + + +def read(path): + return json.loads(Path(path).read_text()) + + +def report(config): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + results = ROOT / "results" / config["batch"] + output = results / "report" + output.mkdir(exist_ok=True) + records, matched, interventions, editing, missing = [], [], [], [], [] + exposures, case_hashes = {}, {} + for spec in config["specs"]: + folder = results / "runs" / spec["name"] + if not (folder / "worker-completion.json").exists(): + missing.append(spec["name"]) + continue + complete = read(folder / "complete.json") + assert read(folder / "audit.json")["passed"] + assert read(folder / "intervention-audit.json")["passed"] + assert complete["data_sha256"] == spec["data_sha256"] + assert complete["initial_model_sha256"] == spec["initial_model_sha256"] + assert complete["parameters"] == spec["parameters"] + with np.load(folder / "exposures.npz") as raw: + current = {k: raw[k].copy() for k in raw.files} + if spec["world"] in exposures: + for key in current: + np.testing.assert_array_equal(current[key], exposures[spec["world"]][key]) + exposures[spec["world"]] = current + metrics = complete["endpoint"]["metrics"] + row = dict( + name=spec["name"], + phase=spec["phase"], + world=spec["world"], + arm=spec["memory_arm"], + train_R=spec["repeats"], + parameters=complete["parameters"], + steps=spec["steps"], + flops=complete["endpoint"]["estimated_training_flops"], + training_seconds=complete["training_seconds"], + atomic=metrics["common_atomic"]["accuracy"], + train=metrics["train_composite"]["accuracy"], + familiar=metrics["familiar_test"]["accuracy"], + strict=metrics["strict_test"]["accuracy"], + coverage=metrics["familiar_test"]["atomic_correct_coverage"], + two_calls=metrics["familiar_test"]["autonomous_two_calls"], + ) + records.append(row) + node = next( + r for r in read(folder / "learning.json") if r["step"] == spec["matched_compute_step"] + ) + matched.append( + dict( + name=spec["name"], + step=node["step"], + budget=spec["reference_compute_budget"], + flops=node["estimated_training_flops"], + metrics=node["metrics"], + ) + ) + interventions.append(dict(name=spec["name"], metrics=read(folder / "interventions.json"))) + for spec in config["editing_specs"]: + folder = results / "runs" / spec["name"] + if not (folder / "worker-completion.json").exists(): + missing.append(spec["name"]) + continue + assert read(folder / "audit.json")["passed"] + manifest = read(folder / "run.json") + assert manifest["case_sha256"] == spec["case_sha256"] + if spec["world"] in case_hashes: + assert case_hashes[spec["world"]] == manifest["case_sha256"] + case_hashes[spec["world"]] = manifest["case_sha256"] + for branch in read(folder / "complete.json")["branches"]: + editing.append( + dict( + name=spec["name"], + phase=spec["phase"], + world=spec["world"], + memory_arm=spec["memory_arm"], + **branch, + ) + ) + paired = [] + for world in sorted({r["world"] for r in records}): + for repeat in sorted({r["train_R"] for r in records if r["world"] == world}): + group = {r["arm"]: r for r in records if r["world"] == world and r["train_R"] == repeat} + if not set(ARMS) <= set(group): + continue + for arm in ARMS[1:]: + paired.append( + dict( + world=world, + train_R=repeat, + arm=arm, + phase=group[arm]["phase"], + **{ + key + "_delta_pp": 100 * (group[arm][key] - group["local"][key]) + for key in ["atomic", "train", "familiar", "strict"] + }, + ) + ) + result = dict( + passed=not missing, + registered_training_runs=len(config["specs"]), + registered_edit_parents=len(config["editing_specs"]), + missing=missing, + endpoints=records, + paired_differences=paired, + matched_compute=matched, + inference_interventions=interventions, + edit_branches=editing, + independent_confirmation_worlds=3, + exposures_identical_within_world=True, + graph_edit_cases_identical_within_world=True, + limitations=[ + "Artificial relation graphs and fixed sentence templates.", + "Three confirmation worlds, one initialization per world.", + "Strict facts have no composition practice; floor effects possible.", + "Masked dense attention still executes doubled key dimensions.", + "Matched FLOPs nodes inherit the full-run learning-rate schedule.", + "Detached backward FLOPs use the same approximate convention.", + "Inference ablation may leave the learned state distribution.", + "Local MLP editing uses finite replay KL, not exact preservation.", + ], + ) + write_json(output / "summary.json", result) + if records: + with (output / "endpoints.csv").open("w") as handle: + writer = csv.DictWriter(handle, fieldnames=list(records[0])) + writer.writeheader() + writer.writerows(records) + confirmation = [r for r in records if r["phase"] == "confirmation"] + fig, axes = plt.subplots(1, 3, figsize=(14, 4.5)) + for ax, key in zip(axes, ["atomic", "familiar", "strict"], strict=True): + for i, arm in enumerate(ARMS): + values = [100 * r[key] for r in confirmation if r["arm"] == arm] + if values: + ax.bar(i, np.mean(values), alpha=0.65) + ax.scatter([i] * len(values), values, color="black", s=22) + ax.set( + xticks=range(4), + xticklabels=["Local", "Shared", "Window", "Detached"], + ylabel="Answer + punctuation + EOS (%)", + title=key, + ) + ax.grid(axis="y", alpha=0.2) + fig.suptitle("Native R=4 | fixed 128k updates | dots are independent confirmation worlds") + fig.tight_layout() + for ext in ["png", "pdf"]: + fig.savefig(output / f"confirmation.{ext}", dpi=180) + plt.close(fig) + fig, axes = plt.subplots(1, 2, figsize=(12, 4.5)) + for ax, repeat in zip(axes, [2, 4], strict=True): + for arm in ARMS: + spec = next( + s + for s in config["specs"] + if s["phase"] == "development" and s["repeats"] == repeat and s["memory_arm"] == arm + ) + path = results / "runs" / spec["name"] / "learning.json" + if path.exists(): + rows = read(path) + ax.plot( + [r["step"] for r in rows], + [100 * r["metrics"]["familiar_test"]["accuracy"] for r in rows], + label=arm, + ) + ax.set( + xlabel="Optimizer updates", + ylabel="Familiar held-out composition (%)", + title=f"Development R={repeat}", + ylim=(-2, 103), + ) + ax.grid(alpha=0.2) + ax.legend(fontsize=8) + fig.tight_layout() + for ext in ["png", "pdf"]: + fig.savefig(output / f"development-curves.{ext}", dpi=180) + plt.close(fig) + lines = [ + "# Shared cache branch: frozen comparison", + "", + f"Complete: {not missing}; missing jobs: {missing}", + "", + "All scores use native training R at fixed endpoints. " + "Development and confirmation are separate.", + "", + "| Phase | World | R | Arm | Atomic | Familiar | Strict |", + "|---|---:|---:|---|---:|---:|---:|", + ] + for r in records: + lines.append( + f"| {r['phase']} | {r['world']} | {r['train_R']} | {r['arm']} | " + f"{100 * r['atomic']:.2f}% | {100 * r['familiar']:.2f}% | " + f"{100 * r['strict']:.2f}% |" + ) + lines.extend( + [ + "", + "Editing, prerequisites, old-answer retention and unrelated facts are retained " + "in summary.json and independently reloaded per-case predictions.", + "", + *["- " + x for x in result["limitations"]], + ] + ) + (output / "report.md").write_text("\n".join(lines) + "\n") + print( + json.dumps( + { + "passed": result["passed"], + "training": len(records), + "edit_branches": len(editing), + "report": str(output), + } + ) + ) + if missing: + raise RuntimeError(f"Incomplete registered matrix: {missing}") + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path, required=True) + args = parser.parse_args() + report(read(args.config)) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/scripts/run_shared_cache_branch.py b/docs/development-artifacts/shared-cache-branch-v1/source/scripts/run_shared_cache_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..fd33eb97319d8da67952a81c5a976946e33f81fa --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/scripts/run_shared_cache_branch.py @@ -0,0 +1,713 @@ +"""Paired shared-KV training, inference ablation and atomic-edit propagation.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import json +import os +import shutil +import subprocess +import sys +import time +import traceback +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +from llm_memory_editability.grok_depth import utc, write_json + +REPOSITORY = Path("/ossfs/workspace/llm-memory-editability") +BATCH = "shared-cache-branch-v1" +ARTIFACT = REPOSITORY / "docs/development-artifacts" / BATCH +RESULTS = REPOSITORY / "results" / BATCH + + +def read(path): + return json.loads(Path(path).read_text()) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def specifications(parent): + from llm_memory_editability.grok_loop_model import flops + from llm_memory_editability.shared_cache import ARMS, construct, executed_flops + + base = next( + s + for s in parent["specs"] + if s["width"] == 128 + and s["layers"] == 1 + and s["repeats"] == 2 + and s["composition_count"] == "all" + ) + result = [] + worlds = [ + (730011, "development", [2, 4]), + (107260711, "confirmation", [4]), + (107260712, "confirmation", [4]), + (107260713, "confirmation", [4]), + ] + for world, phase, repeats in worlds: + for repeat in repeats: + for arm in ARMS: + spec = dict( + base, + layers=4, + repeats=repeat, + world=world, + phase=phase, + memory_arm=arm, + window=2, + initialization=731011 if phase == "development" else 107260721, + stream_seed=732011 if phase == "development" else 107260731, + ) + model = construct(spec, "cpu") + budget = 128000 * flops(model.config, repeat, 192, 9, output_positions=9) + per_step = executed_flops(model.config, repeat, 192, 9, arm) + matched = budget // per_step + spec.update( + name=f"w{world}-{arm}-r{repeat}", + job_type="training", + matched_compute_step=matched, + reference_compute_budget=budget, + per_step_flops=per_step, + nodes=sorted(set(base["nodes"] + [matched])), + checkpoint_nodes=sorted(set([0, 32000, 128000, matched])), + repeat_nodes=[128000], + test_repeats=[1, 2, 4, 8], + ) + result.append(spec) + return result + + +def freeze(): + from llm_memory_editability.latent_scaling import ( + build_world, + data_digest, + model_digest, + ) + from llm_memory_editability.shared_cache import construct + + destination = ARTIFACT / "source" + if destination.exists(): + raise FileExistsError(destination) + parent = read(REPOSITORY / "configs/latent-scaling-v1.json") + specs = specifications(parent) + for spec in specs: + model = construct(spec, "cpu") + spec["initial_model_sha256"] = model_digest(model) + spec["parameters"] = sum(p.numel() for p in model.parameters()) + spec["data_sha256"] = data_digest(build_world(spec)) + for world in {s["world"] for s in specs}: + paired = [s for s in specs if s["world"] == world] + assert len({s["initial_model_sha256"] for s in paired}) == 1 + assert len({s["data_sha256"] for s in paired}) == 1 + from llm_memory_editability.interface_editing import _hash_json, graph_cases + + editing = [] + for parent_spec in specs: + if parent_spec["repeats"] != 4: + continue + cases, qualification = graph_cases(parent_spec, seed=107260741, per_cell=1, replay_n=32) + editing.append( + dict( + name="edit-" + parent_spec["name"], + job_type="editing", + phase=parent_spec["phase"], + world=parent_spec["world"], + memory_arm=parent_spec["memory_arm"], + parent_name=parent_spec["name"], + parent_dir=str(RESULTS / "runs" / parent_spec["name"]), + candidate_seed=107260741, + per_cell=1, + replay_n=32, + nodes=[0, 32, 128, 512], + lr=1e-4, + replay_weight=1.0, + parameter_scope="mlp", + block_index=0, + cases=cases, + qualification=qualification, + case_sha256=_hash_json(cases), + ) + ) + prior = read( + REPOSITORY + / "results/latent-scaling-v1/w730011-i731011-d128-l1-r2-nall-s128000/complete.json" + ) + assert specs[0]["data_sha256"] == prior["data_sha256"] + paths = [ + *REPOSITORY.glob("src/llm_memory_editability/*.py"), + REPOSITORY / "scripts/run_shared_cache_branch.py", + REPOSITORY / "scripts/report_shared_cache_branch.py", + REPOSITORY / "tests/test_shared_cache.py", + REPOSITORY / "configs/latent-scaling-v1.json", + REPOSITORY / "configs/experiment-tracking-defaults.json", + ARTIFACT / "protocol.md", + ] + hashes = {} + for path in paths: + relative = path.relative_to(REPOSITORY) + target = destination / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, target) + hashes[str(relative)] = sha(target) + config = dict( + batch=BATCH, + source_root=str(destination), + source=hashes, + specs=specs, + editing_specs=editing, + gpus=list(range(8)), + created_utc=utc(), + repository=str(REPOSITORY), + runtime=read(REPOSITORY / "configs/composition-data-curves-v1.json")["runtime"], + maximum_run_seconds=3600, + maximum_edit_seconds=900, + maximum_engineering_seconds=400, + maximum_gpu_hours=25, + updates=len(specs) * 128000, + edit_updates=len(editing) * 8 * 512, + historical_source_differences=[ + p for p, h in parent["source"].items() if sha(REPOSITORY / p) != h + ], + ) + write_json(ARTIFACT / "frozen-config.json", config) + write_json( + ARTIFACT / "execution-lock.json", {"config_sha256": sha(ARTIFACT / "frozen-config.json")} + ) + print(json.dumps({"runs": len(specs), "config": str(ARTIFACT / "frozen-config.json")})) + + +def checked_config(path): + path = Path(path) + assert sha(path) == read(path.with_name("execution-lock.json"))["config_sha256"] + config = read(path) + for relative, expected in config["source"].items(): + assert sha(Path(config["source_root"]) / relative) == expected, relative + return config + + +def train_or_audit(config, name, out, audit_only=False, engineering=False): + spec = next(s for s in config["specs"] + config["editing_specs"] if s["name"] == name) + if spec["job_type"] == "editing": + from llm_memory_editability import interface_editing as editor + from llm_memory_editability.shared_cache import construct + + editor.new_model = construct + if not read(Path(spec["parent_dir"]) / "audit.json")["passed"]: + raise RuntimeError("Editing requires an independently audited parent") + if audit_only: + editor.audit(out) + else: + editor.run(spec, out) + manifest = read(out / "run.json") + assert manifest["case_sha256"] == spec["case_sha256"] + return + from llm_memory_editability.shared_cache import install_training_adapter + + latent = install_training_adapter(spec) + if engineering: + spec = dict( + spec, + steps=8, + nodes=[0, 8], + checkpoint_nodes=[0, 8], + repeat_nodes=[8], + test_repeats=[1, 2, 8], + ) + if audit_only: + latent.audit(out) + audit_interventions(spec, out) + return + initial = latent.construct(spec, "cpu") + assert latent.model_digest(initial) == spec["initial_model_sha256"] + world = latent.build_world(spec) + assert latent.data_digest(world) == spec["data_sha256"] + write_json( + out / "run.json", + dict( + spec=spec, + pid=os.getpid(), + gpu=int(os.environ["PHYSICAL_GPU"]), + world_sha256=spec["data_sha256"], + initial_model_sha256=spec["initial_model_sha256"], + parameters=spec["parameters"], + tracking_group=BATCH, + job_type="engineering" if engineering else "training", + ), + ) + latent.train(spec, out, config["source"]) + shutil.copy2(out / f"model-{spec['steps']:06d}.pt", out / "model.pt") + evaluate_interventions(spec, out) + if engineering: + from llm_memory_editability import interface_editing as editor + from llm_memory_editability.shared_cache import construct + + editor.new_model = construct + edit_spec = dict( + parent_dir=str(out), + phase="engineering", + candidate_seed=107260741, + per_cell=1, + replay_n=32, + nodes=[0, 2], + lr=1e-4, + block_index=0, + ) + editor.run(edit_spec, out / "edit-engineering") + editor.audit(out / "edit-engineering") + + +def evaluate_interventions(spec, out, audit=False): + import numpy as np + import torch + + from llm_memory_editability import latent_scaling as latent + from llm_memory_editability.shared_cache import construct + + torch.set_num_threads(1) + saved = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + model = construct(saved["spec"], "cuda:0") + model.load_state_dict(saved["model"]) + world = latent.build_world(spec) + result = {} + for condition in ["normal", "shared_off"]: + model.disable_shared = condition == "shared_off" + metrics, predictions = latent.evaluate(model, world, "low", "cuda:0") + path = out / ("intervention-" + condition + ".npz") + if audit: + expected = read(out / "interventions.json")[condition] + latent.compare_metrics(metrics, expected) + with np.load(path) as original: + latent.compare_predictions(predictions, original) + else: + result[condition] = metrics + np.savez_compressed(path, **predictions) + if not audit: + write_json(out / "interventions.json", result) + else: + write_json(out / "intervention-audit.json", dict(passed=True, conditions=2, utc=utc())) + + +def audit_interventions(spec, out): + evaluate_interventions(spec, out, audit=True) + + +def preflight(config, out): + import numpy as np + import torch + + from llm_memory_editability import latent_scaling as latent + + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + checks = {} + for dtype in (torch.float32, torch.bfloat16): + x = torch.randn(128, 128, device="cuda", dtype=dtype, requires_grad=True) + y = x @ x.T + y.float().square().mean().backward() + torch.cuda.synchronize() + assert torch.isfinite(y).all() and torch.isfinite(x.grad).all() + checks[str(dtype)] = True + from llm_memory_editability.shared_cache import construct + + spec = next(s for s in config["specs"] if s["memory_arm"] == "shared_full") + tokens = torch.tensor([[2, 3, 4, 5, 6, 7]], device="cuda:0") + changed = tokens.clone() + changed[:, 3:] = 20 + normal = construct(spec, "cuda:0") + detached = construct(dict(spec, memory_arm="shared_detached"), "cuda:0") + torch.testing.assert_close(normal(tokens), detached(tokens), rtol=0, atol=0) + torch.testing.assert_close(normal(tokens)[:, :3], normal(changed)[:, :3], rtol=0, atol=0) + normal(tokens)[:, -1].square().sum().backward() + detached(tokens)[:, -1].square().sum().backward() + assert ( + torch.linalg.vector_norm( + normal.blocks[0].attention.qkv.weight.grad + - detached.blocks[0].attention.qkv.weight.grad + ) + > 1e-5 + ) + for arm in ["shared_full", "shared_window", "shared_detached"]: + model_check = construct(dict(spec, memory_arm=arm), "cuda:0") + with torch.autocast("cuda", dtype=torch.bfloat16): + loss = model_check(tokens).float().square().mean() + loss.backward() + assert torch.isfinite(loss) + assert all(torch.isfinite(p.grad).all() for p in model_check.parameters()) + checks["shared_forward_backward_bf16"] = True + checks["causal_shared_mask_and_detach"] = True + parent = REPOSITORY / "results/latent-scaling-v1/w730011-i731011-d128-l1-r2-nall-s128000" + result = read(parent / "complete.json") + saved = torch.load(parent / "model-128000.pt", map_location="cpu", weights_only=False) + model = latent.construct(saved["spec"], "cuda:0") + assert ( + latent.model_digest(latent.construct(saved["spec"], "cpu")) + == result["initial_model_sha256"] + ) + model.load_state_dict(saved["model"]) + world = latent.build_world(saved["spec"]) + assert latent.data_digest(world) == result["data_sha256"] + metrics, pred = latent.evaluate(model, world, "low", "cuda:0") + latent.compare_metrics(metrics, result["endpoint"]["metrics"]) + with np.load(parent / "predictions-128000.npz") as original: + maximum = latent.compare_predictions(pred, original) + write_json( + out / "cuda-and-parent-check.json", + dict( + passed=True, + actual_compute=checks, + parent_predictions_exact=True, + max_nll_difference=maximum, + utc=utc(), + ), + ) + + +def worker(config, name, out, engineering): + script = Path(config["source_root"]) / "scripts/run_shared_cache_branch.py" + arguments = [ + "--config", + str(ARTIFACT / "frozen-config.json"), + "--name", + name, + "--out", + str(out), + ] + if engineering: + arguments += ["--engineering"] + started = time.monotonic() + job = next(s for s in config["specs"] + config["editing_specs"] if s["name"] == name) + budget = ( + config["maximum_engineering_seconds"] + if engineering + else config["maximum_edit_seconds"] + if job["job_type"] == "editing" + else config["maximum_run_seconds"] + ) + + def remaining(limit): + return max(1, min(limit, budget - (time.monotonic() - started))) + + try: + if engineering: + subprocess.run( + [sys.executable, str(script), "preflight", *arguments], + check=True, + timeout=remaining(300), + ) + for mode in ["train", "audit"]: + subprocess.run( + [sys.executable, "-u", str(script), mode, *arguments], + check=True, + timeout=remaining(budget if mode == "train" else 900), + ) + write_json( + out / "worker-completion.json", dict(passed=True, seconds=time.monotonic() - started) + ) + except BaseException: + write_json(out / "failure.json", dict(utc=utc(), traceback=traceback.format_exc())) + raise + + +def gpu_free(gpu): + text = subprocess.check_output( + ["nvidia-smi", "--query-gpu=index,memory.used", "--format=csv,noheader,nounits"], text=True + ) + used = {int(line.split(",")[0]): int(line.split(",")[1]) for line in text.splitlines()} + if used[gpu] > 128: + return False + for context in ["default", "lm-memory", "d157"]: + ids = subprocess.check_output( + ["docker", "--context", context, "ps", "-q"], text=True + ).split() + if not ids: + continue + for item in json.loads( + subprocess.check_output(["docker", "--context", context, "inspect", *ids], text=True) + ): + for request in item["HostConfig"].get("DeviceRequests") or []: + if request.get("Count") == -1 or str(gpu) in (request.get("DeviceIDs") or []): + return False + return True + + +def container(config, gpu, spec, engineering=False): + name = spec["name"] + out = ( + RESULTS + / ("engineering" if engineering else "runs") + / (f"gpu{gpu}" if engineering else name) + ) + out.mkdir(parents=True, exist_ok=False) + cname = f"lm-shared-cache-{'eng-' if engineering else ''}{gpu}-{name}" + cmd = [ + "docker", + "--context", + "lm-memory", + "run", + "--name", + cname, + "--label", + "project=llm-memory-editability", + "--label", + "batch=" + BATCH, + "--label", + "run=" + name, + "--network=none", + "--gpus", + f"device={gpu}", + "--cpus", + "2", + "--memory", + "12g", + "--shm-size=2g", + "--read-only", + "--tmpfs", + "/tmp:rw,size=2g", + "--mount", + f"type=bind,src={REPOSITORY},dst={REPOSITORY},readonly", + "--mount", + f"type=bind,src={out},dst={out}", + "--workdir", + str(REPOSITORY), + ] + for key, value in dict( + PHYSICAL_GPU=gpu, + PYTHONDONTWRITEBYTECODE=1, + OMP_NUM_THREADS=1, + MKL_NUM_THREADS=1, + PYTHONPATH=config["source_root"] + "/src", + XDG_CACHE_HOME="/tmp/cache", + ).items(): + cmd += ["--env", f"{key}={value}"] + cmd += [ + config["runtime"]["image"], + config["runtime"]["python"], + "-u", + config["source_root"] + "/scripts/run_shared_cache_branch.py", + "worker", + "--config", + str(ARTIFACT / "frozen-config.json"), + "--name", + name, + "--out", + str(out), + ] + if engineering: + cmd += ["--engineering"] + write_json(out / "container-command.json", dict(command=cmd, gpu=gpu, container=cname)) + log = (out / "worker.log").open("a") + process = subprocess.Popen(cmd, stdout=log, stderr=subprocess.STDOUT) + for _ in range(30): + inspect = subprocess.run( + ["docker", "--context", "lm-memory", "inspect", cname], capture_output=True, text=True + ) + if inspect.returncode == 0: + info = json.loads(inspect.stdout)[0] + if info["State"]["Pid"]: + write_json( + out / "container-runtime.json", + dict( + host_pid=info["State"]["Pid"], + physical_gpu=gpu, + image=info["Image"], + container=cname, + ), + ) + break + time.sleep(0.2) + return process, log, out, cname + + +def environment(config): + return dict( + os.environ, + PYTHONPATH=config["source_root"] + "/src", + LD_LIBRARY_PATH="/lib64" + + (":" + os.environ["LD_LIBRARY_PATH"] if os.environ.get("LD_LIBRARY_PATH") else ""), + ) + + +def controller(config): + RESULTS.mkdir(parents=True, exist_ok=True) + lock = (RESULTS / "controller.lock").open("w") + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if (RESULTS / "controller-state.json").exists(): + raise FileExistsError( + "Controller already has an execution history; do not silently restart" + ) + state = dict( + state="preflight", + started_utc=utc(), + completed=[], + failed=[], + active={}, + queued=[s["name"] for s in config["specs"] + config["editing_specs"]], + gpus=config["gpus"], + ) + write_json(RESULTS / "controller-state.json", state) + for batch in [ + "loop-block-depth-v1", + "composition-data-curves-v1", + "parametric-architecture-main-v1", + "oo-optimizer-attribution-v1", + ]: + prior = read(REPOSITORY / "results" / batch / "controller-state.json") + assert ( + prior["state"] == "complete" and not prior.get("active") and not prior.get("queued") + ), batch + assert all(gpu_free(g) for g in config["gpus"]), "Registered GPUs are not all idle" + + def check(gpu): + p, log, out, _name = container( + config, + gpu, + next( + s + for s in config["specs"] + if s["memory_arm"] == "shared_window" and s["repeats"] == 4 + ), + engineering=True, + ) + code = p.wait() + log.close() + return code == 0 and read(out / "audit.json")["passed"] + + with ThreadPoolExecutor(max_workers=8) as pool: + passed = list(pool.map(check, config["gpus"])) + write_json( + RESULTS / "preflight.json", dict(passed=all(passed), gpus=config["gpus"], checks=passed) + ) + if not all(passed): + state.update(state="finished_with_failures", failure="preflight") + write_json(RESULTS / "controller-state.json", state) + return + tracking_cmd = [ + str(REPOSITORY / ".venv-wandb/bin/python"), + "-u", + "-m", + "llm_memory_editability.curve_tracking", + "--root", + str(RESULTS), + "--runs-dir", + str(RESULTS / "runs"), + "--defaults", + config["source_root"] + "/configs/experiment-tracking-defaults.json", + ] + tracking_log = (RESULTS / "tracking.log").open("a") + tracker = subprocess.Popen( + tracking_cmd, stdout=tracking_log, stderr=subprocess.STDOUT, env=environment(config) + ) + write_json(RESULTS / "tracking-process.json", dict(pid=tracker.pid, command=tracking_cmd)) + pending, active = list(config["specs"] + config["editing_specs"]), {} + state["state"] = "running" + while pending or active: + for gpu, (p, log, out, _cname, spec) in list(active.items()): + if p.poll() is not None: + log.close() + ok = ( + p.returncode == 0 + and (out / "audit.json").exists() + and read(out / "audit.json")["passed"] + ) + state["completed" if ok else "failed"].append(spec["name"]) + write_json(out / "process-status.json", dict(returncode=p.returncode, utc=utc())) + del active[gpu] + for gpu in config["gpus"]: + if pending and gpu not in active and gpu_free(gpu): + eligible = next( + ( + s + for s in pending + if s["job_type"] == "training" or s["parent_name"] in state["completed"] + ), + None, + ) + if eligible is not None: + pending.remove(eligible) + active[gpu] = (*container(config, gpu, eligible), eligible) + blocked = [s for s in pending if s.get("parent_name") in state["failed"]] + for spec in blocked: + out = RESULTS / "runs" / spec["name"] + out.mkdir(parents=True, exist_ok=True) + write_json( + out / "failure.json", dict(reason="parent_failed", parent=spec["parent_name"]) + ) + state["failed"].append(spec["name"]) + pending.remove(spec) + state.update( + active={str(g): dict(name=v[4]["name"], container=v[3]) for g, v in active.items()}, + queued=[s["name"] for s in pending], + updated_utc=utc(), + ) + write_json(RESULTS / "controller-state.json", state) + time.sleep(5) + report_cmd = [ + sys.executable, + config["source_root"] + "/scripts/report_shared_cache_branch.py", + "--config", + str(ARTIFACT / "frozen-config.json"), + ] + report = subprocess.run(report_cmd, env=environment(config), check=False) + state.update( + state="finished_with_failures" if state["failed"] or report.returncode else "complete", + report_returncode=report.returncode, + finished_utc=utc(), + ) + write_json(RESULTS / "controller-state.json", state) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "mode", choices=["freeze", "launch", "controller", "worker", "train", "audit", "preflight"] + ) + parser.add_argument("--config", type=Path, default=ARTIFACT / "frozen-config.json") + parser.add_argument("--name") + parser.add_argument("--out", type=Path) + parser.add_argument("--engineering", action="store_true") + args = parser.parse_args() + if args.mode == "freeze": + freeze() + return + config = checked_config(args.config) + if args.mode == "launch": + RESULTS.mkdir(parents=True, exist_ok=True) + if (RESULTS / "controller-process.json").exists(): + raise FileExistsError("Existing launch record") + command = [ + sys.executable, + "-u", + config["source_root"] + "/scripts/run_shared_cache_branch.py", + "controller", + "--config", + str(args.config), + ] + with (RESULTS / "controller.log").open("a") as log: + p = subprocess.Popen( + command, + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + env=environment(config), + ) + write_json(RESULTS / "controller-process.json", dict(pid=p.pid, command=command, utc=utc())) + print(json.dumps({"pid": p.pid, "results": str(RESULTS)})) + elif args.mode == "controller": + controller(config) + elif args.mode == "worker": + worker(config, args.name, args.out, args.engineering) + elif args.mode == "preflight": + preflight(config, args.out) + else: + train_or_audit(config, args.name, args.out, args.mode == "audit", args.engineering) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/__init__.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c606cfd654948ec99bedce5244b7c6608a801a1d --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/__init__.py @@ -0,0 +1,19 @@ +"""Analytical examples for research on shared structure and editability.""" + +from .experiments import run_minimal_example +from .low_rank import ( + best_rank_approximation, + evaluate_update, + numerical_rank, + representation_gap, +) + +__version__ = "0.1.0" + +__all__ = [ + "best_rank_approximation", + "evaluate_update", + "numerical_rank", + "representation_gap", + "run_minimal_example", +] diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/__main__.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..860f4f8babf02fc2d6920b26bf4ac11a3e254766 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/__main__.py @@ -0,0 +1,5 @@ +"""Support ``python -m llm_memory_editability``.""" + +from .cli import main + +raise SystemExit(main()) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/alignment_coverage.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/alignment_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..6efacd7bf323dd87ad027292dee80a9f665032fa --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/alignment_coverage.py @@ -0,0 +1,503 @@ +"""Paired geometric-supervision coverage in the established complete GPT task. + +All arms retain full-token CE and all-example first-hop CE. Coverage changes +only a multiplicative mask on the per-example geometric objective; every arm +executes the same forward and backward operations, including the zero mask. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .latent_scaling import build_world, model_digest +from .representation_alignment import new_model +from .representation_alignment import pack_training as pack_base_training +from .storage_composition import data_digest, evaluate, file_hash +from .storage_frontier import learning_rate + +COVERAGES = ("none", "composition_only", "all_atomic_and_composition") +NORMALIZATIONS = ("selected_mean", "batch_mean") +STRATA = ("common_atomic", "train_composite", "anchor_atomic") +COMPONENTS = ( + "text_ce", + "bridge_ce", + "alignment_loss", + "alignment_all_mean", + "alignment_selected_mean", + "alignment_batch_mean", + "alignment_selected_count", + "alignment_denominator", +) + + +def make_specs(phase="development"): + """Return the proposed paired matrix without freezing files or starting jobs.""" + if phase not in ("development", "confirmation"): + raise ValueError("Phase must be development or confirmation") + worlds = [810011] if phase == "development" else [810101, 810102, 810103] + initializations = [811011] if phase == "development" else [811101, 811102] + base = { + "phase": phase, + "stream_seed": 812011 if phase == "development" else 812101, + "heads_n": 256, + "bridges_n": 128, + "tails_n": 64, + "familiar_n": 64, + "strict_n": 32, + "anchor_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "composition_count": 256, + "width": 128, + "heads": 4, + "layers": 1, + "repeats": 2, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 16000, + "nodes": [0, 256, 1000, 2000, 4000, 8000, 16000], + "bridge_weight": 0.3, + "alignment_weight": 0.3, + } + arms = ( + ("none", "none", "batch_mean"), + ("composition_batch", "composition_only", "batch_mean"), + ("composition_selected", "composition_only", "selected_mean"), + ("all_batch", "all_atomic_and_composition", "batch_mean"), + ) + return [ + { + **base, + "nodes": list(base["nodes"]), + "world": world, + "initialization": initialization, + "arm": arm, + "alignment_coverage": coverage, + "alignment_normalization": normalization, + } + for world in worlds + for initialization in initializations + for arm, coverage, normalization in arms + ] + + +def validate_spec(spec): + if spec["alignment_coverage"] not in COVERAGES: + raise ValueError(f"Unknown alignment coverage: {spec['alignment_coverage']}") + if spec["alignment_normalization"] not in NORMALIZATIONS: + raise ValueError(f"Unknown alignment normalization: {spec['alignment_normalization']}") + if spec["bridge_weight"] != 0.3: + raise ValueError("This comparison fixes all-example first-hop CE weight at 0.3") + if not np.isfinite(spec["alignment_weight"]) or spec["alignment_weight"] < 0: + raise ValueError("Alignment weight must be finite and nonnegative") + if spec["batch_size"] <= 0 or spec["batch_size"] % 3: + raise ValueError("Batch size must divide equally into the three fixed streams") + nodes = spec["nodes"] + if not nodes or nodes[0] != 0 or nodes[-1] != spec["steps"]: + raise ValueError("Nodes must include initialization and the fixed endpoint") + if nodes != sorted(set(nodes)) or any(type(n) is not int or n < 0 for n in nodes): + raise ValueError("Nodes must be strictly increasing nonnegative integer steps") + if spec["steps"] <= 0: + raise ValueError("Training needs a positive fixed step budget") + + +def pack_training(world, coverage): + """Keep base data byte-identical and append an explicit geometry mask.""" + if coverage not in COVERAGES: + raise ValueError(f"Unknown alignment coverage: {coverage}") + arrays, sizes = pack_base_training(world) + if min(sizes) <= 0: + raise ValueError("All three training strata must be nonempty") + mask = np.zeros(sum(sizes), dtype=np.float32) + if coverage == "composition_only": + mask[sizes[0] : sizes[0] + sizes[1]] = 1 + elif coverage == "all_atomic_and_composition": + mask[:] = 1 + return (*arrays, mask), sizes + + +def objective( + model, + tokens, + labels, + targets, + geometry_mask, + bridge_weight=0.3, + alignment_weight=0.3, + normalization="selected_mean", +): + """Return the training loss and named, unweighted objective components. + + selected_mean divides by selected examples (clamped to one for an empty + mask). batch_mean divides by all examples. Both reductions are always + evaluated, and mask coverage is recorded separately from loss strength. + """ + if normalization not in NORMALIZATIONS: + raise ValueError(f"Unknown alignment normalization: {normalization}") + 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() + per_example = (F.normalize(bridge, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1) + mask = geometry_mask.to(dtype=per_example.dtype) + selected_count = mask.sum() + numerator = (per_example * mask).sum() + selected_denominator = selected_count.clamp_min(1) + # Avoid creating a device scalar from host data during CUDA graph capture. + batch_denominator = torch.ones_like(selected_count) * per_example.numel() + selected_mean = numerator / selected_denominator + batch_mean = numerator / batch_denominator + use_selected = float(normalization == "selected_mean") + denominator = use_selected * selected_denominator + (1 - use_selected) * batch_denominator + alignment = numerator / denominator + parts = torch.stack( + ( + text_ce, + bridge_ce, + alignment, + per_example.mean(), + selected_mean, + batch_mean, + selected_count, + denominator, + ) + ) + return text_ce + bridge_weight * bridge_ce + alignment_weight * alignment, parts + + +class CoverageStep(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, mask = (part[self.index] for part in self.table) + loss, self.components = objective( + self.model, + tokens, + labels, + targets, + mask, + self.spec["bridge_weight"], + self.spec["alignment_weight"], + self.spec["alignment_normalization"], + ) + 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']}-" + f"{spec['alignment_coverage']}-{spec['alignment_normalization']}" + ) + + +def _draw_indices(streams, offsets, counts, steps, batch_size): + indices = [] + for j, stream in enumerate(streams): + drawn = stream.take(steps * batch_size // 3).reshape(steps, -1) + counts[j] += np.bincount(drawn.ravel(), minlength=len(counts[j])) + indices.append(drawn + offsets[j]) + return np.concatenate(indices, axis=1) + + +def _coverage_presentations(counts, mask, sizes): + offset, result = 0, {} + for name, count, size in zip(STRATA, counts, sizes, strict=True): + result[name] = int(np.dot(count, mask[offset : offset + size].astype(np.int64))) + offset += size + result["total"] = sum(result.values()) + return result + + +def train(spec, out, source, device): + """Train one immutable attempt; save weights and exposures at every node.""" + validate_spec(spec) + out, device = Path(out), torch.device(device) + out.mkdir(parents=True, exist_ok=True) + if any((out / name).exists() for name in ("run.json", "model.pt", "complete.json")): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + if device.type != "cuda": + raise ValueError("The captured training step requires an explicitly allocated CUDA device") + 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, spec["alignment_coverage"]) + mask = arrays[-1] + model = new_model(spec, device) + initial_hash, world_hash = model_digest(model), data_digest(world) + identity = { + "spec": spec, + "source": source, + "implementation_sha256": file_hash(Path(__file__)), + "world_sha256": world_hash, + "initial_model_sha256": initial_hash, + } + write_json( + out / "run.json", + { + **identity, + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device), + "dtype": "float32", + "allow_tf32": True, + "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, + "strata": dict(zip(STRATA, sizes, strict=True)), + "geometry_unique_examples": _coverage_presentations( + [np.ones(n, dtype=np.int64) for n in sizes], mask, sizes + ), + "geometry_definition": ( + "squared distance of normalized early state and detached input embedding" + ), + "bridge_ce_coverage": "all_atomic_and_composition", + "geometry_normalization": spec["alignment_normalization"], + "tracking_owner": "external read-only batch runner", + }, + ) + 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 = CoverageStep(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, checkpoints, step, training_seconds = [], [], 0, 0.0 + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 9, output_positions=9) + 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] * len(COMPONENTS) + coverage = _coverage_presentations(counts, mask, sizes) + row = { + "step": step, + "metrics": metrics, + **dict(zip(COMPONENTS, parts, strict=True)), + "alignment_normalization": spec["alignment_normalization"], + "alignment_weight": spec["alignment_weight"], + "geometry_target_presentations": coverage, + "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], + "sample_stream_sha256": input_hash.hexdigest(), + } + 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", **{f"stratum{j}": c for j, c in enumerate(counts)} + ) + checkpoint = out / f"model-{step:06d}.pt" + torch.save( + { + **identity, + "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), + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": coverage, + }, + checkpoint, + ) + checkpoints.append({"step": step, "file": checkpoint.name, "sha256": file_hash(checkpoint)}) + write_json(out / "checkpoints.json", checkpoints) + 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 = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) + 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() + # Keep the established downstream loader interface on filesystems without links. + shutil.copyfile(out / f"model-{step:06d}.pt", out / "model.pt") + np.savez_compressed(out / "exposures.npz", **{f"stratum{j}": c for j, c in enumerate(counts)}) + write_json( + out / "complete.json", + { + **identity, + "finished_utc": utc(), + "metrics": history[-1]["metrics"], + "training_seconds": training_seconds, + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": history[-1]["geometry_target_presentations"], + "model_sha256": file_hash(out / "model.pt"), + "nodes_saved": spec["nodes"], + }, + ) + write_json(out / "status.json", {"state": "complete", "step": step}) + + +def audit(out, device, *, all_nodes=False): + """Verify all artifacts; independently reload the endpoint (or all nodes).""" + out, device = Path(out), torch.device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + run = json.loads((out / "run.json").read_text()) + complete = json.loads((out / "complete.json").read_text()) + history = json.loads((out / "learning.json").read_text()) + manifest = json.loads((out / "checkpoints.json").read_text()) + spec = run["spec"] + validate_spec(spec) + assert spec == complete["spec"] + assert [row["step"] for row in history] == spec["nodes"] + assert [entry["step"] for entry in manifest] == spec["nodes"] + assert complete["nodes_saved"] == spec["nodes"] + assert file_hash(out / "model.pt") == complete["model_sha256"] == manifest[-1]["sha256"] + world = build_world(spec) + assert data_digest(world) == run["world_sha256"] == complete["world_sha256"] + with np.load(out / "world.npz") as saved_world: + assert set(saved_world.files) == set(world) + for key, value in world.items(): + np.testing.assert_array_equal(value, saved_world[key]) + arrays, sizes = pack_training(world, spec["alignment_coverage"]) + mask, offsets = arrays[-1], np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] + counts = [np.zeros(n, dtype=np.int64) for n in sizes] + input_hash, step, audits = hashlib.sha256(), 0, [] + model = new_model(spec, device) + assert model_digest(model) == run["initial_model_sha256"] == complete["initial_model_sha256"] + for entry, row in zip(manifest, history, strict=True): + while step < entry["step"]: + n = min(128, entry["step"] - step) + indices = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) + input_hash.update(indices.tobytes()) + step += n + checkpoint = out / entry["file"] + assert file_hash(checkpoint) == entry["sha256"] + payload = torch.load(checkpoint, map_location="cpu", weights_only=False) + assert payload["spec"] == spec and payload["step"] == step + for key in ("source", "implementation_sha256", "world_sha256", "initial_model_sha256"): + assert payload[key] == run[key] == complete[key] + assert ( + payload["sample_stream_sha256"] == row["sample_stream_sha256"] == input_hash.hexdigest() + ) + coverage = _coverage_presentations(counts, mask, sizes) + assert ( + payload["geometry_target_presentations"] + == row["geometry_target_presentations"] + == coverage + ) + with np.load(out / f"exposures-{step:06d}.npz") as saved_counts: + for j, count in enumerate(counts): + np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) + np.testing.assert_array_equal(count, payload["counts"][j]) + if step == 0: + model.load_state_dict(payload["model"]) + assert model_digest(model) == run["initial_model_sha256"] + if not all_nodes and step != spec["steps"]: + audits.append({"step": step, "passed": True, "predictions_recomputed": False}) + continue + model.load_state_dict(payload["model"]) + metrics, predictions = evaluate(model, world, "low", device) + max_nll_error = 0.0 + with np.load(out / f"predictions-{step:06d}.npz") as saved: + assert set(saved.files) == set(predictions) + 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]) + for split, values in metrics.items(): + for key, actual in values.items(): + expected = row["metrics"][split][key] + if actual is None: + assert expected is None + else: + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-5) + audits.append( + { + "step": step, + "passed": True, + "predictions_recomputed": True, + "max_nll_error": max_nll_error, + } + ) + assert complete["sample_stream_sha256"] == input_hash.hexdigest() + assert complete["geometry_target_presentations"] == _coverage_presentations(counts, mask, sizes) + with np.load(out / "exposures.npz") as saved_counts: + for j, count in enumerate(counts): + np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) + result = { + "passed": True, + "metrics": metrics, + "nodes": audits, + "max_nll_error": max(a.get("max_nll_error", 0.0) for a in audits), + "all_nodes": all_nodes, + "allow_tf32": True, + "world_sha256": data_digest(world), + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": _coverage_presentations(counts, mask, sizes), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/architecture_bridge.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/architecture_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..3d611f12f7be01721c8f453b8981605455e4b585 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/architecture_bridge.py @@ -0,0 +1,549 @@ +"""Paired interventions on MLP output and same-layer sequence cache. + +Oracle bridge hints define an assisted diagnostic, not an identified natural +reasoning circuit. Cache interventions do not change model parameters. +""" + +from __future__ import annotations + +import contextlib +import copy +import hashlib +import json +import re +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "data/architecture-bridge-v1" +ART = ROOT / "docs/development-artifacts/architecture-bridge-v1" +RESULTS = ROOT / "results/architecture-bridge-v1" +CONFIG = ROOT / "configs/architecture-bridge-v1.json" + + +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 order(value): + return hashlib.sha256(f"142935:{value}".encode()).hexdigest() + + +def normalize(value): + import string + + value = value.lower().translate(str.maketrans("", "", string.punctuation)) + return " ".join(re.sub(r"\b(a|an|the)\b", " ", value).split()) + + +def grade(text, answer, aliases=()): + value = text.rsplit("Final answer:", 1)[-1].strip() + value = re.sub(r"^(?:Answer|Bridge):\s*", "", value, flags=re.I).strip().strip('"*') + predicted, gold = normalize(value), normalize(answer) + a, b = Counter(predicted.split()), Counter(gold.split()) + common = sum((a & b).values()) + return { + "em": predicted == gold, + "f1": 2 * common / (sum(a.values()) + sum(b.values())) if common else 0.0, + "alias_em": predicted in {normalize(x) for x in [answer, *aliases]}, + } + + +def base_prompt(row, question=None): + context = row.get("support_context", "") + parts = ["Question: What is 2 + 2?\nAnswer: 4", "Output only the short answer."] + if context: + parts.append("Use the supplied passages.\nPassages:\n" + context) + parts.append("Question: " + (question if question is not None else row["question"])) + return "\n\n".join(parts) + + +def prefix(row, bridge): + return base_prompt(row) + "\nIntermediate entity: " + bridge + "\n" + + +def prepare(): + from transformers import AutoTokenizer + + if (ART / "data-lock.json").exists(): + raise FileExistsError("This data selection is already frozen") + cfg = read(CONFIG) + toks = { + k: AutoTokenizer.from_pretrained(ROOT / v["path"], local_files_only=True) + for k, v in cfg["models"].items() + } + source_path = ROOT / "data/twohop-frozen-v1/cases.json" + source, selected, audit = read(source_path), [], {} + for dataset in cfg["datasets"]: + for split, count in cfg["cases_per_dataset"].items(): + pool = sorted( + [x for x in source if x["dataset"] == dataset and x["split"] == split], + key=lambda x: order(x["id"]), + ) + for row in pool[:count]: + r = copy.deepcopy(row) + names = sorted({p["bridge"] for p in pool}, key=order) + forbidden = {normalize(x) for x in [r["bridge"], *r.get("bridge_aliases", [])]} + gold = {normalize(x) for x in [r["answer"], *r.get("aliases", [])]} + target = {k: len(t.encode(prefix(r, r["bridge"]))) for k, t in toks.items()} + chosen = [] + for name in names: + norm = normalize(name) + if norm in forbidden or any(g and g in norm for g in gold): + continue + if all(len(t.encode(prefix(r, name))) == target[k] for k, t in toks.items()): + chosen.append(name) + if len(chosen) == 2: + break + reason = None + if len(chosen) < 2: + reason = "fewer_than_two_length_matched_wrong_bridges" + if max(target.values()) > cfg["max_prefix_tokens"]: + reason = "prefix_exceeds_budget" + if any(g and g in normalize(r["bridge"]) for g in gold): + reason = "correct_bridge_contains_final_answer" + competitors = [ + x["answer"] for x in pool if normalize(x["answer"]) != normalize(r["answer"]) + ] + r.update( + prefix_tokens=target, + corrupted_bridge=chosen[0] if chosen else None, + control_bridge=chosen[1] if len(chosen) > 1 else None, + exclusion_reason=reason, + competitor=(r.get("wrong_donor") or {}).get("answer", competitors[0]), + ) + selected.append(r) + audit[f"{dataset}:{split}"] = { + "selected": count, + "eligible": sum( + x["exclusion_reason"] is None + for x in selected + if x["dataset"] == dataset and x["split"] == split + ), + } + # E comes from selected evaluation rows; R and U are independent source groups + # from the unused historical pool. D is never used to choose a direction. + edits = [r for r in selected if r["dataset"] == "2wiki" and r["split"] == "evaluation"] + used = {r["group"] for r in selected if r["dataset"] == "2wiki"} + reserves = sorted( + [ + r + for r in source + if r["dataset"] == "2wiki" and r["split"] == "evaluation" and r["group"] not in used + ], + key=lambda r: order("keep:" + r["id"]), + ) + lc = cfg["local_learning"] + learning = { + "E": edits[: lc["episodes"]], + "R": reserves[: lc["keep_R"]], + "U": reserves[lc["keep_R"] : lc["keep_R"] + lc["unseen_U"]], + } + assert len(learning["U"]) == lc["unseen_U"] + write(DATA / "cases.json", selected) + write(DATA / "learning.json", learning) + write( + ART / "data-lock.json", + { + "config": cfg, + "config_sha256": digest(CONFIG), + "source_sha256": digest(source_path), + "cases_sha256": digest(DATA / "cases.json"), + "learning_sha256": digest(DATA / "learning.json"), + "audit": audit, + "selection": ( + "Fixed hash before outputs; excluded cases are retained without replacement." + ), + }, + ) + return audit + + +def cache_fields(cache, layer): + obj = cache.layers[layer] + if hasattr(obj, "recurrent_states"): + return [("conv_states", 0), ("recurrent_states", 0)] + return [("keys", None), ("values", None)] + + +def field_get(obj, name, index): + value = getattr(obj, name) + return value if index is None else value[index] + + +def field_set(obj, name, index, value): + if index is None: + setattr(obj, name, value) + else: + getattr(obj, name)[index] = value + + +def matched_random(delta, seed): + generator = torch.Generator(device=delta.device).manual_seed(seed) + random = torch.randn(delta.shape, device=delta.device, dtype=delta.dtype, generator=generator) + return random * (delta.norm() / random.norm().clamp_min(torch.finfo(delta.dtype).tiny)) + + +def change_cache(target, donor, layer, random_seed=None): + # Keep recipient metadata and update only equal-shaped tensors. Prefix length + # and token positions are identical across donors in the frozen selection. + stats = {} + for i, (name, index) in enumerate(cache_fields(target, layer)): + a = field_get(target.layers[layer], name, index) + b = field_get(donor.layers[layer], name, index) + if a.shape != b.shape: + raise ValueError(f"Unequal cache shapes for {name}: {a.shape} != {b.shape}") + delta = b - a + if random_seed is not None: + delta = matched_random(delta, random_seed + i) + stats[name + "_delta_norm"] = float(delta.norm()) + field_set( + target.layers[layer], name, index, b.clone() if random_seed is None else a + delta + ) + return stats + + +class Engine: + def __init__(self, key, device=None): + from transformers import ( + AutoTokenizer, + PreTrainedTokenizerFast, + Qwen3_5ForCausalLM, + Qwen3ForCausalLM, + ) + + self.cfg = read(CONFIG) + self.key, self.mc = key, self.cfg["models"][key] + self.device = torch.device(device or self.cfg["device"]) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + if self.device.type == "cuda": + torch.cuda.set_per_process_memory_fraction(self.cfg["gpu_memory_fraction"], self.device) + cls = Qwen3ForCausalLM if key == "qwen3" else Qwen3_5ForCausalLM + # In transformers 5.17 Qwen2Tokenizer rebuilds Qwen3.5's regex and drops + # Unicode combining marks. Load the official tokenizer.json unchanged. + tokenizer_cls = AutoTokenizer if key == "qwen3" else PreTrainedTokenizerFast + self.tok = tokenizer_cls.from_pretrained(ROOT / self.mc["path"], local_files_only=True) + self.model = ( + cls.from_pretrained( + ROOT / self.mc["path"], + local_files_only=True, + dtype=torch.float32, + attn_implementation="eager", + ) + .to(self.device) + .eval() + .requires_grad_(False) + ) + self.layers = self.model.model.layers + self.stats = Counter() + self.eos = self.tok.eos_token_id + + def ids(self, text): + return torch.tensor([self.tok.encode(text, add_special_tokens=False)], device=self.device) + + def forward(self, ids, cache=None, total=None): + total = ids.shape[1] if total is None else total + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += ids.numel() + return self.model( + input_ids=ids, + attention_mask=torch.ones((1, total), device=self.device, dtype=torch.long), + past_key_values=cache, + use_cache=True, + logits_to_keep=1, + ) + + @contextlib.contextmanager + def mlp_hook(self, layer, replacement=None, capture=None): + def hook(module, args, output): + if capture is not None: + capture[layer] = output[0, -1].detach().clone() + if replacement is None: + return None + modified = output.clone() + modified[0, -1] = replacement + return modified + + handle = self.layers[layer].mlp.register_forward_hook(hook) + try: + yield + finally: + handle.remove() + + @torch.no_grad() + def prefill(self, text, layer=None, replacement=None): + ids, captured = self.ids(text), {} + if ids.shape[1] > self.cfg["max_prefix_tokens"]: + raise ValueError("Prefix exceeds budget; truncation is forbidden") + with contextlib.ExitStack() as stack: + for li in self.mc["layers"]: + stack.enter_context( + self.mlp_hook(li, replacement if li == layer else None, captured) + ) + out = self.forward(ids) + return out.past_key_values, captured, ids.shape[1] + + @torch.no_grad() + def continuation_score(self, logits, cache, total, answer): + targets = self.tok.encode(" " + answer, add_special_tokens=False) + [self.eos] + values = [] + for index, token in enumerate(targets): + values.append(float(logits[0, -1].log_softmax(-1)[token])) + if index + 1 < len(targets): + total += 1 + out = self.forward(torch.tensor([[token]], device=self.device), cache, total) + logits, cache = out.logits, out.past_key_values + return {"sum_logp": sum(values), "mean_logp": float(np.mean(values)), "tokens": targets} + + @torch.no_grad() + def finish(self, cache, n_prefix, row, suffix=None): + suffix_ids = self.ids(self.cfg["suffix"] if suffix is None else suffix) + total = n_prefix + suffix_ids.shape[1] + out = self.forward(suffix_ids, cache, total) + logits, cache = out.logits, out.past_key_values + scores = {} + for name, answer in [("correct", row["answer"]), ("competitor", row["competitor"])]: + scores[name] = self.continuation_score(logits, copy.deepcopy(cache), total, answer) + scores["margin"] = scores["correct"]["mean_logp"] - scores["competitor"]["mean_logp"] + tokens = [] + for _ in range(self.cfg["generation_tokens"]): + token = int(logits[0, -1].argmax()) + tokens.append(token) + if token == self.eos: + break + total += 1 + out = self.forward(torch.tensor([[token]], device=self.device), cache, total) + logits, cache = out.logits, out.past_key_values + text = self.tok.decode(tokens, skip_special_tokens=True) + self.stats["generated_tokens"] += len(tokens) + return { + "text": text, + "tokens": tokens, + "ended_eos": tokens[-1] == self.eos, + **grade(text, row["answer"], row.get("unambiguous_aliases", row.get("aliases", []))), + "scores": scores, + } + + def direct(self, row, question=None, answer=None): + qrow = dict(row) + if answer is not None: + qrow.update(answer=answer, aliases=[], unambiguous_aliases=[]) + cache, _, length = self.prefill(base_prompt(row, question)) + return self.finish(cache, length, qrow) + + @torch.no_grad() + def case(self, row): + started = time.monotonic() + before_stats = self.stats.copy() + result = { + "id": row["id"], + "dataset": row["dataset"], + "split": row["split"], + "group": row["group"], + "exclusion_reason": row["exclusion_reason"], + "unassisted": self.direct(row), + "first_hop": self.direct(row, row["q1"], row["bridge"]), + "second_hop": self.direct(row, row["q2"]), + "interventions": [], + } + if row["exclusion_reason"]: + result["seconds"] = time.monotonic() - started + result["resources"] = dict(self.stats - before_stats) + return result + caches, activations, lengths = {}, {}, {} + for name, bridge in [ + ("correct", row["bridge"]), + ("corrupt", row["corrupted_bridge"]), + ("wrong", row["control_bridge"]), + ]: + caches[name], activations[name], lengths[name] = self.prefill(prefix(row, bridge)) + if len(set(lengths.values())) != 1: + raise AssertionError("Token-length matching contract broken") + n = lengths["corrupt"] + if n != row["prefix_tokens"][self.key]: + raise AssertionError("Tokenizer revision changed the frozen prefix length") + result["oracle_input"] = self.finish(copy.deepcopy(caches["correct"]), n, row) + for layer in self.mc["layers"]: + baseline = None + for condition in self.cfg["conditions"]: + donor = "wrong" if condition.endswith("wrong") else "correct" + seed = int(order(row["id"] + str(layer))[:8], 16) + use_mlp = condition.startswith(("mlp_", "joint_")) + use_state = condition.startswith(("state_", "joint_")) + stats = {} + if use_mlp: + delta = activations[donor][layer] - activations["corrupt"][layer] + if condition.endswith("random"): + delta = matched_random(delta, seed) + replacement = ( + activations["corrupt"][layer] + delta + if condition.endswith("random") + else activations[donor][layer] + ) + stats["mlp_delta_norm"] = float(delta.norm()) + cache, _, _ = self.prefill( + prefix(row, row["corrupted_bridge"]), layer, replacement + ) + else: + cache = copy.deepcopy(caches["corrupt"]) + if use_state or condition == "identity": + source = caches["corrupt"] if condition == "identity" else caches[donor] + stats.update( + change_cache( + cache, source, layer, seed + 1 if condition.endswith("random") else None + ) + ) + prediction = self.finish(cache, n, row) + if condition == "baseline": + baseline = prediction + if condition == "identity": + if prediction["tokens"] != baseline["tokens"]: + raise AssertionError("Identity cache changed generated tokens") + if abs(prediction["scores"]["margin"] - baseline["scores"]["margin"]) > 1e-5: + raise AssertionError("Identity cache changed scores") + result["interventions"].append( + { + "layer": layer, + "condition": condition, + "cache_kind": self.mc["kind"], + **stats, + **prediction, + } + ) + result["seconds"] = time.monotonic() - started + result["resources"] = dict(self.stats - before_stats) + return result + + def prompt_suffix_ids(self, prompt): + # Match prefill(prompt) followed by finish(suffix), including BPE boundaries. + return torch.cat([self.ids(prompt), self.ids(self.cfg["suffix"])], dim=1) + + def next_logits(self, prompt): + ids = self.prompt_suffix_ids(prompt) + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += ids.numel() + if torch.is_grad_enabled(): + self.stats["backward_input_tokens"] += ids.numel() + return self.model(input_ids=ids, use_cache=False, logits_to_keep=1).logits[0, -1] + + def target_loss(self, row): + x = self.prompt_suffix_ids(base_prompt(row, row["q1"])) + target = self.tok.encode(" " + row["bridge"], add_special_tokens=False) + [self.eos] + y = torch.tensor([target], device=self.device) + inputs = torch.cat([x, y[:, :-1]], dim=1) + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += inputs.numel() + self.stats["backward_input_tokens"] += inputs.numel() + self.stats["supervised_tokens"] += y.numel() + logits = self.model(input_ids=inputs, use_cache=False, logits_to_keep=len(target)).logits + return torch.nn.functional.cross_entropy(logits.flatten(0, 1), y.flatten()) + + def learning(self, episode, output_dir): + before_stats = self.stats.copy() + lc = self.cfg["local_learning"] + pools = read(DATA / "learning.json") + target = pools["E"][episode] + parameter = self.layers[lc["layer"]].mlp.down_proj.weight + original = parameter.detach().clone() + teacher = {} + for role in ["R", "U"]: + with torch.no_grad(): + teacher[role] = [ + self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1).detach() + for r in pools[role] + ] + result = {"episode": episode, "target_id": target["id"], "nodes": [], "training": []} + started = time.monotonic() + try: + parameter.requires_grad_(True) + optimizer = torch.optim.SGD([parameter], lr=lc["lr"]) + for step in range(lc["steps"] + 1): + if step in lc["nodes"]: + node = { + "step": step, + "E": self.direct(target, target["q1"], target["bridge"]), + "D": self.direct(target), + "R": [], + "U": [], + "parameter_delta_norm": float((parameter.detach() - original).norm()), + } + for role in ["R", "U"]: + for r, old_lp in zip(pools[role], teacher[role], strict=True): + r = dict(r, competitor=target["bridge"]) + with torch.no_grad(): + lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) + kl = float((old_lp.exp() * (old_lp - lp)).sum()) + node[role].append( + { + "id": r["id"], + "kl": kl, + **self.direct(r, r["q1"], r["bridge"]), + } + ) + result["nodes"].append(node) + write(output_dir / "progress.json", result) + if step == lc["steps"]: + break + optimizer.zero_grad(set_to_none=True) + loss = self.target_loss(target) + target_value = float(loss.detach()) + loss.backward() + replay_value = 0.0 + for r, old_lp in zip(pools["R"], teacher["R"], strict=True): + lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) + kl = (old_lp.exp() * (old_lp - lp)).sum() + replay_value += float(kl.detach()) / len(pools["R"]) + (lc["replay_KL_weight"] * kl / len(pools["R"])).backward() + norm = float(torch.nn.utils.clip_grad_norm_([parameter], lc["gradient_clip"])) + if not np.isfinite(target_value + replay_value + norm): + raise FloatingPointError("Nonfinite local learning response") + optimizer.step() + result["training"].append( + { + "step": step + 1, + "target_ce": target_value, + "R_kl": replay_value, + "gradient_norm": norm, + } + ) + torch.save( + { + "down_weight": parameter.detach().cpu(), + "target_id": target["id"], + "layer": lc["layer"], + "steps": lc["steps"], + }, + output_dir / "endpoint.pt", + ) + finally: + with torch.no_grad(): + parameter.copy_(original) + parameter.requires_grad_(False) + if not torch.equal(parameter, original): + raise AssertionError("Episode failed to restore original weight") + result["seconds"] = time.monotonic() - started + result["restored_original"] = True + result["resources"] = dict(self.stats - before_stats) + return result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/architecture_bridge_toy.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/architecture_bridge_toy.py new file mode 100644 index 0000000000000000000000000000000000000000..a406337c9f1b455c1c07183ec90de18541f7d03b --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/architecture_bridge_toy.py @@ -0,0 +1,410 @@ +"""A frozen small GQA / gated-delta mechanism experiment. + +Both models use RMSNorm, SwiGLU and tied token embeddings. The hybrid is a +deliberately small mechanism model, NOT an implementation of any Qwen release. +Its delta mixer has a genuine recurrent matrix, causal q/k/v convolution, +normalized q/k, input-dependent decay/write gates, and a headwise output gate. +""" + +from __future__ import annotations + +import hashlib +import math +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from llm_memory_editability.twohop_depth import BOS, ENTITY, EOS + + +class RMSNorm(nn.Module): + def __init__(self, width, eps): + super().__init__() + self.weight = nn.Parameter(torch.ones(width)) + self.eps = eps + + def forward(self, x): + return x * torch.rsqrt(x.square().mean(-1, keepdim=True) + self.eps) * self.weight + + +def rope(x, offset): + """Full rotary position embedding; head width is even.""" + width = x.shape[-1] + positions = torch.arange(offset, offset + x.shape[-2], device=x.device, dtype=x.dtype) + inverse = 10000.0 ** (-torch.arange(0, width, 2, device=x.device, dtype=x.dtype) / width) + phase = positions[:, None] * inverse[None, :] + even, odd = x[..., 0::2], x[..., 1::2] + return torch.stack( + (even * phase.cos() - odd * phase.sin(), even * phase.sin() + odd * phase.cos()), + dim=-1, + ).flatten(-2) + + +class GQA(nn.Module): + def __init__(self, cfg): + super().__init__() + width, self.heads, self.kv_heads = cfg["width"], cfg["heads"], cfg["kv_heads"] + self.dim = width // self.heads + self.q = nn.Linear(width, width, bias=False) + self.k = nn.Linear(width, self.kv_heads * self.dim, bias=False) + self.v = nn.Linear(width, self.kv_heads * self.dim, bias=False) + self.out = nn.Linear(width, width, bias=False) + self.q_norm = RMSNorm(self.dim, cfg["norm_eps"]) + self.k_norm = RMSNorm(self.dim, cfg["norm_eps"]) + + def forward(self, x, cache=None): + batch, length, width = x.shape + offset = 0 if cache is None else cache["k"].shape[2] + q = self.q(x).view(batch, length, self.heads, self.dim).transpose(1, 2) + k = self.k(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) + v = self.v(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) + q, k = rope(self.q_norm(q), offset), rope(self.k_norm(k), offset) + if cache is not None: + k, v = torch.cat((cache["k"], k), 2), torch.cat((cache["v"], v), 2) + new_cache = {"k": k, "v": v} + repeat = self.heads // self.kv_heads + keys, values = k.repeat_interleave(repeat, 1), v.repeat_interleave(repeat, 1) + scores = (q @ keys.transpose(-2, -1)) / math.sqrt(self.dim) + allowed = ( + torch.arange(k.shape[2], device=x.device)[None, :] + <= torch.arange(offset, offset + length, device=x.device)[:, None] + ) + scores = scores.masked_fill(~allowed, float("-inf")) + out = (scores.softmax(-1) @ values).transpose(1, 2).reshape(batch, length, width) + return self.out(out), new_cache + + +class GatedDelta(nn.Module): + def __init__(self, cfg): + super().__init__() + width, self.heads = cfg["width"], cfg["heads"] + self.dim, self.kernel = width // self.heads, cfg["conv_kernel"] + self.qkv = nn.Linear(width, 3 * width, bias=False) + self.conv_weight = nn.Parameter(torch.empty(self.kernel, 3 * width)) + self.decay = nn.Linear(width, self.heads, bias=True) + self.write = nn.Linear(width, self.heads, bias=True) + self.gate = nn.Linear(width, self.heads, bias=True) + self.out_norm = RMSNorm(self.dim, cfg["norm_eps"]) + self.out = nn.Linear(width, width, bias=False) + + def forward(self, x, cache=None): + batch, length, width = x.shape + raw = self.qkv(x) + if cache is None: + history = raw.new_zeros(batch, self.kernel - 1, 3 * width) + state = raw.new_zeros(batch, self.heads, self.dim, self.dim) + else: + history, state = cache["conv"], cache["state"] + full = torch.cat((history, raw), 1) + convolved = sum(full[:, j : j + length] * self.conv_weight[j] for j in range(self.kernel)) + q, k, v = F.silu(convolved).chunk(3, -1) + q = F.normalize(q.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) + k = F.normalize(k.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) + v = v.view(batch, length, self.heads, self.dim) + alpha = torch.exp(-F.softplus(self.decay(x))) + beta, gate = self.write(x).sigmoid(), self.gate(x).sigmoid() + outputs = [] + for t in range(length): + # S_t = alpha S_(t-1)(I-beta kk^T) + beta vk^T. + state = alpha[:, t, :, None, None] * state + read_at_key = (state * k[:, t, :, None, :]).sum(-1) + error = v[:, t] - read_at_key + state = state + beta[:, t, :, None, None] * (error[..., :, None] * k[:, t, :, None, :]) + outputs.append((state * q[:, t, :, None, :]).sum(-1)) + out = self.out_norm(torch.stack(outputs, 1)) * gate[..., None] + new_cache = {"conv": full[:, -(self.kernel - 1) :], "state": state} + return self.out(out.reshape(batch, length, width)), new_cache + + +class SwiGLU(nn.Module): + def __init__(self, cfg): + super().__init__() + self.up = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) + self.gate = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) + self.down = nn.Linear(cfg["mlp_hidden"], cfg["width"], bias=False) + + def forward(self, x): + return self.down(self.up(x) * F.silu(self.gate(x))) + + +class Block(nn.Module): + def __init__(self, kind, cfg): + super().__init__() + self.norm_mixer = RMSNorm(cfg["width"], cfg["norm_eps"]) + self.mixer = GQA(cfg) if kind == "gqa" else GatedDelta(cfg) + self.norm_mlp = RMSNorm(cfg["width"], cfg["norm_eps"]) + self.mlp = SwiGLU(cfg) + + +def apply_patch(output, patch): + if patch is None: + return output + result = output.clone() + result[:, patch["positions"]] = patch["value"].to(output) + return result + + +class ToyLM(nn.Module): + def __init__(self, architecture, cfg): + super().__init__() + self.config = cfg + self.architecture = architecture + self.token = nn.Embedding(ENTITY + cfg["entities"] + cfg["relations"], cfg["width"]) + self.blocks = nn.ModuleList(Block(kind, cfg) for kind in architecture["mixers"]) + self.norm_final = RMSNorm(cfg["width"], cfg["norm_eps"]) + + def forward( + self, tokens, positions=None, *, cache=None, patches=None, capture=False, return_cache=False + ): + h, states, trace = self.token(tokens), [], {} + patches = {} if patches is None else patches + for layer, block in enumerate(self.blocks): + past = None if cache is None else cache[layer] + mixer, state = block.mixer(block.norm_mixer(h), past) + mixer = apply_patch(mixer, patches.get(("mixer", layer))) + h = h + mixer + mlp = apply_patch(block.mlp(block.norm_mlp(h)), patches.get(("mlp", layer))) + h = h + mlp + states.append(state) + if capture: + trace[("mixer", layer)], trace[("mlp", layer)] = mixer, mlp + h = self.norm_final(h) + if positions is not None: + h = h[torch.arange(len(h), device=h.device)[:, None], positions] + logits = F.linear(h, self.token.weight) + return (logits, states, trace) if capture or return_cache else logits + + +def initialize(model, seed): + """Pair every common named and shaped parameter without RNG-order effects.""" + with torch.no_grad(): + for name, parameter in model.named_parameters(): + if name.endswith(".bias"): + parameter.zero_() + elif "norm" in name and name.endswith(".weight"): + parameter.fill_(1) + else: + key = hashlib.sha256(f"{seed}:{name}".encode()).digest() + generator = torch.Generator().manual_seed(int.from_bytes(key[:8], "little")) + std = 0.02 + if name.endswith("mixer.out.weight") or name.endswith("mlp.down.weight"): + std /= math.sqrt(2 * len(model.blocks)) + parameter.copy_(torch.randn(parameter.shape, generator=generator) * std) + + +def parameter_digest(model): + h = hashlib.sha256() + for name, parameter in model.named_parameters(): + h.update(name.encode()) + h.update(parameter.detach().cpu().contiguous().numpy().tobytes()) + return h.hexdigest() + + +def exposure(cfg, steps): + count = cfg["batch_per_kind"] * steps + return { + "steps": steps, + "atomic_examples": count, + "training_composite_examples": count, + "valid_input_tokens": count * 11, + "processed_tokens_including_padding": count * 12, + "supervised_answer_eos_tokens": count * 4, + } + + +def flops_estimate(model, cfg, steps): + """Conventional 6*N*T estimate plus transparent small mixer correction.""" + params = sum(p.numel() for p in model.parameters()) + tokens = exposure(cfg, steps)["processed_tokens_including_padding"] + n_gqa = model.architecture["mixers"].count("gqa") + n_delta = model.architecture["mixers"].count("delta") + length, width, heads = 6, cfg["width"], cfg["heads"] + dim = width // heads + mixing = tokens * (n_gqa * 12 * length * width + n_delta * 24 * heads * dim * dim) + return { + "parameter_count": params, + "conventional_6_parameter_token_flops": 6 * params * tokens, + "additional_mixing_flops_approx": mixing, + "total_approx": 6 * params * tokens + mixing, + "limitation": ( + "Rough training estimate, not profiler measurements; 6NT includes embeddings " + "and excludes detailed normalization/activation costs." + ), + } + + +@torch.no_grad() +def generate(model, x, y, device, batch=128, patches=None): + result = {key: [] for key in ("pred", "eos", "logp", "logits")} + for start in range(0, len(x), batch): + tokens = torch.as_tensor(x[start : start + batch], device=device) + target = torch.as_tensor(y[start : start + batch], device=device) + part = None + if patches is not None: + part = { + key: { + "positions": value["positions"], + "value": value["value"][start : start + batch], + } + for key, value in patches.items() + } + logits = model(tokens, patches=part)[:, -1] + prediction = logits.argmax(-1) + stop = model(torch.cat((tokens, prediction[:, None]), 1), patches=part)[:, -1].argmax(-1) + result["pred"].append(prediction.cpu().numpy()) + result["eos"].append(stop.cpu().numpy()) + result["logp"].append(logits.log_softmax(-1).gather(1, target[:, None]).cpu().numpy()[:, 0]) + result["logits"].append(logits.cpu().numpy()) + return {key: np.concatenate(value) for key, value in result.items()} + + +@torch.no_grad() +def evaluate(model, world, cfg, device): + model.eval() + arrays, metrics = {}, {} + for name, key, mask in ( + ("atomic", "atomic", slice(None)), + ("train", "composite", world["train_mask"]), + ("test", "composite", ~world["train_mask"]), + ): + x, y = world[key + "_x"][mask], world[key + "_y"][mask] + output = generate(model, x, y, device, cfg["eval_batch"]) + for field, value in output.items(): + arrays[f"{name}_{field}"] = value + correct = (output["pred"] == y) & (output["eos"] == EOS) + metrics[name] = { + "n": len(y), + "answer_accuracy": float(np.mean(output["pred"] == y)), + "exact_answer_eos": float(correct.mean()), + "answer_nll": float(-output["logp"].mean()), + } + indices = np.flatnonzero(~world["train_mask"]) + a, r1, r2 = world["comps"][indices].T + bridge = arrays["atomic_pred"][a * cfg["relations"] + r1] + bridge_eos = arrays["atomic_eos"][a * cfg["relations"] + r1] + second = np.c_[np.full(len(a), BOS), bridge, ENTITY + cfg["entities"] + r2] + y = world["composite_y"][indices] + output = generate(model, second, y, device, cfg["eval_batch"]) + arrays.update({f"two_call_{field}": value for field, value in output.items()}) + arrays["two_call_bridge"], arrays["two_call_bridge_eos"] = bridge, bridge_eos + correct = (output["pred"] == y) & (output["eos"] == EOS) & (bridge_eos == EOS) + metrics["two_call"] = {"n": len(y), "exact_answer_eos": float(correct.mean())} + atom_ok = (arrays["atomic_pred"] == world["atomic_y"]) & (arrays["atomic_eos"] == EOS) + gold_bridge = world["maps"][r1, a] + both = atom_ok[a * cfg["relations"] + r1] & atom_ok[gold_bridge * cfg["relations"] + r2] + direct_ok = (arrays["test_pred"] == y) & (arrays["test_eos"] == EOS) + arrays["test_both_atoms_correct"] = both + metrics["test_given_both_atoms"] = { + "n": int(both.sum()), + "coverage": float(both.mean()), + "exact_answer_eos": float(direct_ok[both].mean()) if both.any() else None, + } + return metrics, arrays + + +def intervention_conditions(traces, cfg, device): + """Same orthogonal transform for both donor norms; no fitted direction.""" + rng = np.random.default_rng(cfg["random_control_seed"]) + perm = torch.as_tensor(rng.permutation(cfg["width"]), device=device) + signs = torch.as_tensor(rng.choice([-1.0, 1.0], cfg["width"]), device=device) + sites = { + "mlp": (cfg["mlp_layer"], cfg["mlp_position"]), + "mixer": (cfg["mixer_layer"], cfg["mixer_position"]), + } + conditions, norms = {}, {} + for target in cfg["patch_targets"]: + kinds = ("mlp", "mixer") if target == "joint" else (target,) + for donor in cfg["patch_donors"]: + patches, measurements = {}, {} + for kind in kinds: + layer, position = sites[kind] + base = traces["identity"][(kind, layer)][:, [position]] + source = donor.replace("random_", "") + delta = traces[source][(kind, layer)][:, [position]] - base + if donor.startswith("random_"): + delta = delta[..., perm] * signs.to(delta) + patches[(kind, layer)] = {"positions": [position], "value": base + delta} + measurements[kind] = delta.flatten(1).norm(dim=-1).cpu().numpy() + key = f"{target}_{donor}" + conditions[key], norms[key] = patches, measurements + return conditions, norms + + +@torch.no_grad() +def diagnostics(model, world, cfg, device): + model.eval() + cases = world["cases"] + query = world["composite_x"][cases[:, 0]] + correct = np.c_[ + np.full(len(cases), BOS), + ENTITY + cases[:, 9], + ENTITY + cfg["entities"] + cases[:, 10], + ENTITY + cfg["entities"] + cases[:, 3], + ] + wrong = np.c_[ + np.full(len(cases), BOS), + ENTITY + cases[:, 6], + ENTITY + cfg["entities"] + cases[:, 2], + ENTITY + cfg["entities"] + cases[:, 3], + ] + traces = {} + for key, x in (("identity", query), ("correct", correct), ("wrong", wrong)): + _, _, traces[key] = model(torch.as_tensor(x, device=device), capture=True) + conditions, norms = intervention_conditions(traces, cfg, device) + target, competitor = ENTITY + cases[:, 5], ENTITY + cases[:, 8] + arrays = { + "case_ids": cases[:, 0], + "target": target, + "wrong_target": competitor, + "query": query, + "correct_donor": correct, + "wrong_donor": wrong, + } + baseline = generate(model, query, target, device, cfg["eval_batch"]) + base_ok = (baseline["pred"] == target) & (baseline["eos"] == EOS) + metrics = {} + for name, patches in {"baseline": None, **conditions}.items(): + output = ( + baseline + if patches is None + else generate(model, query, target, device, cfg["eval_batch"], patches) + ) + for field, value in output.items(): + arrays[f"{name}_{field}"] = value + row = np.arange(len(target)) + margin = output["logits"][row, target] - output["logits"][row, competitor] + arrays[f"{name}_margin"] = margin + exact = (output["pred"] == target) & (output["eos"] == EOS) + wrong_ok = (output["pred"] == competitor) & (output["eos"] == EOS) + metrics[name] = { + "n": len(target), + "correct_exact": float(exact.mean()), + "wrong_exact": float(wrong_ok.mean()), + "rescued": int((exact & ~base_ok).sum()), + "damaged": int((~exact & base_ok).sum()), + "baseline_correct_n": int(base_ok.sum()), + "baseline_incorrect_n": int((~base_ok).sum()), + "mean_correct_minus_wrong_margin": float(margin.mean()), + "max_logit_change": float(np.max(np.abs(output["logits"] - baseline["logits"]))), + } + for kind, value in norms.get(name, {}).items(): + arrays[f"{name}_{kind}_norm"] = value + # Functional interaction in the 2x2 channel intervention, not an attribution percentage. + for donor in ("correct", "wrong", "random_correct", "random_wrong"): + interaction = ( + arrays[f"joint_{donor}_margin"] + - arrays[f"mlp_{donor}_margin"] + - arrays[f"mixer_{donor}_margin"] + + arrays["baseline_margin"] + ) + arrays[f"interaction_{donor}"] = interaction + return metrics, arrays + + +def save_npz(path, arrays): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed(path, **arrays) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_analysis.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae07fb7fccdec9430d5e69bc1b304a9fcebe914 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_analysis.py @@ -0,0 +1,399 @@ +"""Audit saved edit predictions and describe failures without selecting successes.""" + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from .bios_data import N_BASE, RELATIONS, load_world, write_json + +RETENTION_GROUPS = ("0", "1", "2", "3", "2_base", "2_derived") + + +def read(path): + return json.loads(path.read_text()) + + +def failure_flags(point, accuracy=0.95, damage=0.01): + rates = [point["U_heldout_destruction"][g]["rate"] for g in RETENTION_GROUPS] + return { + "E": point["E_root"] < 1 or point["E_member"] < accuracy, + "D": point["D"] < accuracy, + "U": any(r is not None and r > damage for r in rates), + "unevaluable": any(r is None for r in rates), + } + + +def failure_signature(flags): + if flags["unevaluable"]: + return "unevaluable" + return "+".join(k for k in ("E", "D", "U") if flags[k]) or "pass" + + +def propagation_errors(world, sets, prediction): + ids = sets["D"] + value, ended = prediction["prediction"][ids], prediction["ended"][ids] + target = sets["target"][ids] + actual = sets["target"][2112 + world.person[ids]] + correct = (value == target) & ended + remaining = ~correct + counts = {"correct": int(correct.sum())} + for name, mask in ( + ("nontermination", ~ended), + ("old_default", value == world.answers[ids]), + ("personal_city_instead_of_company_default", value == actual), + ): + counts[name] = int((remaining & mask).sum()) + remaining &= ~mask + counts["other_wrong_value"] = int(remaining.sum()) + assert sum(counts.values()) == len(ids) + strata = {} + old_exception = world.exceptions[world.person[ids]] + for name, mask in ( + ("old_exception", old_exception), + ("updated_personal_equals_default", ~old_exception & (actual == target)), + ("updated_personal_differs_from_default", ~old_exception & (actual != target)), + ): + strata[name] = {"n": int(mask.sum()), "correct": int(correct[mask].sum())} + return {"counts": counts, "strata": strata} + + +def retention_masks(sets, old_correct, view="heldout"): + eligible = old_correct.copy() + if view != "full": + selected = np.zeros(len(eligible), dtype=bool) + selected[sets[view]] = True + eligible &= selected + masks = {str(g): eligible & (sets["strata"] == g) for g in range(4)} + masks["2_base"] = masks["2"] & (np.arange(len(eligible)) < N_BASE) + masks["2_derived"] = masks["2"] & (np.arange(len(eligible)) >= N_BASE) + return masks + + +def retention_counts(sets, correct, old_correct, view="heldout"): + return { + group: { + "known": int(mask.sum()), + "broken": int((mask & ~correct).sum()), + "rate": float((~correct[mask]).mean()) if mask.any() else None, + } + for group, mask in retention_masks(sets, old_correct, view).items() + } + + +def dump_csv(path, rows): + if not rows: + return + with path.open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def summarize_group(cases): + n = len(cases) + result = {"n": n} + for field in ("E", "E_root", "E_member", "D", "U_accuracy", "E_target_value_nll"): + result[f"mean_{field}"] = float(np.mean([c["final"][field] for c in cases])) + result.update( + final_pass=sum(c["final"]["joint_pass"] is True for c in cases), + ever_pass=sum(c["first_observed_joint_step"] is not None for c in cases), + regressed=sum( + c["first_observed_joint_step"] is not None and not c["final"]["joint_pass"] + for c in cases + ), + signatures=dict(Counter(c["failure_signature"] for c in cases)), + **{f"fail_{k}": sum(c["failure_flags"][k] for c in cases) for k in ("E", "D", "U")}, + ) + for g in RETENTION_GROUPS: + rates = [c["final"]["U_heldout_destruction"][g]["rate"] for c in cases] + result[f"fail_U{g}"] = sum(r is not None and r > 0.01 for r in rates) + result[f"mean_U{g}_damage"] = float(np.mean([r for r in rates if r is not None])) + result["D_error_counts"] = dict( + sum((Counter(c["propagation"]["counts"]) for c in cases), Counter()) + ) + result["mean_initial_new_answer_nll"] = float(np.mean([c["initial_nll"] for c in cases])) + return result + + +def run(args): + root, out = Path(args.root), Path(args.output) + out.mkdir(parents=True, exist_ok=True) + worlds = {i: load_world(f"data/bios-work-v1/world-{i}") for i in (0, 1)} + cases, audit, timelines = [], [], [] + lookup = {} + for run_dir in sorted(root.glob("world-*-seed-*-*")): + config = read(run_dir / "config.json") + world = worlds[config["world_seed"]] + for dirname, window in (("edits", 3), ("edits-window0", 0)): + completed = read(run_dir / dirname / "complete.json") + assert completed["status"] == "complete" and len(completed["cases"]) == 16 + for path in sorted((run_dir / dirname).glob("*/complete.json")): + c = read(path) + assert c["status"] == "complete" and c["final"]["step"] == 512 + assert c["window_zero_based"] == list(range(window, window + 3)) + sets = dict(np.load(path.parent / "sets.npz")) + pred = dict(np.load(path.parent / "predictions-512.npz")) + correct = (pred["prediction"] == sets["target"]) & pred["ended"] + np.testing.assert_array_equal(correct, pred["correct"]) + retention = retention_counts(sets, correct, sets["old_correct"]) + assert retention == c["final"]["U_heldout_destruction"] + for name, ids in ( + ("E", sets["E"]), + ("D", sets["D"]), + ("E_root", sets["E"][world.relation[sets["E"]] == 1]), + ("E_member", sets["E"][world.relation[sets["E"]] == 2]), + ): + assert float(correct[ids].mean()) == c["final"][name] + trajectory = read(path.parent / "trajectory.json") + for point in trajectory: + flags = failure_flags(point) + expected = None if flags["unevaluable"] else not any(flags.values()) + assert point["joint_pass"] == expected + flags = failure_flags(c["final"]) + damaged_by_relation = {} + for group, mask in retention_masks(sets, sets["old_correct"]).items(): + broken = mask & ~correct + damaged_by_relation[group] = { + name: int((broken & (world.relation == relation)).sum()) + for relation, name in enumerate((*RELATIONS, "derived_default_city")) + } + assert sum(damaged_by_relation[group].values()) == int(broken.sum()) + method = f"FT-{c['scope'].upper()}" + if c["branch"]: + method += f"+{c['branch']}" + meta = { + "run": run_dir.name, + "world": world.seed, + "seed": config["seed"], + "order": config["order"], + "window": window, + "method": method, + "kind": c["kind"], + "support": c["support"], + } + c.update( + meta, + directory=str(path.parent), + failure_flags=flags, + failure_signature=failure_signature(flags), + heldout_damage_by_relation=damaged_by_relation, + propagation=propagation_errors(world, sets, pred), + replay_retention=retention_counts(sets, correct, sets["old_correct"], "replay"), + initial_nll=trajectory[0]["E_target_value_nll"], + ever_E=any(not failure_flags(p)["E"] for p in trajectory), + ever_D=any(not failure_flags(p)["D"] for p in trajectory), + ever_U=any(not failure_flags(p)["U"] for p in trajectory), + last_failure_free_E_step=max( + (p["step"] for p in trajectory if not failure_flags(p)["E"]), default=None + ), + down_calibration=c["final"].get("down_calibration"), + ) + cases.append(c) + lookup[(run_dir.name, window, method, c["kind"], c["support"])] = (c, sets, pred) + audit.append( + {"path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()} + ) + timelines.extend( + {**meta, **p, "failure_flags": failure_flags(p)} for p in trajectory + ) + assert len(cases) == 256 + groups = defaultdict(list) + for c in cases: + groups[(c["window"], c["method"], c["order"], c["kind"])].append(c) + aggregates = [ + {"window": w, "method": m, "order": o, "kind": k, **summarize_group(cs)} + for (w, m, o, k), cs in sorted(groups.items()) + ] + common, duplicates, branch_pairs = [], [], [] + for (run_name, window, method, kind, support), (case, sets, pred) in lookup.items(): + if case["order"] == "SA": + other, other_sets, other_pred = lookup[ + (run_name[:-2] + "AS", window, method, kind, support) + ] + for field in ( + "E", + "D", + "target", + "heldout", + "replay", + "strata", + "edit_sampling", + "replay_sampling", + ): + np.testing.assert_array_equal(sets[field], other_sets[field]) + known = sets["old_correct"] & other_sets["old_correct"] + sa = retention_counts(sets, pred["correct"], known) + ass = retention_counts(sets, other_pred["correct"], known) + common.append( + { + "world": case["world"], + "seed": case["seed"], + "window": window, + "method": method, + "kind": kind, + "support": support, + "SA": sa, + "AS": ass, + } + ) + if method == "FT-ALL" and window == 3: + _, _, duplicate = lookup[(run_name, 0, method, kind, support)] + duplicates.append( + { + "run": run_name, + "kind": kind, + "support": support, + "identical_final_predictions": bool( + all(np.array_equal(pred[k], duplicate[k]) for k in pred) + ), + } + ) + if case["branch"]: + baseline, _, baseline_pred = lookup[(run_name, window, "FT-MLP", kind, support)] + branch_pairs.append( + { + "run": run_name, + "window": window, + "method": method, + "kind": kind, + "support": support, + **{f"delta_{k}": case["final"][k] - baseline["final"][k] for k in ("E", "D")}, + "baseline_joint": baseline["final"]["joint_pass"], + "branch_joint": case["final"]["joint_pass"], + "changed_predictions_vs_baseline": int( + (pred["prediction"] != baseline_pred["prediction"]).sum() + ), + "max_value_nll_difference_vs_baseline": float( + np.max(np.abs(pred["value_nll"] - baseline_pred["value_nll"])) + ), + } + ) + sensitivity = [] + for (window, method, order, kind), cs in sorted(groups.items()): + for accuracy in (0.90, 0.95, 0.99): + for damage in (0.0, 0.01, 0.02, 0.05): + sensitivity.append( + { + "window": window, + "method": method, + "order": order, + "kind": kind, + "accuracy_threshold": accuracy, + "damage_threshold": damage, + "n": len(cs), + "final_pass": sum( + not any(failure_flags(c["final"], accuracy, damage).values()) + for c in cs + ), + } + ) + quality = [] + for world in (0, 1): + for seed in (0, 1): + sa, ass = [ + read(root / f"world-{world}-seed-{seed}-{order}" / "complete.json")["final"] + for order in ("SA", "AS") + ] + quality.append( + { + "world": world, + "seed": seed, + "base_difference_pp": 100 * (sa["base_accuracy"] - ass["base_accuracy"]), + "derived_difference_pp": 100 + * (sa["derived_accuracy"] - ass["derived_accuracy"]), + "passed": bool( + min( + sa["base_accuracy"], + ass["base_accuracy"], + sa["derived_accuracy"], + ass["derived_accuracy"], + ) + >= 0.99 + and abs(sa["base_accuracy"] - ass["base_accuracy"]) <= 0.005 + and abs(sa["derived_accuracy"] - ass["derived_accuracy"]) <= 0.005 + and abs(sa["value_nll"] - ass["value_nll"]) <= 0.1 + ), + } + ) + quality_keys = {(q["world"], q["seed"]) for q in quality if q["passed"]} + quality_aggregates = [] + for (w, m, o, k), cs in sorted(groups.items()): + subset = [c for c in cs if (c["world"], c["seed"]) in quality_keys] + quality_aggregates.append( + {"window": w, "method": m, "order": o, "kind": k, **summarize_group(subset)} + ) + report = { + "phase": "symbolic development; descriptive; not independent edit replicates", + "cases": cases, + "groups": aggregates, + "common_known_retention": common, + "branch_paired_support0": branch_pairs, + "ft_all_window_duplicates": duplicates, + "quality_pairs": quality, + "quality_subset_groups": quality_aggregates, + "sensitivity": sensitivity, + "source_audit": audit, + "expected_cases": 256, + "audited_cases": len(cases), + } + write_json(out / "failure-analysis.json", report) + write_json(out / "edit-trajectories.json", timelines) + dump_csv( + out / "failure-summary.csv", + [{k: v for k, v in row.items() if not isinstance(v, dict)} for row in aggregates], + ) + dump_csv(out / "threshold-sensitivity.csv", sensitivity) + dump_csv(out / "branch-paired-support0.csv", branch_pairs) + dump_csv( + out / "case-failures.csv", + [ + { + **{ + k: c[k] + for k in ( + "run", + "world", + "seed", + "order", + "window", + "method", + "kind", + "support", + "failure_signature", + "first_observed_joint_step", + "initial_nll", + ) + }, + **{k: c["final"][k] for k in ("E", "E_root", "E_member", "D", "joint_pass")}, + } + for c in cases + ], + ) + print( + json.dumps( + { + "audited_cases": len(cases), + "groups": len(aggregates), + "quality_pairs_passed": len(quality_keys), + "FT_ALL_identical_duplicate_cases": sum( + d["identical_final_predictions"] for d in duplicates + ), + } + ) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", default="results/bios-dev-v1") + parser.add_argument("--output", default="results/bios-dev-v1/failure-analysis-20260926") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_branch.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c6ebef8f0f501ac43d2d94de8f4f59b954208b --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_branch.py @@ -0,0 +1,127 @@ +"""Equal-parameter residual branches from old-world activation directions.""" + +import time + +import numpy as np +import torch +from torch import nn + +from .bios_data import ANS +from .bios_train import precision + + +class ResidualBranch(nn.Module): + def __init__(self, q, mean, scale, width=32, seed=73): + super().__init__() + self.register_buffer("q", q) + self.register_buffer("mean", mean) + self.register_buffer("scale", scale) + # Explicit local RNG: same A in all arms without changing training RNG state. + generator = torch.Generator(device=q.device).manual_seed(seed) + self.a = nn.Parameter( + torch.randn(width, q.shape[1], generator=generator, device=q.device) / q.shape[1] ** 0.5 + ) + self.b = nn.Parameter(torch.zeros(q.shape[0], width, device=q.device)) + + def forward(self, v): + s = (v.float() @ self.q - self.mean) / self.scale + return (torch.nn.functional.gelu(s @ self.a.T) @ self.b.T).to(v.dtype) + + +@torch.no_grad() +def build_bases(model, world, data, layer=4, rank=32): + device = data["tokens"].device + values = [] + + def capture(_module, _inputs, output): + values.append(output[:, 3].float()) + + handle = model.blocks[layer].register_forward_hook(capture) + started = time.perf_counter() + try: + with precision(device): + for begin in range(2112, 4160, 256): + model( + data["prompts"][begin : begin + 256], + data["lengths"][begin : begin + 256, None] - 1, + ) + finally: + handle.remove() + v = torch.cat(values) + group_means = torch.stack( + [v[torch.as_tensor(world.employers == c, device=device)].mean(0) for c in range(64)] + ) + centered_means = group_means - v.mean(0) + _, shared_s, shared_vh = torch.linalg.svd(centered_means, full_matrices=False) + q_shared = shared_vh[:rank].T.contiguous() + residual = v - group_means[torch.as_tensor(world.employers, device=device)] + residual = residual - (residual @ q_shared) @ q_shared.T + _, independent_s, independent_vh = torch.linalg.svd(residual, full_matrices=False) + q_independent = independent_vh[:rank].T.contiguous() + valid = bool( + shared_s[rank - 1] > shared_s[0] * 1e-6 + and independent_s[rank - 1] > independent_s[0] * 1e-6 + ) + if not valid: + return None, {"available": False, "reason": "fewer than 32 nondegenerate directions"} + generator = torch.Generator(device=device).manual_seed(74) + q_random = torch.linalg.qr(torch.randn(v.shape[1], rank, generator=generator, device=device)).Q + bases, checks = {}, {} + for kind, q in (("shared", q_shared), ("independent", q_independent), ("random", q_random)): + projected = v @ q + mean, std = projected.mean(0), projected.std(0, correction=0) + std = std.clamp_min(0.01 * std.square().mean().sqrt()) + normalized = (projected - mean) / std + # Equal total variance across all branches (one, not dependent on their rank). + scale = std * normalized.square().sum(-1).mean().sqrt() + bases[kind] = (q, mean, scale) + normalized = (projected - mean) / scale + within = [] + for c in range(64): + mask = (world.employers == c) & ~world.exceptions + z = normalized[torch.as_tensor(mask, device=device)] + within.append((z - z.mean(0)).square().sum(-1).mean().item()) + checks[kind] = { + "same_company_relation_old_answer_identity_variance": float(np.mean(within)), + "total_variance": normalized.square().sum(-1).mean().item(), + } + if device.type == "cuda": + torch.cuda.synchronize(device) + return bases, { + "available": True, + "construction_seconds": time.perf_counter() - started, + "rank": rank, + "shared_32nd_relative_singular_value": (shared_s[rank - 1] / shared_s[0]).item(), + "independent_32nd_relative_singular_value": ( + independent_s[rank - 1] / independent_s[0] + ).item(), + "checks": checks, + } + + +def attach_branch(model, basis, layer=4, width=32): + branch = ResidualBranch(*basis, width=width) + model.add_module("edit_branch", branch) + + def save_position(_module, args): + branch.positions = args[0].eq(ANS).long().argmax(-1) + + def add(_module, _inputs, output): + rows = torch.arange(len(output), device=output.device) + result = output.clone() + result[rows, branch.positions] = result[rows, branch.positions] + branch( + output[rows, branch.positions] + ) + return result + + handles = [ + model.register_forward_pre_hook(save_position), + model.blocks[layer].register_forward_hook(add), + ] + return branch, handles + + +def remove_branch(model, handles): + for handle in handles: + handle.remove() + delattr(model, "edit_branch") diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_capacity.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_capacity.py new file mode 100644 index 0000000000000000000000000000000000000000..d07d84eb1c19bc5055e15255b0de00799b8713c5 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_capacity.py @@ -0,0 +1,48 @@ +"""Predeclared splits and query-level capacity diagnostics.""" + +import numpy as np + +from .bios_data import N_BASE, N_QUERIES, rng_for + + +def qa_split(world, mode): + if mode == "all": + return np.arange(N_BASE, N_QUERIES), np.array([], dtype=np.int64) + if mode != "half": + raise ValueError("Unknown QA split") + rng = rng_for(world.seed, 910) + train, heldout = [], [] + for company in np.unique(world.employers): + for exception in (False, True): + people = np.flatnonzero((world.employers == company) & (world.exceptions == exception)) + people = rng.permutation(people) + train.extend((N_BASE + people[: len(people) // 2]).tolist()) + heldout.extend((N_BASE + people[len(people) // 2 :]).tolist()) + return np.sort(train), np.sort(heldout) + + +def split_metrics(world, arrays, train_ids, heldout_ids): + correct, nll = arrays["correct"], arrays["value_nll"] + # The derivation needs the person's employer and that employer's default city. + # Build by semantic IDs rather than assuming a base-fact row layout. + employer = {int(world.person[i]): i for i in np.flatnonzero(world.relation == 0)} + defaults = {int(world.company[i]): i for i in np.flatnonzero(world.relation == 1)} + result = {} + for name, ids in (("trained", train_ids), ("heldout", heldout_ids)): + result[f"derived_{name}_count"] = len(ids) + result[f"derived_{name}_accuracy"] = float(correct[ids].mean()) if len(ids) else None + result[f"derived_{name}_nll"] = float(nll[ids].mean()) if len(ids) else None + eligible = np.array( + [ + i + for i in ids + if correct[employer[int(world.person[i])]] + and correct[defaults[int(world.company[i])]] + ], + dtype=np.int64, + ) + result[f"derived_{name}_known_components_count"] = len(eligible) + result[f"derived_{name}_known_components_accuracy"] = ( + float(correct[eligible].mean()) if len(eligible) else None + ) + return result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_causal_paths.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_causal_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2d8963ce2c5db80362fdd38cc80e83c8415b53 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_causal_paths.py @@ -0,0 +1,455 @@ +"""Offline donor-state interventions on frozen crossover models. + +Truth is used to match donor/recipient pairs and score outputs, never supplied as +an answer or bridge to the model. This is a causal diagnostic, not an editor. +""" + +import csv +import json +from pathlib import Path + +import numpy as np + +from .bios_cross import CHAINS, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_path_diagnostics import ( + INDISTINGUISHABLE, + classify_answers, + file_sha256, + free_generate_values, +) + +PAIR_TYPES = ( + "same_group_different_actual", + "different_group_same_actual_different_default", + "same_group_same_actual_different_person", + "different_group_different_actual_different_default", +) +POSITIONS = (2, 3, 4) +ANSWER_ROLES = ("recipient_default", "recipient_actual", "donor_default", "donor_actual") + + +def make_donor_plan(world, chain, per_population=64): + """Select using truth and train/heldout membership only, with fixed RNG. + + A missing donor stays -1. No prediction- or success-based replacement occurs. + The same world yields identical pairs across sizes, conditions and model seeds. + """ + heldout = world.person[world.heldout_ids[chain]] + train = world.person[world.train_ids[chain]] + rng = rng_for(world.seed, 971, chain) + recipients = [] + for exceptional in (False, True): + pool = heldout[world.exceptions[chain, heldout] == exceptional] + if len(pool) < per_population: + raise ValueError("Not enough heldout recipients for predeclared sample") + recipients.extend(rng.choice(pool, per_population, replace=False)) + recipients = np.asarray(recipients, dtype=np.int64) + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + recipient_rows, donor_rows, type_rows, candidate_counts = [], [], [], [] + for recipient in recipients: + same_group = group[train] == group[recipient] + same_actual = actual[train] == actual[recipient] + same_default = default[train] == default[recipient] + masks = ( + same_group & ~same_actual, + ~same_group & same_actual & ~same_default, + same_group & same_actual & (train != recipient), + ~same_group & ~same_actual & ~same_default, + ) + for pair_type, mask in enumerate(masks): + candidates = train[mask] + recipient_rows.append(recipient) + donor_rows.append(rng.choice(candidates) if len(candidates) else -1) + type_rows.append(pair_type) + candidate_counts.append(len(candidates)) + donor_rows = np.asarray(donor_rows, dtype=np.int64) + complete = (donor_rows.reshape(-1, len(PAIR_TYPES)) >= 0).all(axis=1) + return { + "case_id": np.arange(len(donor_rows), dtype=np.int64), + "recipient": np.asarray(recipient_rows, dtype=np.int64), + "donor": donor_rows, + "pair_type": np.asarray(type_rows, dtype=np.int8), + "candidate_count": np.asarray(candidate_counts, dtype=np.int32), + "common_recipient": np.repeat(complete, len(PAIR_TYPES)), + "recipient_old_exception": world.exceptions[chain, recipient_rows], + } + + +def intervention_state(recipient_state, donor_state, intervention, seed): + """Random control matches the donor-minus-recipient perturbation norm per row.""" + if recipient_state.shape != donor_state.shape: + raise ValueError("Activation shapes do not match") + delta = donor_state.astype(np.float64) - recipient_state.astype(np.float64) + norms = np.linalg.norm(delta, axis=-1) + if intervention == "donor": + patched = donor_state.copy() + elif intervention == "sham": + patched = recipient_state.copy() + elif intervention == "matched_random": + noise = np.random.default_rng(seed).standard_normal(delta.shape) + noise /= np.maximum(np.linalg.norm(noise, axis=-1, keepdims=True), 1e-30) + patched = (recipient_state + noise * norms[:, None]).astype(recipient_state.dtype) + else: + raise ValueError("Unknown intervention") + actual_norms = np.linalg.norm(patched.astype(np.float64) - recipient_state, axis=-1) + return patched, norms, actual_norms + + +def cache_clean_states(model, prompts, lengths, device, batch_size=256): + """Capture post-block residuals at fixed positions for clean prompt passes.""" + import torch + + from .bios_train import precision + + states = [[] for _ in model.blocks] + hooks = [] + for layer, block in enumerate(model.blocks): + + def capture(module, inputs, output, layer=layer): + states[layer].append(output[:, POSITIONS, :].detach().float().cpu().numpy()) + + hooks.append(block.register_forward_hook(capture)) + model.eval() + try: + with torch.no_grad(): + for start in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[start : start + batch_size], device=device) + n = torch.as_tensor(lengths[start : start + batch_size], device=device) + with precision(device): + model(p, (n - 1)[:, None]) + finally: + for hook in hooks: + hook.remove() + return np.stack([np.concatenate(layer_states) for layer_states in states]) + + +def generate_with_state_patch( + model, prompts, lengths, replacements, layer, position, device, batch_size=256 +): + """Apply the same pre-answer state patch in value and EOS generation passes. + + Positions <= 4 cannot depend on the generated token at position 5 under the + causal mask, so the clean prompt cache contains no teacher-forced answer. + """ + import torch + + from .bios_train import precision + + if position not in POSITIONS or np.any(lengths != 5): + raise ValueError("This diagnostic is restricted to five-token derived queries") + predictions, ended = [], [] + model.eval() + with torch.no_grad(): + for start in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[start : start + batch_size], device=device) + n = torch.as_tensor(lengths[start : start + batch_size], device=device) + replacement = torch.as_tensor(replacements[start : start + batch_size], device=device) + + def patch(module, inputs, output, replacement=replacement): + changed = output.clone() + changed[:, position] = replacement.to(output.dtype) + return changed + + hook = model.blocks[layer].register_forward_hook(patch) + try: + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), device=device, dtype=torch.long) + continuation[:, :5] = p + continuation[:, 5] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + finally: + hook.remove() + return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)} + + +def _candidate_values(world, chain, recipients, donors): + default = world.answers[world.root_ids[chain, world.memberships[chain]]] + actual = world.answers[world.actual_ids[chain]] + return np.column_stack( + [default[recipients], actual[recipients], default[donors], actual[donors]] + ) + + +def _node_rows(arrays, identity): + rows = [] + for pair_type, label in enumerate(PAIR_TYPES): + for population in ("all", "ordinary", "old_exception"): + for common_only in (False, True): + selected = arrays["pair_type"] == pair_type + if population != "all": + selected &= arrays["recipient_old_exception"] == (population == "old_exception") + if common_only: + selected &= arrays["common_recipient"] + n = int(selected.sum()) + before = arrays["baseline_correct"][selected] + after = arrays["correct"][selected] + row = { + **identity, + "pair_type": label, + "population": population, + "common_recipients_only": common_only, + "n": n, + "baseline_correct": int(before.sum()), + "correct": int(after.sum()), + "known_became_wrong": int((before & ~after).sum()), + "wrong_became_correct": int((~before & after).sum()), + "termination_error": int((~arrays["ended"][selected]).sum()), + "prediction_changed": int( + ( + arrays["prediction"][selected] + != arrays["baseline_prediction"][selected] + ).sum() + ), + "indistinguishable": int( + (arrays["class_code"][selected] == INDISTINGUISHABLE).sum() + ), + "mean_perturbation_norm": float(arrays["perturbation_norm"][selected].mean()) + if n + else None, + } + for i, role in enumerate(ANSWER_ROLES): + row[f"matches_{role}"] = int( + ( + ((arrays["matched_role_bits"][selected] & (1 << i)) != 0) + & arrays["ended"][selected] + ).sum() + ) + rows.append(row) + return rows + + +def diagnose_causal_run(run, output, step=15360, device="cuda", batch_size=256, per_population=64): + """One model, both relations, all layers/positions with fixed donor controls.""" + import torch + + from .bios_model import CausalLM, ModelConfig + from .bios_organization_train import atomic_numpy_save + + repository = Path(__file__).resolve().parents[2] + run, output = Path(run).resolve(), Path(output).resolve() + if output == run or run in output.parents: + raise ValueError("Never write causal diagnostics inside frozen training runs") + output.mkdir(parents=True, exist_ok=True) + config = json.loads((run / "config.json").read_text()) + if config["world"] not in (0, 1) or config["model"]["width"] not in (256, 768): + raise ValueError("This development diagnostic is frozen to worlds 0/1, widths 256/768") + checkpoint = run / f"model-{step}.pt" + device = torch.device(device) + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if array_hash(world.answers) != config["truth_sha256"]: + raise ValueError("World truth mismatch") + identity = { + "run": str(run), + "checkpoint": str(checkpoint), + "step": step, + "checkpoint_sha256": file_sha256(checkpoint), + "config_sha256": file_sha256(run / "config.json"), + "diagnostic_source_sha256": file_sha256(__file__), + "generation_helper_sha256": file_sha256( + repository / "src/llm_memory_editability/bios_path_diagnostics.py" + ), + "world": config["world"], + "seed": config["seed"], + "condition": config["condition"], + "width": config["model"]["width"], + "per_population": per_population, + "positions": list(POSITIONS), + "device_type": device.type, + "batch_size": batch_size, + "torch": torch.__version__, + "offline_truth_matching": True, + "role": "candidate_localization" if config["world"] == 0 else "development_replication", + } + config_path = output / "config.json" + if config_path.exists(): + if json.loads(config_path.read_text()) != identity: + raise ValueError("Causal diagnostic identity changed") + else: + write_json(config_path, identity) + if (output / "complete.json").exists(): + return + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + rows, plan_rows = [], [] + source_output_hashes = {} + for chain, name in enumerate(CHAINS): + dest = output / name + dest.mkdir(exist_ok=True) + plan = make_donor_plan(world, chain, per_population) + plan_path = dest / "plan.npz" + if plan_path.exists(): + with np.load(plan_path) as existing: + if any(not np.array_equal(existing[k], v) for k, v in plan.items()): + raise ValueError("Saved donor plan differs") + else: + atomic_numpy_save(plan_path, **plan) + source_output_hashes[str(plan_path.relative_to(output))] = file_sha256(plan_path) + valid = plan["donor"] >= 0 + selected = {k: v[valid] for k, v in plan.items()} + recipients, donors = selected["recipient"], selected["donor"] + for pair_type, label in enumerate(PAIR_TYPES): + for exceptional in (False, True): + matching = (plan["pair_type"] == pair_type) & ( + plan["recipient_old_exception"] == exceptional + ) + plan_rows.append( + { + "chain": name, + "pair_type": label, + "population": "old_exception" if exceptional else "ordinary", + "requested": int(matching.sum()), + "valid": int((matching & valid).sum()), + "missing": int((matching & ~valid).sum()), + } + ) + people = np.unique(np.concatenate([recipients, donors])) + ids = world.derived_ids[chain, people] + cache_path = dest / "clean-cache.npz" + if cache_path.exists(): + with np.load(cache_path) as cache: + states = cache["states"] + baseline = {k: cache[k] for k in ("prediction", "ended")} + if not np.array_equal(cache["people"], people): + raise ValueError("Clean cache people mismatch") + else: + states = cache_clean_states( + model, world.prompts[ids], world.lengths[ids], device, batch_size + ) + baseline = free_generate_values( + model, world.prompts[ids], world.lengths[ids], device, batch_size + ) + atomic_numpy_save(cache_path, people=people, states=states, **baseline) + source_output_hashes[str(cache_path.relative_to(output))] = file_sha256(cache_path) + ri, di = np.searchsorted(people, recipients), np.searchsorted(people, donors) + recipient_queries = world.derived_ids[chain, recipients] + candidates = _candidate_values(world, chain, recipients, donors) + base = { + **selected, + "recipient_query": recipient_queries, + "donor_query": world.derived_ids[chain, donors], + "candidate_tokens": candidates, + "baseline_prediction": baseline["prediction"][ri], + "baseline_ended": baseline["ended"][ri], + "baseline_correct": (baseline["prediction"][ri] == candidates[:, 0]) + & baseline["ended"][ri], + } + for layer in range(len(model.blocks)): + for position_index, position in enumerate(POSITIONS): + receiver_states = states[layer, ri, position_index] + donor_states = states[layer, di, position_index] + seed = [world.seed, 972, chain, layer, position] + for intervention in ("donor", "matched_random", "sham"): + node = dest / f"layer-{layer}-position-{position}-{intervention}.npz" + if node.exists(): + with np.load(node) as existing: + arrays = dict(existing) + if not np.array_equal(arrays["case_id"], selected["case_id"]): + raise ValueError("Saved node case mismatch") + else: + replacement, donor_norm, actual_norm = intervention_state( + receiver_states, donor_states, intervention, seed + ) + generated = generate_with_state_patch( + model, + world.prompts[recipient_queries], + world.lengths[recipient_queries], + replacement, + layer, + position, + device, + batch_size, + ) + classes, bits = classify_answers( + generated["prediction"], generated["ended"], candidates + ) + arrays = { + **base, + **generated, + "class_code": classes, + "matched_role_bits": bits, + "correct": (generated["prediction"] == candidates[:, 0]) + & generated["ended"], + "donor_delta_norm": donor_norm, + "perturbation_norm": actual_norm, + } + atomic_numpy_save(node, **arrays) + source_output_hashes[str(node.relative_to(output))] = file_sha256(node) + node_identity = { + "world": world.seed, + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "chain": name, + "layer": layer, + "position": position, + "intervention": intervention, + "terminal_control": layer == len(model.blocks) - 1, + } + rows.extend(_node_rows(arrays, node_identity)) + print( + json.dumps( + { + "event": "causal_node_complete", + "run": str(run), + "chain": name, + "layer": layer, + "position": position, + } + ), + flush=True, + ) + for filename, contents in (("summary.csv", rows), ("pair-coverage.csv", plan_rows)): + with (output / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + output / "schema.json", + { + "pair_types": PAIR_TYPES, + "answer_roles": ANSWER_ROLES, + "state": "post-transformer-block residual stream", + "positions": { + "2": "membership relation", + "3": "default relation", + "4": "answer marker", + }, + "world_roles": { + "0": "candidate localization", + "1": "development replication, not confirmation", + }, + "random_control": "Random vector matched per case to ||donor_state-recipient_state||_2", + "matching": "True group/actual/default answers select pairs offline; prompts contain " + "no true answer or true bridge entity.", + "missing": "No donor replacement across types; no prediction-based recipient selection", + "common_recipients": "Auxiliary rows require all four donor types; truth-selected", + "last_layer_controls": "Positions 2/3 cannot affect other tokens after final block; " + "position 4 directly changes value readout and is not routing evidence.", + "causal_scope": "Single-state replacement establishes an intervention effect, not a " + "unique mechanism or strict necessity. Same-point restoration equals sham.", + "eos": "Value and EOS are independently generated with identical intervention; " + "non-terminated values are failures even if an answer candidate matches.", + "overlap": "All matched roles retained; multiple roles remain indistinguishable", + }, + ) + write_json(output / "artifacts.json", source_output_hashes) + write_json( + output / "complete.json", + { + "complete": True, + "identity": identity, + "node_files": 2 * len(model.blocks) * len(POSITIONS) * 3, + "plan_rows": plan_rows, + "artifacts_sha256": file_sha256(output / "artifacts.json"), + }, + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_confirmation_stats.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_confirmation_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..27d0d82cc96b250b88771946b569218a090bee50 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_confirmation_stats.py @@ -0,0 +1,280 @@ +"""Locked world-level inference for the narrower shortcut confirmation. + +This module consumes independently audited endpoint counts, never query outcomes +for selecting hypotheses. Nested seeds, organizations, chains and supports are +averaged within a world before any inferential calculation. +""" + +import itertools +import math + +DEFAULT_STATISTICS = { + "revision": "shortcut-confirmation-statistics-v1", + "scope": "training-correlation behavioral confirmation, not organization-path mediation", + "worlds": list(range(100, 108)), + "seeds": [0, 1], + "conditions": ["company", "project", "neither"], + "chains": ["company", "project"], + "prevalences": ["low", "high"], + "supports": [0, 1], + "kinds": ["coherent", "exception"], + "width": 256, + "learning_step": 15360, + "editing_step": 512, + "learning_denominator": 64, + "editing_denominator": 9, + "primary_endpoint": "editing_exception_fixed9", + "confirmatory_family": [ + "editing_exception_fixed9", + "learning_original_exception", + "editing_coherent_fixed9", + ], + "contrast": "high-minus-low", + "unit": "world; all nested pairs equally weighted within each world", + "test": "two-sided one-sample t on eight world-level paired differences, df=7", + "assumption": "independent generated worlds; approximately normal world-level differences", + "multiplicity": "Holm across the three confirmatory endpoints, family alpha=0.05", + "intervals": ["95% marginal t", "98.33333333333333% Bonferroni simultaneous t"], + "sensitivity": "all 256 world sign flips; valid under null sign symmetry, not an " + "unconditional randomized-treatment test", + "zero_sd": "all-zero differences: t=0,p=1,CI=[0,0], degenerate/no equivalence; " + "constant nonzero differences: t/p/CI=null, Holm input=1, adjusted p=1", + "stopping": "fixed eight worlds; no interim outcome inspection or optional extension", + "publication": "all three endpoints, signs, all E/U/global-D/base checks published " + "regardless of significance; no automatic natural-language or editor-method trigger", +} + + +def _beta_fraction(a, b, x): + tiny, tolerance = 1e-300, 3e-14 + qab, qap, qam = a + b, a + 1, a - 1 + c, d = 1.0, 1.0 - qab * x / qap + d = 1 / (d if abs(d) >= tiny else tiny) + h = d + for m in range(1, 401): + double = 2 * m + aa = m * (b - m) * x / ((qam + double) * (a + double)) + d, c = 1 + aa * d, 1 + aa / c + d = 1 / (d if abs(d) >= tiny else tiny) + c = c if abs(c) >= tiny else tiny + h *= d * c + aa = -(a + m) * (qab + m) * x / ((a + double) * (qap + double)) + d, c = 1 + aa * d, 1 + aa / c + d = 1 / (d if abs(d) >= tiny else tiny) + c = c if abs(c) >= tiny else tiny + factor = d * c + h *= factor + if abs(factor - 1) <= tolerance: + return h + raise ArithmeticError("Incomplete beta continued fraction did not converge") + + +def regularized_beta(x, a, b): + if not (0 <= x <= 1 and a > 0 and b > 0): + raise ValueError("Invalid beta arguments") + if x in (0, 1): + return float(x) + scale = math.exp( + math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x) + ) + if x < (a + 1) / (a + b + 2): + result = scale * _beta_fraction(a, b, x) / a + else: + result = 1 - scale * _beta_fraction(b, a, 1 - x) / b + return min(1.0, max(0.0, result)) + + +def t_two_sided_p(statistic, degrees): + if degrees <= 0 or not math.isfinite(statistic): + raise ValueError("Finite t and positive degrees of freedom required") + return regularized_beta(degrees / (degrees + statistic**2), degrees / 2, 0.5) + + +def t_critical(alpha, degrees): + if not (0 < alpha < 1 and degrees > 0): + raise ValueError("Invalid t quantile arguments") + lower, upper = 0.0, 1.0 + while t_two_sided_p(upper, degrees) > alpha: + upper *= 2 + for _ in range(100): + middle = (lower + upper) / 2 + if t_two_sided_p(middle, degrees) > alpha: + lower = middle + else: + upper = middle + return (lower + upper) / 2 + + +def holm(p_values): + """Unavailable p-values conservatively occupy a place in the family as 1.""" + values = [1.0 if p is None else float(p) for p in p_values] + if any(not math.isfinite(p) or not 0 <= p <= 1 for p in values): + raise ValueError("p-values must be finite and in [0,1], or None") + order = sorted(range(len(values)), key=lambda i: (values[i], i)) + result, previous = [None] * len(values), 0.0 + for rank, index in enumerate(order): + previous = max(previous, min(1.0, (len(values) - rank) * values[index])) + result[index] = previous + return result + + +def sign_flip_sensitivity(values): + if len(values) != 8 or not all(math.isfinite(x) for x in values): + raise ValueError("Exactly eight finite world differences required") + observed = abs(math.fsum(values)) + tolerance = 1e-12 * max(1.0, math.fsum(abs(x) for x in values)) + extreme = sum( + abs(math.fsum(s * x for s, x in zip(signs, values, strict=True))) >= observed - tolerance + for signs in itertools.product((-1, 1), repeat=8) + ) + return {"p": extreme / 256, "extreme": extreme, "enumerated": 256} + + +def world_t_statistics(values): + values = [float(x) for x in values] + if len(values) != 8 or not all(math.isfinite(x) for x in values): + raise ValueError("Exactly eight finite world differences required") + mean = math.fsum(values) / 8 + variance = math.fsum((value - mean) ** 2 for value in values) / 7 + sd = math.sqrt(variance) + result = { + "worlds": 8, + "df": 7, + "mean": mean, + "sd": sd, + "sign_flip_sensitivity": sign_flip_sensitivity(values), + } + if max(values) == min(values): + zero = values[0] == 0 + result.update( + status="degenerate_zero" if zero else "degenerate_nonzero", + t=0.0 if zero else None, + p=1.0 if zero else None, + ci95=[0.0, 0.0] if zero else None, + ci_bonferroni=[0.0, 0.0] if zero else None, + ) + return result + standard_error = sd / math.sqrt(8) + statistic = mean / standard_error + result.update(status="estimable", t=statistic, p=t_two_sided_p(statistic, 7)) + for key, alpha in [("ci95", 0.05), ("ci_bonferroni", 0.05 / 3)]: + half = t_critical(alpha, 7) * standard_error + result[key] = [mean - half, mean + half] + return result + + +def _integer(value, label): + if isinstance(value, bool): + raise ValueError(f"Boolean integer for {label}") + parsed = int(value) + if isinstance(value, str) and str(parsed) != value: + raise ValueError(f"Noncanonical integer for {label}: {value!r}") + if not isinstance(value, str) and parsed != value: + raise ValueError(f"Noninteger value for {label}: {value!r}") + return parsed + + +def validate_endpoints(rows, editing=False): + keys = ["world", "seed", "condition", "chain", "prevalence"] + if editing: + keys += ["support", "kind"] + indexed = {} + for raw in rows: + row = dict(raw) + if not editing and "support" in row: + raise ValueError("Learning endpoints must not be repeated or labeled by support") + for name in ["world", "seed", "step", "n", "correct"] + (["support"] if editing else []): + row[name] = _integer(row[name], name) + if "width" in row and _integer(row["width"], "width") != 256: + raise ValueError("Unexpected model width") + if row["step"] != (512 if editing else 15360): + raise ValueError("Endpoint step differs from the fixed budget") + if row["n"] != (9 if editing else 64) or not 0 <= row["correct"] <= row["n"]: + raise ValueError("Fixed cohort count is invalid") + if not editing and (row["cohort"] != "original_exception" or row["split"] != "heldout"): + raise ValueError("Wrong learning cohort or split") + key = tuple(row[k] for k in keys) + if key in indexed: + raise ValueError(f"Duplicate endpoint: {key}") + indexed[key] = row + dimensions = [ + range(100, 108), + (0, 1), + ("company", "project", "neither"), + ("company", "project"), + ("low", "high"), + ] + if editing: + dimensions += [(0, 1), ("coherent", "exception")] + expected = set(itertools.product(*dimensions)) + if set(indexed) != expected: + raise ValueError( + f"Endpoint matrix mismatch: missing {len(expected - set(indexed))}, " + f"unexpected {len(set(indexed) - expected)}" + ) + return indexed + + +def analyze_endpoints(learning, editing): + learning = validate_endpoints(learning) + editing = validate_endpoints(editing, editing=True) + world_rows, case_rows = [], [] + for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: + kind = None if endpoint == "learning_original_exception" else endpoint.split("_")[1] + source, denominator = (learning, 64) if kind is None else (editing, 9) + for world in range(100, 108): + pairs = [] + for seed, condition, chain in itertools.product( + (0, 1), ("company", "project", "neither"), ("company", "project") + ): + for support in [None] if kind is None else (0, 1): + base = (world, seed, condition, chain) + suffix = () if kind is None else (support, kind) + low = source[(*base, "low", *suffix)] + high = source[(*base, "high", *suffix)] + row = { + "endpoint": endpoint, + "world": world, + "seed": seed, + "condition": condition, + "chain": chain, + "support": support, + "kind": kind, + "n": denominator, + "low_correct": low["correct"], + "high_correct": high["correct"], + "correct_difference": high["correct"] - low["correct"], + } + row["accuracy_difference"] = row["correct_difference"] / denominator + pairs.append(row) + case_rows.append(row) + n = len(pairs) * denominator + world_rows.append( + { + "endpoint": endpoint, + "world": world, + "paired_cases": len(pairs), + "nested_query_count_descriptive": n, + "low_accuracy": sum(r["low_correct"] for r in pairs) / n, + "high_accuracy": sum(r["high_correct"] for r in pairs) / n, + "difference": sum(r["correct_difference"] for r in pairs) / n, + } + ) + results = [] + for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: + values = [row["difference"] for row in world_rows if row["endpoint"] == endpoint] + results.append({"endpoint": endpoint, **world_t_statistics(values)}) + adjusted = holm([result["p"] for result in results]) + for result, value in zip(results, adjusted, strict=True): + result.update( + holm_input=1.0 if result["p"] is None else result["p"], + holm_adjusted_p=value, + reject_two_sided_family_05=result["p"] is not None and value <= 0.05, + ) + return { + "contract": DEFAULT_STATISTICS, + "results": results, + "world_effects": world_rows, + "paired_cases": case_rows, + "input_rows": {"learning": len(learning), "editing": len(editing)}, + } diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_context_control.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_context_control.py new file mode 100644 index 0000000000000000000000000000000000000000..26c20f349951ff08ba251e2e61c158ad8f4c0f85 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_context_control.py @@ -0,0 +1,250 @@ +"""Conditional P3 control: block cross-fact document attention during training. + +The frozen document tensors, absolute positions, loss masks, optimizer, QA stream, +and inference path are unchanged. Only document attention edges are removed. +This module is prepared for conditional execution; importing it does not train. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import time +from contextlib import contextmanager +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import bios_cross_train as frozen_trainer +from .bios_cross import CHAINS, CONDITIONS, audit, documents, make_cross_world, qa_schedule +from .bios_data import array_hash, write_json +from .bios_model import Attention, CausalLM +from .bios_organization_train import atomic_numpy_save +from .bios_path_diagnostics import autonomous_two_step + +RECORD_LENGTH = 6 +DOCUMENT_LENGTH = 60 +CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360) + + +def fact_causal_mask(length=DOCUMENT_LENGTH, record_length=RECORD_LENGTH, device=None): + """SDPA Boolean True means an allowed edge: same record and causal order.""" + if length <= 0 or record_length <= 0 or length % record_length: + raise ValueError("Document length must contain complete fact records") + position = torch.arange(length, device=device) + return (position[:, None] // record_length == position[None, :] // record_length) & ( + position[None, :] <= position[:, None] + ) + + +class FactIsolatedAttention(Attention): + """An existing Attention object's parameters are retained without reinitializing.""" + + def forward(self, x): + if not self.document_attention_isolated: + return super().forward(x) + batch, length, width = x.shape + if length != DOCUMENT_LENGTH: + raise ValueError("Document-only attention entered with a non-document tensor") + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=self.fact_mask, + is_causal=False, + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +class FactIsolatedCausalLM(CausalLM): + """Use the original initializer, forward, position IDs, and state-dict schema. + + In the frozen trainer the only 60-token training input is a document; QA + training inputs contain six tokens. Evaluation always uses the original + attention path, including an unusually long inference input. No dropout, + extra trainable parameter, random draw, or reset of position IDs is added. + """ + + def __init__(self, config): + super().__init__(config) + mask = fact_causal_mask() + for block in self.blocks: + attention = block.attention + attention.__class__ = FactIsolatedAttention + attention.document_attention_isolated = False + attention.register_buffer("fact_mask", mask, persistent=False) + + def forward(self, tokens, positions=None): + isolate = self.training and tokens.shape[1] == DOCUMENT_LENGTH + if self.training and tokens.shape[1] not in (RECORD_LENGTH, DOCUMENT_LENGTH): + raise ValueError("Unexpected training input length; document/QA dispatch is unsafe") + if isolate: + if positions is None or positions.shape[1] != 20: + raise ValueError("Document training must preserve all twenty supervised positions") + expected = torch.arange(DOCUMENT_LENGTH, device=tokens.device).view(10, 6)[:, 3:5] + if not torch.equal(positions, expected.reshape(1, 20).expand(len(tokens), -1)): + raise ValueError("Document supervision positions changed") + for block in self.blocks: + block.attention.document_attention_isolated = isolate + try: + return super().forward(tokens, positions) + finally: + for block in self.blocks: + block.attention.document_attention_isolated = False + + +@contextmanager +def isolated_model_factory(): + """Patch only this worker's factory while retaining the frozen trainer body.""" + original = frozen_trainer.CausalLM + if original is not CausalLM: + raise RuntimeError("The frozen trainer already has a modified model factory") + frozen_trainer.CausalLM = FactIsolatedCausalLM + try: + yield + finally: + frozen_trainer.CausalLM = original + + +def context_sources(): + directory = Path(__file__).parent + return { + **frozen_trainer.source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ("bios_context_control.py", "bios_path_diagnostics.py") + }, + } + + +def validate_study(study): + expected = { + "width": 256, + "layers": 8, + "heads": 4, + "steps": 15360, + "checkpoints": list(CHECKPOINTS), + "lr": 0.0001, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "learning_runs": 12, + "edit_cases": 0, + } + for key, value in expected.items(): + if study.get(key) != value: + raise ValueError(f"Context control changed its frozen study setting: {key}") + + +def run(args): + study = json.loads(Path(args.config).read_text()) + validate_study(study) + if args.world not in study["worlds"] or args.seed not in study["seeds"]: + raise ValueError("Context control is restricted to the development matrix") + output = Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + world = make_cross_world(args.world) + world_audit = audit(world) + docs, schedule = documents(world, args.condition), qa_schedule(world, study["steps"]) + contract = { + "protocol": "v2.8-p3-context-control", + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "study": study, + "sources": context_sources(), + "intervention": { + "training_document_attention": "causal within each six-token fact only", + "absolute_positions": "unchanged 0 through 59; never reset within facts", + "document_tokens_batches_and_supervision": "unchanged", + "QA_training_attention": "original causal attention", + "all_inference_attention": "original causal attention", + "mask_sha256": array_hash(fact_causal_mask().numpy()), + }, + "data": { + "truth_sha256": world_audit["truth_sha256"], + "prompts_sha256": world_audit["prompts_sha256"], + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + }, + "environment": { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + } + path = output / "launch-contract.json" + if path.exists(): + old = json.loads(path.read_text()) + for key in contract.keys() - {"environment"}: + if old[key] != contract[key]: + raise ValueError(f"Context control contract changed: {key}") + else: + write_json(path, contract) + if (output / "complete.json").exists(): + return + torch.set_num_threads(args.threads) + device = torch.device(args.device) + controlled_study = { + **study, + "context_contract": contract["sources"], + "context_intervention": contract["intervention"], + } + try: + with isolated_model_factory(): + model, _ = frozen_trainer.learning(args, world, output, controlled_study, device) + # Inference must be the original unrestricted forward path. + model.eval() + with np.load(output / f"predictions-{study['steps']}.npz") as saved: + direct = {key: saved[key] for key in ("prediction", "ended", "correct")} + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) + atomic_numpy_save(output / f"two-step-{name}.npz", **arrays) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": "P3-context-control-learning-only", + "learning_steps": study["steps"], + "edit_cases": 0, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + { + "type": type(error).__name__, + "message": str(error), + "time": time.time(), + }, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True, type=int) + parser.add_argument("--seed", required=True, type=int) + parser.add_argument("--condition", required=True, choices=CONDITIONS) + parser.add_argument("--config", default="configs/bios-context-control-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_context_gradient.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_context_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..89f78f244a71569026fd75d76ac6b10b702fed9d --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_context_gradient.py @@ -0,0 +1,669 @@ +"""Prospectively frozen context-statistic prediction of common-state gradients. + +The predictor contracts supervised target/context co-occurrences with fixed +embeddings and first-layer value weights. It uses neither real gradients nor +contextual activations, and has no fitted scale. It is a new residual-path +approximation, not a theorem for the project's Transformer or AdamW updates. +""" + +import argparse +import hashlib +import itertools +import json +import platform +import time +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path +from types import MethodType + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CONDITIONS, + documents, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_cross_train import tensor_queries +from .bios_data import array_hash, write_json +from .bios_model import CausalLM, ModelConfig + +TARGET = "blocks.0.attention.proj.weight" +CONTRASTS = (("company", "neither"), ("project", "neither"), ("company", "project")) + + +def sha(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def stamp(): + return datetime.now(timezone.utc).isoformat() + + +def allowed_mask(length, isolated, device=None): + pos = torch.arange(length, device=device) + mask = pos[None, :] <= pos[:, None] + if isolated: + mask &= pos[None, :] // 6 == pos[:, None] // 6 + return mask + + +def _isolated_forward(self, x): + batch, length, width = x.shape + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=allowed_mask(length, True, x.device), + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +@contextmanager +def attention_mode(model, isolated): + originals = [] + if isolated: + for block in model.blocks: + attention = block.attention + originals.append((attention, attention.forward)) + attention.forward = MethodType(_isolated_forward, attention) + try: + yield + finally: + for attention, forward in originals: + attention.forward = forward + + +def ln_vjp(x, upstream, layer): + """Exact input VJP of LayerNorm, without reading a real model gradient.""" + centered = x - x.mean(-1, keepdim=True) + inverse = torch.rsqrt(centered.square().mean(-1, keepdim=True) + layer.eps) + normalized = centered * inverse + affine = upstream * layer.weight + return inverse * ( + affine + - affine.mean(-1, keepdim=True) + - normalized * (affine * normalized).mean(-1, keepdim=True) + ) + + +@torch.no_grad() +def statistic_predictors(model, tokens, positions, labels, shuffled, isolated): + """Gradients of a zero-residual baseline plus one infinitesimal OV branch. + + x_j = E[token_j] + P[j] (or E[token_j] for the token-only control). + m_t = average_{j allowed at t} (Wv LN1(x_j) + bv). + epsilon_t = J_LNfinal(x_t)^T E^T (softmax(E LNfinal(x_t)) - onehot(y_t)). + Ghat = mean_t epsilon_t m_t^T. This is a contraction of position/mask + weighted token-target counts; all other residual branches are omitted. + The answer and EOS means returned here are separately normalized. + """ + width = model.config.width + result = {} + for position_aware in (True, False): + x = model.token(tokens) + if position_aware: + x = x + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + value = F.linear( + model.blocks[0].ln1(x), + model.blocks[0].attention.qkv.weight[2 * width :], + model.blocks[0].attention.qkv.bias[2 * width :], + ) + mask = allowed_mask(tokens.shape[1], isolated, tokens.device).to(x.dtype) + mask /= mask.sum(-1, keepdim=True) + mean_value = (mask @ value)[:, positions] + query = x[:, positions] + probability = F.linear(model.ln_final(query), model.token.weight).softmax(-1) + expected = probability @ model.token.weight + variants = ( + (("position", labels), ("shuffled", shuffled)) + if position_aware + else (("token", labels),) + ) + for name, targets in variants: + epsilon = ln_vjp(query, expected - model.token(targets), model.ln_final) + for offset, kind in enumerate(("answer", "eos")): + left, right = epsilon[:, offset::2], mean_value[:, offset::2] + result[f"{name}/{kind}"] = torch.einsum("btd,bte->de", left, right) / ( + left.shape[0] * left.shape[1] + ) + return result + + +def vector_metrics(actual, predicted): + actual = np.asarray(actual, dtype=np.float64).ravel() + predicted = np.asarray(predicted, dtype=np.float64).ravel() + an, pn = np.linalg.norm(actual), np.linalg.norm(predicted) + return { + "actual_norm": float(an), + "predicted_norm": float(pn), + "cosine": float(np.dot(actual, predicted) / (an * pn)) if an and pn else None, + "relative_error": float(np.linalg.norm(actual - predicted) / an) if an else None, + "norm_ratio": float(pn / an) if an else None, + } + + +def module_name(name): + if name.startswith("blocks."): + parts = name.split(".") + if parts[2] == "attention" and parts[3] == "qkv": + return ".".join(parts[:4]) + return ".".join(parts[:3]) + return name.split(".")[0] + + +def module_differences(first, second): + sums = {} + for name in first: + # The concatenated qkv parameter is additionally split by role. + pieces = [(module_name(name), first[name], second[name])] + if ".attention.qkv." in name: + pieces = [ + (name.split(".qkv.")[0] + "." + role, a, b) + for role, a, b in zip( + ("query", "key", "value"), + np.split(first[name], 3), + np.split(second[name], 3), + strict=True, + ) + ] + for group, left, right in pieces: + values = sums.setdefault(group, np.zeros(3, dtype=np.float64)) + left, right = left.astype(np.float64), right.astype(np.float64) + values += (np.sum((left - right) ** 2), np.sum(left**2), np.sum(right**2)) + return { + group: { + "difference_norm": float(np.sqrt(value[0])), + "relative_to_mean_arm_norm": float( + np.sqrt(value[0]) / ((np.sqrt(value[1]) + np.sqrt(value[2])) / 2) + ) + if value[1] + value[2] + else None, + } + for group, value in sums.items() + } + + +def source_files(root, config): + names = [ + "bios_context_gradient.py", + "bios_cross.py", + "bios_cross_train.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_organization.py", + ] + paths = [root / "src/llm_memory_editability" / name for name in names] + paths += [ + root / "scripts/run_bios_context_gradient.py", + root / "tests/test_bios_context_gradient.py", + ] + paths += [root / "configs/bios-context-gradient-v1.json"] + for world in config["worlds"]: + paths += [ + root / config["source_world_root"] / f"world-{world}" / name + for name in ("world.npz", "metadata.json", "audit.json") + ] + return paths + + +def freeze(root, config): + out = root / config["artifacts"] + lockpath = out / "preregistration-lock.json" + if lockpath.exists(): + raise FileExistsError("An existing prospective lock must not be replaced") + protocol = (root / "docs/experimental-protocol.md").read_text().split("## 16. ", 1)[1] + out.mkdir(parents=True, exist_ok=True) + (out / "preregistration.md").write_text("## 16. " + protocol) + sources = {} + for path in source_files(root, config): + relative = path.relative_to(root) + sources[str(relative)] = sha(path) + # Data stay in their original location, hash-bound by the lock. + if relative.parts[0] != "data": + copy = out / "frozen-files" / relative + copy.parent.mkdir(parents=True, exist_ok=True) + copy.write_bytes(path.read_bytes()) + write_json( + lockpath, + { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(out / "preregistration.md"), + "torch": torch.__version__, + "numpy": np.__version__, + "python": platform.python_version(), + }, + ) + return {"lock": str(lockpath), "sha256": sha(lockpath)} + + +def verify_lock(root, config): + lockpath = root / config["artifacts"] / "preregistration-lock.json" + lock = json.loads(lockpath.read_text()) + if lock["config"] != config: + raise ValueError("Configuration differs from prospective lock") + for path, expected in lock["sources"].items(): + if sha(root / path) != expected: + raise ValueError("Frozen source changed: " + path) + if sha(root / config["artifacts"] / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Prospective protocol changed") + return sha(lockpath) + + +def context_audit(world, config): + """Exact exposure/bigram audit plus a centered city-by-person Phi subblock.""" + people = [i for i, label in enumerate(world.token_labels) if label.startswith("person:")] + cities = np.unique(world.city_tokens) + pi, ci = np.full(world.vocab_size, -1), np.full(world.vocab_size, -1) + pi[people], ci[cities] = np.arange(len(people)), np.arange(len(cities)) + histograms, contexts, receipts = {}, {}, {} + for condition in CONDITIONS: + docs = documents(world, condition) + receipts[condition] = {"documents_sha256": array_hash(docs)} + counts = np.bincount(docs.ravel(), minlength=world.n_base) + receipts[condition]["exposure_sha256"] = array_hash(counts) + for isolated in (False, True): + joint = np.zeros((len(cities), len(people))) + marginal = np.zeros(len(people)) + bigrams = np.zeros((2, world.vocab_size), dtype=np.int64) + for epoch in range(config["rotations"]): + batch = render(world, epoch_documents(docs, world.seed, epoch)) + for col, pos in enumerate(batch["positions"][0]): + targets = batch["labels"][:, col] + # All answer predictors use ANS; EOS predictors use answer tokens. + values = targets if col % 2 == 0 else batch["tokens"][:, pos] + bigrams[col % 2] += np.bincount(values, minlength=world.vocab_size) + left = int(pos) // 6 * 6 if isolated else 0 + weight = 1 / (int(pos) - left + 1) + rows = ci[targets] + for prefix in range(left, int(pos) + 1): + columns = pi[batch["tokens"][:, prefix]] + valid = columns >= 0 + np.add.at(marginal, columns[valid], weight) + valid &= rows >= 0 + np.add.at(joint, (rows[valid], columns[valid]), weight) + contexts[condition, isolated] = (joint - marginal[None] / world.vocab_size) / ( + config["rotations"] * len(docs) * 20 + ) + histograms[condition] = bigrams + result = {"receipts": receipts, "comparisons": []} + for a, b in CONTRASTS: + equal = np.array_equal(histograms[a], histograms[b]) + if not equal or receipts[a]["exposure_sha256"] != receipts[b]["exposure_sha256"]: + raise ValueError("Organization exposure or supervised bigrams differ") + for isolated in (False, True): + first, second = contexts[a, isolated], contexts[b, isolated] + difference = np.max(np.abs(first - second)) + if isolated and difference > 1e-14: + raise ValueError("Isolated context statistics differ") + result["comparisons"].append( + { + "first": a, + "second": b, + "isolated": isolated, + "supervised_bigram_equal": equal, + "context_max_abs_difference": float(difference), + "context_relative_difference": float( + np.linalg.norm(first - second) / np.linalg.norm(second) + ), + } + ) + result["bigram_sha256"] = array_hash(histograms["neither"]) + result["qa_ids_sha256"] = array_hash(world.train_ids) + return result + + +def numpy_gradients(accumulators): + return {name: value.cpu().numpy().astype(np.float32) for name, value in accumulators.items()} + + +def measure_arm(model, world, condition, isolated, config, device, out): + docs = documents(world, condition) + named = dict(model.named_parameters()) + params = tuple(named.values()) + accumulators = { + kind: {name: torch.zeros_like(value, dtype=torch.float64) for name, value in named.items()} + for kind in ("answer", "eos") + } + predictions = { + f"{predictor}/{kind}": torch.zeros( + (model.config.width, model.config.width), dtype=torch.float64, device=device + ) + for predictor in config["predictors"] + for kind in ("answer", "eos") + } + losses = {"answer": 0.0, "eos": 0.0} + total_documents = len(docs) * config["rotations"] + started = time.perf_counter() + model.eval() + with attention_mode(model, isolated): + for epoch in range(config["rotations"]): + batch = render(world, epoch_documents(docs, world.seed, epoch)) + shuffled = batch["labels"].copy() + rng = np.random.default_rng( + np.random.SeedSequence([config["shuffle_seed"], world.seed, epoch]) + ) + # Each column is one relation at one absolute position. Marginals + # are exactly preserved, with the same permutations in every arm. + for col in range(shuffled.shape[1]): + shuffled[:, col] = shuffled[rng.permutation(len(docs)), col] + for begin in range(0, len(docs), config["measurement_batch"]): + end = min(begin + config["measurement_batch"], len(docs)) + tokens = torch.as_tensor(batch["tokens"][begin:end], device=device) + labels = torch.as_tensor(batch["labels"][begin:end], device=device) + positions = torch.as_tensor(batch["positions"][0], device=device) + shuffled_batch = torch.as_tensor(shuffled[begin:end], device=device) + weight = config["document_weight"] * 0.5 * (end - begin) / total_documents + predictors = statistic_predictors( + model, tokens, positions, labels, shuffled_batch, isolated + ) + for name, prediction in predictors.items(): + predictions[name].add_(prediction.double(), alpha=weight) + logits = model(tokens, positions[None].expand(len(tokens), -1)) + for offset, kind in enumerate(("answer", "eos")): + loss = F.cross_entropy( + logits[:, offset::2].flatten(0, 1), labels[:, offset::2].flatten() + ) + gradients = torch.autograd.grad(loss, params, retain_graph=offset == 0) + for name, gradient in zip(named, gradients, strict=True): + accumulators[kind][name].add_(gradient.double(), alpha=weight) + losses[kind] += float(loss.detach()) * (end - begin) / total_documents + print( + json.dumps({"event": "rotation", "arm": out.name, "rotation": epoch + 1}), + flush=True, + ) + result = {kind: numpy_gradients(accumulators[kind]) for kind in accumulators} + result["predictions"] = numpy_gradients(predictions) + out.mkdir(parents=True, exist_ok=False) + np.savez(out / "answer.npz", **result["answer"]) + np.savez(out / "eos.npz", **result["eos"]) + np.savez(out / "predictions.npz", **result["predictions"]) + metadata = { + "condition": condition, + "isolated": isolated, + "documents": total_documents, + "supervised_tokens": total_documents * 20, + "losses": losses, + "seconds": time.perf_counter() - started, + "files": {name: sha(out / name) for name in ("answer.npz", "eos.npz", "predictions.npz")}, + } + if any(not np.isfinite(value).all() for part in result.values() for value in part.values()): + raise FloatingPointError("Nonfinite gradients or predictions") + write_json(out / "receipt.json", metadata) + return result + + +def arm_data(path): + return { + kind: dict(np.load(path / f"{filename}.npz")) + for kind, filename in (("answer", "answer"), ("eos", "eos"), ("predictions", "predictions")) + } + + +def common_training_step(model, optimizer, world, config, step, device, schedule, data): + epoch, offset = divmod(step, 128) + arranged = epoch_documents(documents(world, "neither"), world.seed, epoch) + batch = render(world, arranged[offset * 16 : (offset + 1) * 16]) + tokens = torch.as_tensor(batch["tokens"], device=device) + positions = torch.as_tensor(batch["positions"], device=device) + labels = torch.as_tensor(batch["labels"], device=device) + qa = torch.as_tensor(schedule[step], device=device) + model.train() + optimizer.zero_grad(set_to_none=True) + for group in optimizer.param_groups: + group["lr"] = config["lr"] * min((epoch + 1) / config["warmup_epochs"], 1) + loss = F.cross_entropy(model(tokens, positions).flatten(0, 1), labels.flatten()) + (config["document_weight"] * loss).backward() + qa_loss = F.cross_entropy( + model(data["tokens"][qa], data["positions"][qa]).flatten(0, 1), data["labels"][qa].flatten() + ) + (config["qa_weight"] * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config["clip_norm"]) + if not torch.isfinite(loss + qa_loss + norm): + raise FloatingPointError("Nonfinite common training step") + optimizer.step() + return { + "step": step + 1, + "document_loss": float(loss.detach()), + "qa_loss": float(qa_loss.detach()), + } + + +def run(root, config, world_seed, seed, device): + lock_hash = verify_lock(root, config) + if world_seed not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("World/initialization is outside the frozen matrix") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.manual_seed(seed) + world = make_cross_world(world_seed, root / config["source_world_root"]) + out = root / config["output"] / f"world-{world_seed}-seed-{seed}" + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + raise FileExistsError("Completed run cannot be overwritten") + audit_path = out / "data-audit.json" + if not audit_path.exists(): + write_json(audit_path, context_audit(world, config)) + model = CausalLM( + ModelConfig( + world.vocab_size, config["width"], config["layers"], config["heads"], config["context"] + ) + ).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), + lr=config["lr"], + weight_decay=config["weight_decay"], + fused=device.type == "cuda", + ) + schedule = qa_schedule(world, max(config["states"])) + data = tensor_queries(world, device) + trajectory = [] + write_json( + out / "identity.json", + { + "world": world_seed, + "seed": seed, + "lock_sha256": lock_hash, + "created_at": stamp(), + "model": model.config_dict(), + "parameters": sum(p.numel() for p in model.parameters()), + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "torch": torch.__version__, + "numpy": np.__version__, + "qa_schedule_sha256": array_hash(schedule), + }, + ) + for step in range(max(config["states"]) + 1): + if step in config["states"]: + state_path = out / f"state-{step}.pt" + if state_path.exists(): + # Resumption reconstructs the exact common trajectory and verifies + # weights before using any existing diagnostic artifacts. + saved = torch.load(state_path, map_location=device, weights_only=False) + if any( + not torch.equal(v, saved["model"][k]) for k, v in model.state_dict().items() + ): + raise ValueError("Reconstructed reference weights differ") + else: + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "config": model.config_dict(), + }, + state_path, + ) + for mask in config["masks"]: + for condition in config["conditions"]: + path = out / f"step-{step}-{mask}-{condition}" + if (path / "receipt.json").exists(): + receipt = json.loads((path / "receipt.json").read_text()) + if any( + sha(path / name) != digest for name, digest in receipt["files"].items() + ): + raise ValueError("Existing gradient artifact hash mismatch") + continue + if path.exists(): + raise FileExistsError("Incomplete output must be retained and audited") + print( + json.dumps( + { + "event": "arm_start", + "world": world_seed, + "seed": seed, + "step": step, + "mask": mask, + "condition": condition, + } + ), + flush=True, + ) + measure_arm(model, world, condition, mask == "isolated", config, device, path) + write_json(out / "trajectory.json", trajectory) + if step < max(config["states"]): + trajectory.append( + common_training_step(model, optimizer, world, config, step, device, schedule, data) + ) + verify_lock(root, config) + files = {str(path.relative_to(out)): sha(path) for path in out.rglob("*") if path.is_file()} + write_json( + out / "complete.json", {"completed_at": stamp(), "lock_sha256": lock_hash, "files": files} + ) + + +def summarize(root, config): + verify_lock(root, config) + rows, modules, checks = [], [], [] + for world_seed, seed in itertools.product(config["worlds"], config["seeds"]): + runpath = root / config["output"] / f"world-{world_seed}-seed-{seed}" + completion = json.loads((runpath / "complete.json").read_text()) + for name, digest in completion["files"].items(): + if sha(runpath / name) != digest: + raise ValueError("Completed run artifact changed: " + name) + for step, mask in itertools.product(config["states"], config["masks"]): + arms = {c: arm_data(runpath / f"step-{step}-{mask}-{c}") for c in CONDITIONS} + for a, b in CONTRASTS: + identity = { + "world": world_seed, + "seed": seed, + "step": step, + "mask": mask, + "first": a, + "second": b, + } + for kind in ("answer", "eos", "combined"): + kinds = ("answer", "eos") if kind == "combined" else (kind,) + ga = {n: sum(arms[a][k][n] for k in kinds) for n in arms[a]["answer"]} + gb = {n: sum(arms[b][k][n] for k in kinds) for n in arms[b]["answer"]} + modules.append( + {**identity, "kind": kind, "modules": module_differences(ga, gb)} + ) + for predictor in config["predictors"]: + pred = sum( + arms[a]["predictions"][f"{predictor}/{k}"] + - arms[b]["predictions"][f"{predictor}/{k}"] + for k in kinds + ) + row = { + **identity, + "kind": kind, + "predictor": predictor, + **vector_metrics(ga[TARGET] - gb[TARGET], pred), + } + # Near-zero isolated contrasts are cancellation controls; + # cosine between rounding residues has no scientific meaning. + if mask == "isolated": + row["cosine"] = None + rows.append(row) + norm = np.linalg.norm(ga[TARGET] - gb[TARGET]) + reference = (np.linalg.norm(ga[TARGET]) + np.linalg.norm(gb[TARGET])) / 2 + if mask == "isolated": + checks.append( + { + **identity, + "kind": kind, + "relative_cancellation_residue": float(norm / reference), + } + ) + if any(c["relative_cancellation_residue"] > 1e-4 for c in checks): + raise ValueError("Isolated common-state gradient cancellation failed") + out = root / config["artifacts"] + write_json(out / "metrics.json", rows) + write_json(out / "module-metrics.json", modules) + write_json( + out / "audit.json", + {"passed": True, "runs": 4, "arms": 72, "isolated_checks": checks, "completed_at": stamp()}, + ) + primary = [ + r + for r in rows + if r["step"] == 0 + and r["mask"] == "open" + and r["kind"] == "answer" + and r["second"] == "neither" + ] + lines = [ + "# Context statistics and common-state gradients", + "", + "Descriptive development experiment; no fitted scale or significance tests.", + "", + "| World | Seed | Contrast | Predictor | Cosine | Relative error | Norm ratio |", + "| --- | --- | --- | --- | ---: | ---: | ---: |", + ] + for row in primary: + lines.append( + f"| {row['world']} | {row['seed']} | {row['first']}−{row['second']} | " + f"{row['predictor']} | {row['cosine']:.6f} | {row['relative_error']:.6f} | " + f"{row['norm_ratio']:.6f} |" + ) + (out / "report.md").write_text("\n".join(lines) + "\n") + print( + json.dumps( + { + "report": str(out / "report.md"), + "rows": len(rows), + "max_isolated_residue": max(c["relative_cancellation_residue"] for c in checks), + } + ) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=("freeze", "run", "summarize")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument( + "--config", type=Path, default=Path("configs/bios-context-gradient-v1.json") + ) + args = parser.parse_args() + root = Path(__file__).resolve().parents[2] + config = json.loads((root / args.config).read_text()) + if args.mode == "freeze": + print(json.dumps(freeze(root, config))) + elif args.mode == "run": + run(root, config, args.world, args.seed, torch.device(args.device)) + else: + summarize(root, config) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_cross.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..960ef7e03dd29b834df68149d8aca7cbcd077a10 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_cross.py @@ -0,0 +1,330 @@ +"""Two-chain organization crossover: shared facts, symmetric relational tasks. + +This is a new development world, not an alteration of the archived A/B/C runs. +Company and project each have 64 groups of 32 people and two old exceptions. +""" + +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +from .bios_data import ANS, BOS, EOS, N_BASE, N_PEOPLE, array_hash, load_world, rng_for, write_json + +CONDITIONS = ("company", "project", "neither") +CHAINS = ("company", "project") +SLOTS = 10 + + +@dataclass +class CrossWorld: + seed: int + prompts: np.ndarray + lengths: np.ndarray + answers: np.ndarray + relation: np.ndarray + person: np.ndarray + memberships: np.ndarray + defaults: np.ndarray + exceptions: np.ndarray + membership_ids: np.ndarray + root_ids: np.ndarray + actual_ids: np.ndarray + derived_ids: np.ndarray + train_ids: np.ndarray + heldout_ids: np.ndarray + city_tokens: np.ndarray + token_labels: list + n_base: int + + @property + def vocab_size(self): + return len(self.token_labels) + + +def make_cross_world(seed, source_root="data/bios-organization-v1"): + old = load_world(Path(source_root) / f"world-{seed}") + labels = ( + old.token_labels + + [f"project:{i}" for i in range(64)] + + ["relation:project", "relation:project_default", "relation:project_actual"] + ) + token = {name: i for i, name in enumerate(labels)} + rng = rng_for(seed, 901) + memberships = np.stack([old.employers, rng.permutation(np.repeat(np.arange(64), 32))]) + defaults = np.stack([old.defaults, rng.permutation(old.defaults)]) + exceptions = np.stack([old.exceptions, np.zeros(N_PEOPLE, dtype=bool)]) + actual = defaults[1, memberships[1]].copy() + for group in range(64): + people = rng.choice(np.flatnonzero(memberships[1] == group), 2, replace=False) + exceptions[1, people] = True + choices = np.unique(defaults[1][defaults[1] != defaults[1, group]]) + actual[people] = rng.choice(choices, 2) + n_base = N_BASE + 2 * N_PEOPLE + 64 + size = n_base + 2 * N_PEOPLE + prompts = np.zeros((size, 5), dtype=np.int64) + answers = np.zeros(size, dtype=np.int64) + lengths = np.full(size, 4, dtype=np.int64) + relation = np.zeros(size, dtype=np.int64) + person = np.full(size, -1, dtype=np.int64) + prompts[:N_BASE], answers[:N_BASE] = old.prompts[:N_BASE], old.answers[:N_BASE] + relation[:N_BASE], person[:N_BASE] = old.relation[:N_BASE], old.person[:N_BASE] + membership_ids = np.stack([np.arange(N_PEOPLE), N_BASE + np.arange(N_PEOPLE)]) + root_ids = np.stack([N_PEOPLE + np.arange(64), N_BASE + N_PEOPLE + np.arange(64)]) + actual_ids = np.stack( + [N_PEOPLE + 64 + np.arange(N_PEOPLE), N_BASE + N_PEOPLE + 64 + np.arange(N_PEOPLE)] + ) + person_tokens = np.array([token[f"person:{i}"] for i in range(N_PEOPLE)]) + new_values = [ + np.array([token[f"project:{i}"] for i in memberships[1]]), + old.city_tokens[defaults[1]], + old.city_tokens[actual], + ] + for rel, ids, values in zip( + (7, 8, 9), (membership_ids[1], root_ids[1], actual_ids[1]), new_values, strict=True + ): + subjects = ( + np.array([token[f"project:{i}"] for i in range(64)]) if rel == 8 else person_tokens + ) + rtoken = token[ + ("relation:project", "relation:project_default", "relation:project_actual")[rel - 7] + ] + prompts[ids, :4] = np.column_stack( + [np.full(len(ids), BOS), subjects, np.full(len(ids), rtoken), np.full(len(ids), ANS)] + ) + answers[ids], relation[ids] = values, rel + if rel != 8: + person[ids] = np.arange(N_PEOPLE) + derived_ids = n_base + np.arange(2 * N_PEOPLE).reshape(2, N_PEOPLE) + trained, heldout = [], [] + for chain in range(2): + ids = derived_ids[chain] + prompts[ids] = np.column_stack( + [ + np.full(N_PEOPLE, BOS), + person_tokens, + np.full(N_PEOPLE, token["relation:employer" if chain == 0 else "relation:project"]), + np.full( + N_PEOPLE, + token["relation:default_city" if chain == 0 else "relation:project_default"], + ), + np.full(N_PEOPLE, ANS), + ] + ) + answers[ids] = old.city_tokens[defaults[chain, memberships[chain]]] + lengths[ids], relation[ids], person[ids] = 5, 10 + chain, np.arange(N_PEOPLE) + split_rng = rng_for(seed, 902, chain) + included = [] + for group in range(64): + for exception in (False, True): + candidates = np.flatnonzero( + (memberships[chain] == group) & (exceptions[chain] == exception) + ) + included.extend(split_rng.permutation(candidates)[: len(candidates) // 2]) + trained.append(np.sort(ids[included])) + heldout.append(np.setdiff1d(ids, trained[-1])) + # Randomize the complete vocabulary, so appended token numbers carry no task order. + permutation = np.arange(len(labels)) + permutation[4:] = rng_for(seed, 903).permutation(permutation[4:]) + new_labels = [""] * len(labels) + for index, label in enumerate(labels): + new_labels[permutation[index]] = label + return CrossWorld( + seed, + permutation[prompts], + lengths, + permutation[answers], + relation, + person, + memberships, + defaults, + exceptions, + membership_ids, + root_ids, + actual_ids, + derived_ids, + np.stack(trained), + np.stack(heldout), + permutation[old.city_tokens], + new_labels, + n_base, + ) + + +def documents(world, condition): + if condition not in CONDITIONS: + raise ValueError("Unknown crossover condition") + docs = np.empty((N_PEOPLE, SLOTS), dtype=np.int64) + for rel in range(SLOTS): + if rel in (1, 8): + continue + ids = np.flatnonzero(world.relation[: world.n_base] == rel) + docs[world.person[ids], rel] = ids + for chain, slot in enumerate((1, 8)): + membership = world.memberships[chain] + group = membership.copy() + if condition != CHAINS[chain]: + rng = rng_for(world.seed, 904, chain) + members = np.stack( + [rng.permutation(np.flatnonzero(membership == g)) for g in range(64)] + ) + for lane in range(32): + cycle = rng.permutation(64) + group[members[cycle, lane]] = np.roll(cycle, -1) + docs[:, slot] = world.root_ids[chain, group] + return docs + + +def epoch_documents(docs, seed, epoch): + rows = rng_for(seed, 905, epoch).permutation(N_PEOPLE) + return np.roll(docs[rows], epoch % SLOTS, axis=1) + + +def render(world, ids): + tokens = np.empty((*ids.shape, 6), dtype=np.int64) + tokens[:, :, :4] = world.prompts[ids, :4] + tokens[:, :, 4], tokens[:, :, 5] = world.answers[ids], EOS + positions = (np.arange(SLOTS)[:, None] * 6 + np.array([3, 4])).ravel() + labels = np.stack([world.answers[ids], np.full_like(ids, EOS)], axis=-1) + return { + "tokens": tokens.reshape(len(ids), SLOTS * 6), + "positions": np.broadcast_to(positions, (len(ids), SLOTS * 2)).copy(), + "labels": labels.reshape(len(ids), SLOTS * 2), + } + + +def qa_schedule(world, steps): + streams = [] + for chain in range(2): + rng = rng_for(world.seed, 906, chain) + pool = world.train_ids[chain] + streams.append( + np.concatenate( + [rng.permutation(pool) for _ in range((steps * 20 + len(pool) - 1) // len(pool))] + )[: steps * 20].reshape(steps, 20) + ) + return np.concatenate(streams, axis=1) + + +def audit(world): + expected = np.ones(world.n_base, dtype=np.int64) + expected[world.root_ids.ravel()] = 32 + report = {} + for condition in CONDITIONS: + docs = documents(world, condition) + if not np.array_equal(np.bincount(docs.ravel(), minlength=world.n_base), expected): + raise ValueError("Unequal fact exposure") + personal = world.person[docs[:, [0, 2, 3, 4, 5, 6, 7, 9]]] + if not np.all(personal == np.arange(N_PEOPLE)[:, None]): + raise ValueError("Person grouping changed") + for chain, slot in enumerate((1, 8)): + linked = docs[:, slot] == world.root_ids[chain, world.memberships[chain]] + if not np.all(linked == (condition == CHAINS[chain])): + raise ValueError("Incorrect linked/unlinked manipulation") + slots = np.zeros((world.n_base, SLOTS), dtype=np.int64) + for epoch in range(SLOTS): + arranged = epoch_documents(docs, world.seed, epoch) + np.add.at(slots, (arranged, np.arange(SLOTS)[None, :]), 1) + if not np.array_equal(slots, np.repeat(expected[:, None], SLOTS, axis=1)): + raise ValueError("Unequal position exposure") + report[condition] = { + "documents_sha256": array_hash(docs), + "exposure_sha256": array_hash(expected), + } + for chain in range(2): + if not np.array_equal(np.bincount(world.memberships[chain]), np.full(64, 32)): + raise ValueError("Unequal group sizes") + for group in range(64): + members = world.memberships[chain] == group + if world.exceptions[chain, members].sum() != 2: + raise ValueError("Unequal exceptions") + if len(np.intersect1d(world.train_ids[chain], world.heldout_ids[chain])): + raise ValueError("QA leakage") + truth = world.city_tokens[world.defaults[chain, world.memberships[chain]]] + np.testing.assert_array_equal(world.answers[world.derived_ids[chain]], truth) + np.testing.assert_array_equal(np.sort(world.defaults[0]), np.sort(world.defaults[1])) + return { + "passed": True, + "world": world.seed, + "conditions": report, + "base_facts": world.n_base, + "queries": len(world.answers), + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "QA_train_per_chain": 1024, + "QA_heldout_per_chain": 1024, + } + + +def save_world(world, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + directory / "world.npz", + **{key: value for key, value in vars(world).items() if isinstance(value, np.ndarray)}, + ) + write_json( + directory / "metadata.json", + {"seed": world.seed, "n_base": world.n_base, "token_labels": world.token_labels}, + ) + write_json(directory / "audit.json", audit(world)) + + +def edit_pair(world, chain, support=0): + rng = rng_for(world.seed, 907, chain * 100 + support) + while True: + groups = rng.choice(64, 3, replace=False) + if len(set(world.defaults[chain, groups])) == 3: + break + coherent, exception = world.answers.copy(), world.answers.copy() + conflict_people = [] + for j, group in enumerate(groups): + new, alt = world.city_tokens[world.defaults[chain, groups[[(j + 1) % 3, (j + 2) % 3]]]] + root = world.root_ids[chain, group] + coherent[root] = exception[root] = new + members = rng.permutation( + np.flatnonzero((world.memberships[chain] == group) & ~world.exceptions[chain]) + ) + ids = world.actual_ids[chain, members] + coherent[ids] = new + exception[ids[:15]], exception[ids[15:]] = new, alt + conflict_people.extend(members[15:]) + derived = world.derived_ids[chain, world.memberships[chain] == group] + coherent[derived] = exception[derived] = new + changed = coherent != world.answers + np.testing.assert_array_equal(changed, exception != world.answers) + e, d = np.flatnonzero(changed[: world.n_base]), np.flatnonzero(changed & (world.relation >= 10)) + assert len(e) == 93 and len(d) == 96 + np.testing.assert_array_equal(np.sort(coherent[e]), np.sort(exception[e])) + # Disjoint retention strata: old exceptions, other facts of affected people, + # remaining task-chain facts, and remaining independent/cross-chain facts. + selected_people = np.isin(world.memberships[chain], groups) + selected_facts = (world.person >= 0) & selected_people[np.maximum(world.person, 0)] + old_exceptions = np.zeros(len(world.answers), dtype=bool) + old_exceptions[world.actual_ids[chain, selected_people & world.exceptions[chain]]] = True + relevant = np.isin(world.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(world.answers), -1, dtype=np.int64) + strata[~changed & old_exceptions] = 0 + strata[~changed & selected_facts & ~old_exceptions] = 1 + strata[~changed & ~selected_facts & relevant] = 2 + strata[~changed & ~selected_facts & ~relevant] = 3 + assert np.array_equal(strata >= 0, ~changed) + heldout, replay_pool = [], [] + for g in range(4): + ids = rng.permutation(np.flatnonzero((strata == g) & (world.relation < 10))) + n = max(1, int(np.ceil(0.2 * len(ids)))) + heldout.extend(ids[:n]) + replay_pool.extend(ids[n:]) + heldout.extend(np.flatnonzero((strata >= 0) & (world.relation >= 10))) + replay = rng.choice(replay_pool, min(4096, len(replay_pool)), replace=False) + return { + "coherent": coherent, + "exception": exception, + "E": e, + "D": d, + "conflict_D": world.derived_ids[chain, conflict_people], + "strata": strata, + "heldout": np.array(sorted(heldout)), + "replay": replay, + "groups": groups, + } diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_cross_continue.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_cross_continue.py new file mode 100644 index 0000000000000000000000000000000000000000..df0a21278c640164306e05b7465e24cc0e6d0df8 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_cross_continue.py @@ -0,0 +1,627 @@ +"""Protocol v2.8 P2: audited continuation of frozen crossover checkpoints.""" + +import argparse +import copy +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CHAINS, + audit, + documents, + edit_pair, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_cross_train import edit_metrics as original_edit_metrics +from .bios_cross_train import evaluate, learning_metrics, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +PARENT_STEP = 15360 +FINAL_STEP = 30720 +CHECKPOINTS = (15360, 20480, 25600, 30720) +EDIT_CHECKPOINTS = (0, 32, 128, 512) + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def continuation_sources(): + return {**source_hashes(), Path(__file__).name: file_hash(__file__)} + + +def tree_hash(value): + """Stable audit hash for nested optimizer/RNG states, without pickle metadata.""" + digest = hashlib.sha256() + + def visit(item): + if isinstance(item, torch.Tensor): + item = item.detach().cpu().contiguous() + digest.update(f"tensor:{item.dtype}:{tuple(item.shape)}:".encode()) + digest.update(item.reshape(-1).view(torch.uint8).numpy().tobytes()) + elif isinstance(item, np.ndarray): + digest.update(f"numpy:{item.dtype}:{item.shape}:".encode()) + digest.update(np.ascontiguousarray(item).tobytes()) + elif isinstance(item, dict): + digest.update(b"dict[") + for key in sorted(item, key=lambda key: (type(key).__name__, str(key))): + visit(key) + visit(item[key]) + digest.update(b"]") + elif isinstance(item, (list, tuple)): + digest.update(type(item).__name__.encode() + b"[") + for child in item: + visit(child) + digest.update(b"]") + else: + digest.update(f"{type(item).__name__}:{item!r};".encode()) + + visit(value) + return digest.hexdigest() + + +def continuation_lr(base_lr, absolute_step): + """Use the original absolute epoch; never restart warmup at a branch point.""" + return base_lr * min((absolute_step // 128 + 1) / 16, 1) + + +def validate_optimizer(optimizer_state, step, learning_rate): + states = optimizer_state["state"] + groups = optimizer_state["param_groups"] + if not states or sum(len(group["params"]) for group in groups) != len(states): + raise ValueError("Missing parent optimizer moments") + for state in states.values(): + if not {"step", "exp_avg", "exp_avg_sq"} <= state.keys(): + raise ValueError("Incomplete AdamW state") + if int(state["step"]) != step: + raise ValueError("Optimizer update count differs from checkpoint step") + for group in groups: + if group["lr"] != learning_rate or group["weight_decay"] != 0.1: + raise ValueError("Parent optimizer learning rate or decay changed") + + +def expected_exposure(world, docs, schedule, step, base_lr): + """Reconstruct original full-epoch exposure, positions, and LR-weighted exposure.""" + epochs, remainder = divmod(step, 128) + if remainder: + raise ValueError("Parent must end on a complete document epoch") + occurrence = np.bincount(docs.ravel(), minlength=world.n_base) + counts = np.bincount(schedule[:step].ravel(), minlength=len(world.answers)) + counts[: world.n_base] += epochs * occurrence + slots = np.repeat((occurrence * (epochs // 10))[:, None], 10, axis=1) + for epoch in range(epochs % 10): + arranged = np.roll(docs, epoch, axis=1) + np.add.at(slots, (arranged, np.arange(10)[None, :]), 1) + weighted = np.zeros(len(world.answers), dtype=np.float64) + weighted[: world.n_base] = occurrence * sum( + continuation_lr(base_lr, epoch * 128) for epoch in range(epochs) + ) + rates = np.repeat([continuation_lr(base_lr, i) for i in range(step)], 40) + np.add.at(weighted, schedule[:step].ravel(), rates) + return counts, slots, weighted + + +def validate_parent(parent, world, new_lr): + """Verify immutable parent provenance and the longer stream before any updates.""" + parent = Path(parent).resolve() + config = json.loads((parent / "config.json").read_text()) + study = config["study"] + if study["width"] not in (128, 256) or config["world"] not in (0, 1): + raise ValueError("P2 includes only the two declared sizes and development worlds") + if config["seed"] not in (0, 1) or config["condition"] not in ("company", "project", "neither"): + raise ValueError("Unexpected P2 initialization or organization") + if new_lr not in (0.0001, 0.0003) or (new_lr == 0.0003 and config["seed"] != 0): + raise ValueError("The sensitivity branch contains only initialization zero") + if study["steps"] != PARENT_STEP or study["lr"] != 0.0001: + raise ValueError("P2 must fork the original 15360-step, 1e-4 trajectory") + if config["sources"] != source_hashes(): + raise ValueError("Frozen parent training sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent Torch/NumPy versions differ from continuation") + if config["world"] != world.seed or config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent world/truth mismatch") + if config["prompts_sha256"] != array_hash(world.prompts): + raise ValueError("Parent query prompts changed") + for name, expected in { + "layers": 8, + "heads": study["width"] // 64, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "edit_steps": 512, + "edit_lr": 0.00003, + "retention_kl": 1.0, + }.items(): + if study[name] != expected: + raise ValueError(f"Unexpected frozen parent setting: {name}") + docs, schedule = documents(world, config["condition"]), qa_schedule(world, FINAL_STEP) + with np.load(parent / "schedule.npz") as old: + np.testing.assert_array_equal(docs, old["documents"]) + np.testing.assert_array_equal(schedule[:PARENT_STEP], old["qa"]) + if array_hash(docs) != config["documents_sha256"]: + raise ValueError("Parent document hash mismatch") + if array_hash(schedule[:PARENT_STEP]) != config["qa_sha256"]: + raise ValueError("Extended QA stream does not preserve the original prefix") + resume = torch.load(parent / "resume.pt", map_location="cpu", weights_only=False) + if resume["step"] != PARENT_STEP or resume["config_sha256"] != file_hash( + parent / "config.json" + ): + raise ValueError("Parent resume step/config mismatch") + validate_optimizer(resume["optimizer"], PARENT_STEP, study["lr"]) + saved_model = torch.load( + parent / f"model-{PARENT_STEP}.pt", map_location="cpu", weights_only=False + ) + completed = json.loads((parent / "learning-complete.json").read_text()) + model_hash = state_hash(resume["model"]) + if ( + model_hash != state_hash(saved_model["model"]) + or model_hash != completed["model_sha256"] + or saved_model["step"] != PARENT_STEP + or saved_model["config"] != config["model"] + ): + raise ValueError("Parent final model and resume state disagree") + expected = expected_exposure(world, docs, schedule, PARENT_STEP, study["lr"]) + with np.load(parent / f"predictions-{PARENT_STEP}.npz") as predictions: + for key, wanted in zip(("counts", "slots", "weighted"), expected, strict=True): + if key == "weighted": + np.testing.assert_allclose(resume[key], wanted, rtol=0, atol=1e-10) + else: + np.testing.assert_array_equal(resume[key], wanted) + stored_key = "exposure" if key == "counts" else key + np.testing.assert_array_equal(resume[key], predictions[stored_key]) + if resume["timeline"][-1]["step"] != PARENT_STEP: + raise ValueError("Parent learning history lacks the final checkpoint") + if not isinstance(resume["torch_rng"], torch.Tensor): + raise ValueError("Parent torch RNG is missing") + files = ( + "config.json", + "resume.pt", + f"model-{PARENT_STEP}.pt", + "schedule.npz", + f"predictions-{PARENT_STEP}.npz", + "learning-complete.json", + ) + provenance = { + "directory": str(parent), + "files_sha256": {name: file_hash(parent / name) for name in files}, + "model_sha256": model_hash, + "optimizer_sha256": tree_hash(resume["optimizer"]), + "torch_rng_sha256": tree_hash(resume["torch_rng"]), + "cuda_rng_sha256": tree_hash(resume["cuda_rng"]), + "qa_prefix_verified": True, + "exposure_reconstruction_verified": True, + } + return config, resume, docs, schedule, provenance + + +def restore_state(model, optimizer, saved, device): + model.load_state_dict(saved["model"]) + # load_state_dict may alias CPU tensors; branch updates must not mutate the parent. + optimizer.load_state_dict(copy.deepcopy(saved["optimizer"])) + torch.set_rng_state(saved["torch_rng"].cpu()) + if device.type == "cuda": + if saved["cuda_rng"] is None: + raise ValueError("CUDA parent/resume RNG state is missing") + torch.cuda.set_rng_state(saved["cuda_rng"].cpu(), device) + + +def capture_state(model, optimizer, device, **metadata): + return { + **metadata, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + } + + +def learning_update(model, optimizer, cache, data, qa, start, end, lr, device): + """The original arithmetic/gradient order, with an absolute-step learning rate.""" + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(cache["tokens"][start:end], cache["positions"][start:end]) + doc_loss = F.cross_entropy( + logits.float().flatten(0, 1), cache["labels"][start:end].flatten() + ) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(data["tokens"][qa], data["positions"][qa]) + qa_loss = F.cross_entropy(logits.float().flatten(0, 1), data["labels"][qa].flatten()) + (0.2 * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1) + if not torch.isfinite(doc_loss + qa_loss + norm): + raise FloatingPointError("Nonfinite continuation update") + optimizer.step() + + +def learning(parent, out, world, base_lr, device): + old_config, parent_resume, docs, schedule, provenance = validate_parent(parent, world, base_lr) + study = { + **old_config["study"], + "protocol": "v2.8-development-p2-continuation", + "steps": FINAL_STEP, + "checkpoints": list(CHECKPOINTS), + "lr": base_lr, + "edit_scopes": ["mlp"], + "seeds": [0] if base_lr == 0.0003 else [0, 1], + "learning_runs": 6 if base_lr == 0.0003 else 12, + "edit_cases": 24 if base_lr == 0.0003 else 48, + "edit_cases_per_run": 4, + "parent_step": PARENT_STEP, + "warmup": "original absolute epoch; no restart", + "primary_learning": ( + "heldout full-answer accuracy at 30720 absolute steps; " + "preserve all prespecified earlier checkpoints" + ), + "aggregation": ( + "pair organizations within world/initialization; " + "development worlds are not confirmatory replications" + ), + } + identity = { + "world": old_config["world"], + "seed": old_config["seed"], + "condition": old_config["condition"], + "study": study, + "sources": continuation_sources(), + "parent": provenance, + "model": old_config["model"], + "initial_sha256": old_config["initial_sha256"], + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + "torch": torch.__version__, + "numpy": np.__version__, + "device_type": device.type, + "cuda": torch.version.cuda, + "gpu_type": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + } + config_path = out / "config.json" + if config_path.exists(): + existing = json.loads(config_path.read_text()) + if any(existing.get(key) != value for key, value in identity.items()): + raise ValueError("Continuation identity, parent, software or sources changed") + else: + write_json( + config_path, + { + **identity, + "python": platform.python_version(), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast; FP32 weights and optimizer", + "parameters": old_config["parameters"], + }, + ) + atomic_numpy_save(out / "schedule.npz", documents=docs, qa=schedule) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + model_config = ModelConfig(**old_config["model"]) + model = CausalLM(model_config).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=base_lr, weight_decay=0.1, fused=device.type == "cuda" + ) + if (out / "resume.pt").exists(): + saved = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if saved["config_sha256"] != file_hash(config_path): + raise ValueError("Continuation resume configuration mismatch") + else: + saved = {**parent_resume, "timeline": [], "config_sha256": file_hash(config_path)} + restore_state(model, optimizer, saved, device) + first, seconds = saved["step"], saved["seconds"] + timeline = saved["timeline"] + counts, slots, weighted = saved["counts"], saved["slots"], saved["weighted"] + if not PARENT_STEP <= first <= FINAL_STEP: + raise ValueError("Continuation resume step is outside its frozen interval") + data = tensor_queries(world, device) + + def save_resume(step): + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + counts=counts, + slots=slots, + weighted=weighted, + config_sha256=file_hash(config_path), + ), + out / "resume.pt", + ) + + epoch_cached = -1 + for step in range(first, FINAL_STEP + 1): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + if step == PARENT_STEP: + with np.load(Path(parent) / f"predictions-{PARENT_STEP}.npz") as old: + arrays = { + key: old[key] for key in ("prediction", "ended", "correct", "value_nll") + } + else: + arrays = evaluate(model, data, world.answers) + point = { + "step": step, + **learning_metrics(world, arrays), + "train_seconds": seconds, + "exposure_sha256": array_hash(counts), + "slots_sha256": array_hash(slots), + "weighted_sha256": array_hash(weighted), + "train_matmul_flops_estimate": step + * (matmul_flops(model_config, 16, 60, 20) + matmul_flops(model_config, 40, 6, 2)), + } + timeline.append(point) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slots=slots, + weighted=weighted, + ) + atomic_torch_save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + write_json(out / "learning.json", timeline) + save_resume(step) + print(json.dumps({"event": "checkpoint", **point}), flush=True) + if step == FINAL_STEP: + break + epoch, offset = divmod(step, 128) + if epoch != epoch_cached: + arranged = epoch_documents(docs, world.seed, epoch) + cache = { + key: torch.as_tensor(value, device=device) + for key, value in render(world, arranged).items() + } + epoch_cached = epoch + start, end = offset * 16, (offset + 1) * 16 + qa = torch.as_tensor(schedule[step], device=device) + lr = continuation_lr(base_lr, step) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + learning_update(model, optimizer, cache, data, qa, start, end, lr, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + fact_ids = arranged[start:end] + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, schedule[step], 1) + np.add.at(slots, (fact_ids, np.arange(10)[None, :]), 1) + np.add.at(weighted, fact_ids.ravel(), lr) + np.add.at(weighted, schedule[step], lr) + if (step + 1) % 256 == 0 and step + 1 not in CHECKPOINTS: + save_resume(step + 1) + print( + json.dumps({"event": "progress", "step": step + 1, "seconds": seconds}), flush=True + ) + write_json( + out / "learning-complete.json", + { + "status": "complete", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + return model, data, study + + +def edit_metrics(world, pair, arrays, old_correct): + metrics = original_edit_metrics(world, pair, arrays, old_correct) + heldout = np.intersect1d(pair["conflict_D"], world.heldout_ids.ravel()) + metrics["D_conflict_heldout_n"] = len(heldout) + metrics["D_conflict_heldout"] = ( + float(arrays["correct"][heldout].mean()) if len(heldout) else None + ) + for label, ids in (("default", world.root_ids.ravel()), ("actual", world.actual_ids.ravel())): + subset = np.intersect1d(pair["E"], ids) + metrics[f"E_{label}_n"] = len(subset) + metrics[f"E_{label}"] = float(arrays["correct"][subset].mean()) + return metrics + + +def edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device): + model.train() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce = F.cross_entropy(logits.flatten(0, 1), new_data["labels"][ei].flatten()) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite continuation edit") + optimizer.step() + + +def edits(world, model, data, out, study, device): + baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()} + old_arrays = evaluate(model, data, world.answers) + config_sha = file_hash(out / "config.json") + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + e_choices = rng.integers(len(pair["E"]), size=(512, 128)) + r_choices = rng.integers(len(pair["replay"]), size=(512, 128)) + for kind in ("coherent", "exception"): + dest = out / "edits" / f"{name}-{kind}-mlp" + if (dest / "complete.json").exists(): + continue + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + target = pair[kind] + new_data = tensor_queries(world, device, target) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline, seconds, first = [], 0.0, 0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["config_sha256"] != config_sha or saved["case"] != dest.name: + raise ValueError("Editing resume identity mismatch") + restore_state(model, optimizer, saved, device) + timeline, seconds, first = saved["timeline"], saved["seconds"], saved["step"] + for step in range(first, 513): + if step in EDIT_CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, data, target) + point = { + "step": step, + **edit_metrics(world, pair, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + config_sha256=config_sha, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update( + model, optimizer, selected, data, new_data, references, ei, ri, choices, device + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict()}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "chain": name, + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + }, + ) + print( + json.dumps( + { + "event": "edit_complete", + "case": dest.name, + "E": timeline[-1]["E"], + "D": timeline[-1]["D"], + } + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--lr", type=float, choices=(0.0001, 0.0003), default=0.0001) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + parser.add_argument("--learning-only", action="store_true") + args = parser.parse_args() + parent, out = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == out or parent in out.parents or out in parent.parents: + raise ValueError("Continuation output must be separate from its immutable parent") + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + world = make_cross_world(json.loads((parent / "config.json").read_text())["world"]) + audit(world) + device = torch.device(args.device) + try: + model, data, study = learning(parent, out, world, args.lr, device) + if not args.learning_only: + edits(world, model, data, out, study, device) + write_json( + out / "complete.json", + { + "status": "complete", + "learning_steps": FINAL_STEP, + "edit_cases": 4, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_cross_scale.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_cross_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..af5c92edca554475a9bdf9dee9b46438455b1f96 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_cross_scale.py @@ -0,0 +1,51 @@ +"""Contracts and denominator-aware summaries for the frozen crossover size extension.""" + +from itertools import product + +import numpy as np + + +def validate_size_study(reference, study, width, heads): + expected = {**reference, "width": width, "heads": heads} + if study != expected: + changed = sorted(k for k in set(expected) | set(study) if expected.get(k) != study.get(k)) + raise ValueError(f"Non-size study changes: {changed}") + if width // heads != 64 or study["layers"] != 8: + raise ValueError("Expected eight layers and head dimension 64") + + +def validate_run_grid(configs, study, require_complete): + expected = set(product(study["worlds"], study["seeds"], study["conditions"])) + keys = [(c["world"], c["seed"], c["condition"]) for c in configs] + if len(keys) != len(set(keys)) or set(keys) - expected: + raise ValueError("Duplicate or unexpected experimental units") + if require_complete and set(keys) != expected: + raise ValueError("Missing experimental units") + + +def retention_coverage(pair, old_correct, row): + """Keep unknown facts outside the damage denominator and expose their coverage.""" + result = {} + for pool_name, pool in ( + ("full", np.arange(len(old_correct))), + ("heldout", pair["heldout"]), + ): + totals, knowns, brokens = [], [], [] + for group in range(4): + ids = np.intersect1d(pool, np.flatnonzero(pair["strata"] == group)) + prefix = f"U_{pool_name}_{group}" + total, known, broken = len(ids), int(old_correct[ids].sum()), row[f"{prefix}_broken"] + if known != row[f"{prefix}_known"] or not 0 <= broken <= known: + raise ValueError("Retention denominator or broken count mismatch") + totals.append(total) + knowns.append(known) + brokens.append(broken) + result[f"{prefix}_total"] = total + result[f"{prefix}_coverage"] = known / total if total else None + total, known, broken = sum(totals), sum(knowns), sum(brokens) + result[f"U_{pool_name}_total"] = total + result[f"U_{pool_name}_coverage"] = known / total if total else None + result[f"U_{pool_name}_micro_damage"] = broken / known if known else None + result["E_old_accuracy"] = float(old_correct[pair["E"]].mean()) + result["D_old_accuracy"] = float(old_correct[pair["D"]].mean()) + return result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_cross_train.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_cross_train.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5f3f45a169e643c408f1044eaa766b79a595fd --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_cross_train.py @@ -0,0 +1,474 @@ +"""Frozen learning and editing runs for the two-relation crossover.""" + +import argparse +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CHAINS, + CONDITIONS, + audit, + documents, + edit_pair, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + + +def tensor_queries(world, device, answers=None): + answers = world.answers if answers is None else answers + prompts = torch.as_tensor(world.prompts, device=device) + lengths = torch.as_tensor(world.lengths, device=device) + targets = torch.as_tensor(answers, device=device) + tokens = torch.zeros((len(answers), 6), device=device, dtype=torch.long) + tokens[:, :5] = prompts + tokens[torch.arange(len(answers), device=device), lengths] = targets + tokens[lengths == 4, 5] = EOS + return { + "prompts": prompts, + "lengths": lengths, + "tokens": tokens, + "positions": torch.stack([lengths - 1, lengths], -1), + "labels": torch.stack([targets, torch.full_like(targets, EOS)], -1), + } + + +@torch.no_grad() +def evaluate(model, data, answers, batch_size=512): + model.eval() + device = data["tokens"].device + predictions, ended, nll = [], [], [] + for begin in range(0, len(answers), batch_size): + end = min(begin + batch_size, len(answers)) + lengths = data["lengths"][begin:end] + with precision(device): + logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float() + first = logits.argmax(-1) + continuation = torch.zeros((end - begin, 6), device=device, dtype=torch.long) + continuation[:, :5] = data["prompts"][begin:end] + continuation[torch.arange(end - begin, device=device), lengths] = first + second = model(continuation, lengths[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + targets = torch.as_tensor(answers[begin:end], device=device) + nll.append(F.cross_entropy(logits, targets, reduction="none").cpu().numpy()) + prediction, ended = np.concatenate(predictions), np.concatenate(ended) + return { + "prediction": prediction, + "ended": ended, + "correct": (prediction == answers) & ended, + "value_nll": np.concatenate(nll), + } + + +def learning_metrics(world, arrays): + correct = arrays["correct"] + result = { + "base_accuracy": float(correct[: world.n_base].mean()), + "base_nll": float(arrays["value_nll"][: world.n_base].mean()), + } + for chain, name in enumerate(CHAINS): + for split, ids in ( + ("trained", world.train_ids[chain]), + ("heldout", world.heldout_ids[chain]), + ): + result[f"{name}_{split}"] = float(correct[ids].mean()) + result[f"{name}_{split}_nll"] = float(arrays["value_nll"][ids].mean()) + for label, ids in ( + ("membership", world.membership_ids[chain]), + ("default", world.root_ids[chain]), + ("actual", world.actual_ids[chain]), + ): + result[f"{name}_{label}"] = float(correct[ids].mean()) + # A conditional diagnostic, never a replacement for the whole test pool. + prerequisites = ( + correct[world.membership_ids[chain]] + & correct[world.root_ids[chain, world.memberships[chain]]] + ) + known_ids = np.intersect1d( + world.heldout_ids[chain], world.derived_ids[chain, prerequisites] + ) + result[f"{name}_known_heldout_n"] = len(known_ids) + result[f"{name}_known_heldout"] = ( + float(correct[known_ids].mean()) if len(known_ids) else None + ) + result["mean_heldout"] = (result["company_heldout"] + result["project_heldout"]) / 2 + return result + + +def source_hashes(): + root = Path(__file__).parent + return { + name: hashlib.sha256((root / name).read_bytes()).hexdigest() + for name in ( + "bios_cross.py", + "bios_cross_train.py", + "bios_model.py", + "bios_data.py", + "bios_train.py", + "bios_organization_train.py", + ) + } + + +def learning(args, world, out, study, device): + torch.manual_seed(args.seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + config = ModelConfig(world.vocab_size, study["width"], study["layers"], study["heads"]) + model = CausalLM(config).to(device) + initial_hash = state_hash(model.state_dict()) + docs, schedule = documents(world, args.condition), qa_schedule(world, study["steps"]) + identity = { + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "study": study, + "sources": source_hashes(), + "model": model.config_dict(), + "initial_sha256": initial_hash, + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + } + config_path = out / "config.json" + if config_path.exists(): + saved = json.loads(config_path.read_text()) + if any(saved[k] != v for k, v in identity.items()): + raise ValueError("Frozen run identity or sources changed") + else: + write_json( + config_path, + { + **identity, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "python": platform.python_version(), + "numpy": np.__version__, + "device": str(device), + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "precision": "BF16 autocast; FP32 weights and optimizer", + "parameters": sum(p.numel() for p in model.parameters()), + }, + ) + atomic_numpy_save(out / "schedule.npz", documents=docs, qa=schedule) + data = tensor_queries(world, device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=study["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline, first, seconds = [], 0, 0.0 + counts = np.zeros(len(world.answers), dtype=np.int64) + slots = np.zeros((world.n_base, 10), dtype=np.int64) + weighted = np.zeros(len(world.answers), dtype=np.float64) + if (out / "resume.pt").exists(): + resume = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if resume["config_sha256"] != hashlib.sha256(config_path.read_bytes()).hexdigest(): + raise ValueError("Resume configuration mismatch") + model.load_state_dict(resume["model"]) + optimizer.load_state_dict(resume["optimizer"]) + first, timeline, seconds = resume["step"], resume["timeline"], resume["seconds"] + counts, slots, weighted = resume["counts"], resume["slots"], resume["weighted"] + torch.set_rng_state(resume["torch_rng"]) + if device.type == "cuda": + torch.cuda.set_rng_state(resume["cuda_rng"], device) + epoch_cached, cache = -1, None + for step in range(first, study["steps"] + 1): + if step in study["checkpoints"] and (not timeline or step != first): + arrays = evaluate(model, data, world.answers) + point = { + "step": step, + **learning_metrics(world, arrays), + "train_seconds": seconds, + "exposure_sha256": array_hash(counts), + "slots_sha256": array_hash(slots), + "weighted_sha256": array_hash(weighted), + "train_matmul_flops_estimate": step + * (matmul_flops(config, 16, 60, 20) + matmul_flops(config, 40, 6, 2)), + } + timeline.append(point) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slots=slots, + weighted=weighted, + ) + atomic_torch_save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + write_json(out / "learning.json", timeline) + atomic_torch_save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "timeline": timeline, + "seconds": seconds, + "counts": counts, + "slots": slots, + "weighted": weighted, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), + }, + out / "resume.pt", + ) + print(json.dumps({"event": "checkpoint", **point}), flush=True) + if step == study["steps"]: + break + epoch, offset = divmod(step, 128) + if epoch != epoch_cached: + arranged = epoch_documents(docs, world.seed, epoch) + cache = { + k: torch.as_tensor(v, device=device) for k, v in render(world, arranged).items() + } + epoch_cached = epoch + start, end = offset * 16, (offset + 1) * 16 + fact_ids = arranged[start:end] + qa = torch.as_tensor(schedule[step], device=device) + lr = study["lr"] * min((epoch + 1) / 16, 1) + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(cache["tokens"][start:end], cache["positions"][start:end]) + doc_loss = F.cross_entropy( + logits.float().flatten(0, 1), cache["labels"][start:end].flatten() + ) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(data["tokens"][qa], data["positions"][qa]) + qa_loss = F.cross_entropy(logits.float().flatten(0, 1), data["labels"][qa].flatten()) + (0.2 * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1) + if not torch.isfinite(doc_loss + qa_loss + norm): + raise FloatingPointError("Nonfinite learning update") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, schedule[step], 1) + np.add.at(slots, (fact_ids, np.arange(10)[None, :]), 1) + np.add.at(weighted, fact_ids.ravel(), lr) + np.add.at(weighted, schedule[step], lr) + if (step + 1) % 256 == 0: + print( + json.dumps({"event": "progress", "step": step + 1, "seconds": seconds}), flush=True + ) + write_json( + out / "learning-complete.json", + { + "status": "complete", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + return model, data + + +def edit_metrics(world, pair, arrays, old_correct): + correct = arrays["correct"] + metrics = { + "E": float(correct[pair["E"]].mean()), + "D": float(correct[pair["D"]].mean()), + "D_conflict": float(correct[pair["conflict_D"]].mean()), + } + for split, ids in ( + ("trained", world.train_ids.ravel()), + ("heldout", world.heldout_ids.ravel()), + ): + subset = np.intersect1d(pair["D"], ids) + metrics[f"D_{split}_n"] = len(subset) + metrics[f"D_{split}"] = float(correct[subset].mean()) if len(subset) else None + for name, pool in (("full", np.arange(len(correct))), ("heldout", pair["heldout"])): + strata = {} + for group in range(4): + ids = np.intersect1d(pool, np.flatnonzero((pair["strata"] == group) & old_correct)) + strata[str(group)] = { + "known": len(ids), + "broken": int((~correct[ids]).sum()), + "rate": float((~correct[ids]).mean()) if len(ids) else None, + } + metrics[f"U_{name}"] = strata + return metrics + + +def edits(args, world, model, data, out, study, device): + baseline = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()} + old_arrays = evaluate(model, data, world.answers) + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + e_choices = rng.integers(len(pair["E"]), size=(study["edit_steps"], 128)) + r_choices = rng.integers(len(pair["replay"]), size=(study["edit_steps"], 128)) + for kind in ("coherent", "exception"): + target = pair[kind] + new_data = tensor_queries(world, device, target) + for scope in ("mlp", "all"): + dest = out / "edits" / f"{name}-{kind}-{scope}" + if (dest / "complete.json").exists(): + continue + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, scope, 3) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append( + model(data["tokens"][ids], data["positions"][ids]).detach() + ) + references = torch.cat(references) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline = [] + seconds = 0.0 + for step in range(study["edit_steps"] + 1): + if step in study["edit_checkpoints"]: + arrays = evaluate(model, data, target) + point = { + "step": step, + **edit_metrics(world, pair, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step == study["edit_steps"]: + break + model.train() + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce = F.cross_entropy(logits.flatten(0, 1), new_data["labels"][ei].flatten()) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + study["retention_kl"] * kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite edit") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict()}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "chain": name, + "kind": kind, + "scope": scope, + "final": timeline[-1], + }, + ) + print( + json.dumps( + { + "event": "edit_complete", + "case": dest.name, + "E": timeline[-1]["E"], + "D": timeline[-1]["D"], + } + ), + flush=True, + ) + del references, optimizer + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--config", default="configs/bios-cross-development-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + args = parser.parse_args() + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + study = json.loads(Path(args.config).read_text()) + torch.set_num_threads(args.threads) + device = torch.device(args.device) + world = make_cross_world(args.world) + audit(world) + try: + model, data = learning(args, world, out, study, device) + edits(args, world, model, data, out, study, device) + write_json( + out / "complete.json", + { + "status": "complete", + "learning_steps": study["steps"], + "edit_cases": 8, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_data.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3acf9b51a11985eb747a2c2565bc551ae803fd9b --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_data.py @@ -0,0 +1,367 @@ +"""bioS-Work-v1 truth, equal-exposure curricula and paired counterfactual worlds. + +Official files remain unmodified in data/bios-source; this is a new adapter. +The symbolic experiment does not imply that the natural-language audit is complete. +""" + +import calendar +import hashlib +import json +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +REVISION = "211b28f2e9d453114ca5a1cbbb2d5a632ac60fcf" +SOURCE_FOLDER = "data-synthetic-pretrain/Capo-bioS-bioR" +RELATIONS = ( + "employer", + "default_city", + "actual_city", + "birth_date", + "birth_city", + "university", + "major", +) +N_PEOPLE, N_COMPANIES, N_BASE, N_QUERIES = 2048, 64, 12352, 14400 +PAD, BOS, ANS, EOS = range(4) + + +def rng_for(seed, purpose, index=0): + return np.random.default_rng(np.random.SeedSequence([seed, purpose, index])) + + +def array_hash(array): + return hashlib.sha256(np.ascontiguousarray(array).tobytes()).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, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temporary.replace(path) + + +@dataclass +class World: + seed: int + prompts: np.ndarray + lengths: np.ndarray + answers: np.ndarray + relation: np.ndarray + person: np.ndarray + company: np.ndarray + employers: np.ndarray + defaults: np.ndarray + actual: np.ndarray + exceptions: np.ndarray + city_tokens: np.ndarray + token_labels: list + names: dict + + @property + def vocab_size(self): + return len(self.token_labels) + + def save(self, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + arrays = {k: v for k, v in vars(self).items() if isinstance(v, np.ndarray)} + np.savez_compressed(directory / "world.npz", **arrays) + write_json( + directory / "metadata.json", + {"seed": self.seed, "token_labels": self.token_labels, "names": self.names}, + ) + write_json(directory / "audit.json", audit_world(self)) + + +def load_world(directory): + directory = Path(directory) + metadata = json.loads((directory / "metadata.json").read_text()) + with np.load(directory / "world.npz", allow_pickle=False) as arrays: + return World(**metadata, **dict(arrays)) + + +def make_world(seed, source_root="data/bios-source"): + source_root = Path(source_root) + manifest = json.loads((source_root / "manifest.json").read_text()) + if manifest["revision"] != REVISION: + raise ValueError("Unexpected official source revision") + for entry in manifest["files"]: + if ( + hashlib.sha256((source_root / entry["path"]).read_bytes()).hexdigest() + != entry["sha256"] + ): + raise ValueError("Source hash mismatch: " + entry["path"]) + + def field(name): + return (source_root / SOURCE_FOLDER / "fields" / (name + ".txt")).read_text().splitlines() + + cities, universities, majors = field("city"), field("university"), field("field") + first, middle, last = field("first_name"), field("middle_name"), field("last_name") + names_rng, group_rng, value_rng = (rng_for(seed, i) for i in (11, 12, 13)) + + def unique_names(count): + result, used = [], set() + while len(result) < count: + value = f"{names_rng.choice(first)} {names_rng.choice(middle)} {names_rng.choice(last)}" + if value.casefold() not in used: + result.append(value) + used.add(value.casefold()) + return result + + person_names = unique_names(2 * N_PEOPLE) + syllables = ("va", "ne", "ri", "lo", "sa", "tu", "mi", "ze", "ka", "po", "da", "fi") + company_names, used = [], set() + while len(company_names) < 2 * N_COMPANIES: + value = "".join(names_rng.choice(syllables, 4)).capitalize() + " Labs" + if value not in used: + used.add(value) + company_names.append(value) + employers = group_rng.permutation(np.repeat(np.arange(N_COMPANIES), 32)) + work_cities = value_rng.choice(len(cities), 32, replace=False) + defaults = value_rng.permutation(np.repeat(work_cities, 2)) + exceptions = np.zeros(N_PEOPLE, dtype=bool) + actual = defaults[employers].copy() + for c in range(N_COMPANIES): + selected = group_rng.choice(np.flatnonzero(employers == c), 2, replace=False) + exceptions[selected] = True + actual[selected] = value_rng.choice(work_cities[work_cities != defaults[c]], 2) + attributes_rng = rng_for(seed, 14) + years = attributes_rng.integers(1900, 2100, N_PEOPLE) + months = attributes_rng.integers(1, 13, N_PEOPLE) + days = attributes_rng.integers(1, 29, N_PEOPLE) + dates = [ + f"{calendar.month_name[m]} {d}, {y}" for y, m, d in zip(years, months, days, strict=True) + ] + birth_cities = attributes_rng.integers(0, len(cities), N_PEOPLE) + university = attributes_rng.integers(0, len(universities), N_PEOPLE) + major = attributes_rng.integers(0, len(majors), N_PEOPLE) + labels = ( + [f"person:{i}" for i in range(N_PEOPLE)] + + [f"company:{i}" for i in range(N_COMPANIES)] + + [f"city:{i}" for i in range(len(cities))] + + [f"date:{d}" for d in sorted(set(dates))] + + [f"university:{i}" for i in range(len(universities))] + + [f"major:{i}" for i in range(len(majors))] + + [f"relation:{r}" for r in RELATIONS] + ) + labels = list(rng_for(seed, 15).permutation(labels)) + token_labels = ["", "", "", ""] + labels + token = {label: i for i, label in enumerate(token_labels)} + city_tokens = np.array([token[f"city:{i}"] for i in range(len(cities))]) + prompts = np.full((N_QUERIES, 5), PAD, dtype=np.int64) + lengths = np.full(N_QUERIES, 4, dtype=np.int64) + answers = np.empty(N_QUERIES, dtype=np.int64) + relation = np.empty(N_QUERIES, dtype=np.int64) + person = np.full(N_QUERIES, -1, dtype=np.int64) + company = np.empty(N_QUERIES, dtype=np.int64) + values = [ + [token[f"company:{c}"] for c in employers], + city_tokens[defaults], + city_tokens[actual], + [token[f"date:{d}"] for d in dates], + city_tokens[birth_cities], + [token[f"university:{u}"] for u in university], + [token[f"major:{m}"] for m in major], + ] + offset = 0 + for rel, rel_values in enumerate(values): + for i, value in enumerate(rel_values): + q = offset + i + is_company = rel == 1 + subject = token[f"company:{i}" if is_company else f"person:{i}"] + prompts[q, :4] = [BOS, subject, token[f"relation:{RELATIONS[rel]}"], ANS] + answers[q], relation[q] = value, rel + company[q] = i if is_company else employers[i] + if not is_company: + person[q] = i + offset += len(rel_values) + for i in range(N_PEOPLE): + q = N_BASE + i + prompts[q] = [ + BOS, + token[f"person:{i}"], + token["relation:employer"], + token["relation:default_city"], + ANS, + ] + answers[q] = city_tokens[defaults[employers[i]]] + lengths[q], relation[q], person[q], company[q] = 5, 7, i, employers[i] + names = { + "people": person_names[:N_PEOPLE], + "people_aliases": person_names[N_PEOPLE:], + "companies": company_names[:N_COMPANIES], + "company_aliases": company_names[N_COMPANIES:], + "company_source_ids": names_rng.choice( + len(field("company")), N_COMPANIES, replace=False + ).tolist(), + "cities": cities, + "universities": universities, + "majors": majors, + "work_city_ids": work_cities.tolist(), + } + world = World( + seed, + prompts, + lengths, + answers, + relation, + person, + company, + employers, + defaults, + actual, + exceptions, + city_tokens, + token_labels, + names, + ) + audit_world(world) + return world + + +def curriculum(world, order, total_steps, batch_size=128): + if order not in {"SA", "AS"} or total_steps < 5280 or batch_size != 128: + raise ValueError("Protocol curriculum requires SA/AS, >=5280 steps and batch 128") + s = np.flatnonzero(np.isin(world.relation[:N_BASE], [0, 1])) + a = np.flatnonzero(~np.isin(world.relation[:N_BASE], [0, 1])) + parts = {} + for name, ids, repeats, purpose in (("S", s, 160, 21), ("A", a, 33, 22)): + rng = rng_for(world.seed, purpose) + parts[name] = np.concatenate([rng.permutation(ids) for _ in range(repeats)]) + assert len(parts[name]) == 337920 + rng = rng_for(world.seed, 23) + n_mix = (total_steps - 5280) * batch_size + # Exact 80:20 across each five-step block; final partial block is recorded. + n_derived = n_mix // 5 + n_atomic = n_mix - n_derived + atomic = np.concatenate([rng.permutation(N_BASE) for _ in range(n_atomic // N_BASE + 1)])[ + :n_atomic + ] + derived = N_BASE + np.tile(rng.permutation(N_PEOPLE), n_derived // N_PEOPLE + 1)[:n_derived] + mixed = np.empty(n_mix, dtype=np.int64) + derived_positions = np.arange(4, n_mix, 5) + mixed[derived_positions] = derived + is_atomic = np.ones(n_mix, dtype=bool) + is_atomic[derived_positions] = False + mixed[is_atomic] = atomic + return np.concatenate([parts[order[0]], parts[order[1]], mixed]).reshape( + total_steps, batch_size + ) + + +def paired_edit(world, support=0, k=1): + if k not in (1, 4, 16): + raise ValueError("Protocol scales are 1, 4 and 16") + rng = rng_for(world.seed, 31, support + 100 * k) + # Draw whole disjoint supports until every triple has three different defaults. + for _ in range(100000): + companies = rng.choice(N_COMPANIES, 3 * k, replace=False).reshape(k, 3) + if all(len(set(world.defaults[t])) == 3 for t in companies): + break + else: + raise RuntimeError("No valid support") + coherent, exception = world.answers.copy(), world.answers.copy() + for triple in companies: + old = world.defaults[triple] + for j, c in enumerate(triple): + next_city, alternate = old[(j + 1) % 3], old[(j + 2) % 3] + root = 2048 + c + coherent[root] = exception[root] = world.city_tokens[next_city] + members = rng.permutation(np.flatnonzero((world.employers == c) & ~world.exceptions)) + rows = 2112 + members + coherent[rows] = world.city_tokens[next_city] + exception[rows[:15]], exception[rows[15:]] = ( + world.city_tokens[next_city], + world.city_tokens[alternate], + ) + derived = N_BASE + np.flatnonzero(world.employers == c) + coherent[derived] = exception[derived] = world.city_tokens[next_city] + edit_mask = coherent != world.answers + assert np.array_equal(edit_mask, exception != world.answers) + e = np.flatnonzero(edit_mask & (np.arange(N_QUERIES) < N_BASE)) + d = np.flatnonzero(edit_mask & (np.arange(N_QUERIES) >= N_BASE)) + u = ~edit_mask + selected = np.isin(world.company, companies.ravel()) + old_exception = (world.relation == 2) & world.exceptions[np.maximum(world.person, 0)] + strata = np.full(N_QUERIES, -1, dtype=np.int64) + strata[u & selected & old_exception] = 0 + strata[u & selected & ~old_exception] = 1 + strata[u & ~selected & np.isin(world.relation, [1, 2, 7])] = 2 + strata[u & ~selected & np.isin(world.relation, [0, 3, 4, 5, 6])] = 3 + assert np.array_equal(strata >= 0, u) + assert len(e) == 93 * k and len(d) == 96 * k + assert np.array_equal( + np.bincount(coherent[e], minlength=world.vocab_size), + np.bincount(exception[e], minlength=world.vocab_size), + ) + split_rng = rng_for(world.seed, 32, support + 100 * k) + replay_pool, heldout = [], [] + for group in range(4): + ids = split_rng.permutation( + np.flatnonzero((strata == group) & (np.arange(N_QUERIES) < N_BASE)) + ) + n_test = max(1, int(np.ceil(0.2 * len(ids)))) + heldout.extend(ids[:n_test]) + replay_pool.extend(ids[n_test:]) + heldout.extend(np.flatnonzero(u & (np.arange(N_QUERIES) >= N_BASE))) + replay = split_rng.choice(replay_pool, min(4096, len(replay_pool)), replace=False) + return { + "companies": companies, + "coherent": coherent, + "exception": exception, + "E": e, + "D": d, + "strata": strata, + "replay": replay, + "heldout": np.array(sorted(heldout)), + "support": support, + "k": k, + "selection": "prespecified_unmatched", + } + + +def audit_world(world): + assert world.prompts.shape == (N_QUERIES, 5) + assert len(set(map(tuple, world.prompts))) == N_QUERIES + assert np.array_equal(np.bincount(world.employers), np.full(N_COMPANIES, 32)) + assert np.array_equal(np.unique(world.defaults, return_counts=True)[1], np.full(32, 2)) + assert world.exceptions.sum() == 128 + assert np.array_equal( + np.bincount(world.employers[world.exceptions], minlength=64), np.full(64, 2) + ) + assert np.array_equal(world.actual != world.defaults[world.employers], world.exceptions) + assert np.array_equal(world.answers[2112:4160], world.city_tokens[world.actual]) + assert np.array_equal( + world.answers[N_BASE:], world.city_tokens[world.defaults[world.employers]] + ) + for key, alias in (("people", "people_aliases"), ("companies", "company_aliases")): + names = world.names[key] + world.names[alias] + assert len(set(n.casefold().strip() for n in names)) == len(names) + baseline = {} + for relation in range(7): + values = world.answers[world.relation == relation] + answer = int(np.bincount(values, minlength=world.vocab_size).argmax()) + baseline[RELATIONS[relation]] = { + "answer_token": answer, + "accuracy": float(np.mean(values == answer)), + } + return { + "version": "bioS-Work-v1", + "world_seed": world.seed, + "source_revision": REVISION, + "base_facts": N_BASE, + "derived_queries": N_PEOPLE, + "people": N_PEOPLE, + "companies": N_COMPANIES, + "old_exceptions": 128, + "vocab_size": world.vocab_size, + "truth_sha256": array_hash(world.answers), + "queries_sha256": array_hash(world.prompts), + "majority_baseline": baseline, + "oracle_default_baseline": {"overall": 0.9375, "old_exception": 0.0, "nonexception": 1.0}, + "symbolic_truth_audit": "passed", + "natural_language_audit": "not_complete; not used in symbolic run", + } diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_direction.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_direction.py new file mode 100644 index 0000000000000000000000000000000000000000..15e8d1db07bd56a73048608a8d9dfb99e5737a7a --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_direction.py @@ -0,0 +1,617 @@ +"""Target-complete direction experiments; batched independent down-only editors. + +The randomized generalized Gauss--Newton sketch is a diagnostic solver, not +AlphaEdit/CrispEdit. Every finite hard-constraint proposal is checked against the +original parent. Training batches contain E/R only; evaluation has no gradients. +""" + +import hashlib +import itertools +import json +import time +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +NODES = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024) +ARMS = tuple( + "-".join(x) for x in itertools.product(("func", "repr"), ("soft", "hard"), ("adam", "gn")) +) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def stable_order(values, *key): + return sorted(values, key=lambda i: hashlib.sha256(f"{key}:{int(i)}".encode()).hexdigest()) + + +def load_parent(path, device): + saved = torch.load(path, map_location=device, weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])).to(device).eval() + model.load_state_dict(saved["model"]) + for parameter in model.parameters(): + parameter.requires_grad_(False) + return model + + +@dataclass +class Task: + name: str + tokens: torch.Tensor + positions: torch.Tensor + labels: torch.Tensor + old_labels: torch.Tensor + sets: dict + metadata: dict + + def manifest(self): + return { + "name": self.name, + "sets": self.sets, + "metadata": self.metadata, + "labels": self.labels.cpu().tolist(), + "old_labels": self.old_labels.cpu().tolist(), + "tokens_sha256": hashlib.sha256(self.tokens.cpu().numpy().tobytes()).hexdigest(), + } + + +def minimal_task(seed, person, kind, device, labels=None): + people = torch.arange(32, device=device).repeat_interleave(3) + relation = torch.arange(3, device=device).repeat(32) + tokens = torch.stack( + (torch.ones_like(people), 3 + people, 35 + relation, torch.full_like(people, 2)), -1 + ) + old = 38 + (people + (relation == 2)) % 3 if labels is None else labels.to(device) + old = old[:, None] + desired = old.clone() + first, second = (0, 1) if seed % 2 == 0 else (1, 0) + i, j, k = 3 * person + first, 3 * person + second, 3 * person + 2 + c = int(old[i, 0]) + assert int(old[j, 0]) == c + a, b = 38 + (c - 38 + 1) % 3, 38 + (c - 38 + 2) % 3 + desired[i] = a if kind == "coherent" else b + e, local = [i], [k] + if kind != "selective": + desired[j] = a + e.append(j) + else: + local.append(j) + remaining = stable_order([x for x in range(32) if x != person], "split", person, 271520) + + def expand(xs): + return [3 * p + r for p in xs for r in range(3)] + + sets = { + "E": e, + "R": local + expand(remaining[:15]), + "V": expand(remaining[15:23]), + "U": expand(remaining[23:]), + "local": local, + } + return Task( + f"seed-{seed}-person-{person}-{kind}", + tokens, + torch.full((96, 1), 3, device=device), + desired, + old, + sets, + {"seed": seed, "person": person, "kind": kind, "a": a, "b": b, "c": c, "pair": [i, j]}, + ) + + +class Suffix: + """Frozen prefix cached for independent weight matrices (batch axis zero).""" + + def __init__(self, model, layer, tokens, positions): + self.model, self.layer, self.positions = model, layer, positions + if tokens.ndim == 2: + tokens = tokens[None] + self.positions = positions[None] + self.n, self.q, self.t = tokens.shape + with torch.no_grad(): + flat = tokens.reshape(-1, self.t) + x = model.token(flat) + model.position(torch.arange(self.t, device=flat.device)) + for block in model.blocks[:layer]: + x = block(x) + block = model.blocks[layer] + x = x + block.attention(block.ln1(x)) + self.base = (x + block.mlp.down.bias).reshape(self.n, self.q, self.t, -1).detach() + self.z = ( + block.mlp.activation(block.mlp.up(block.ln2(x))) + .reshape(self.n, self.q, self.t, -1) + .detach() + ) + self.forward_calls = 0 + + def __call__(self, w): + self.forward_calls += 1 + n = w.shape[0] + x = self.base + torch.einsum("nqtk,ndk->nqtd", self.z.expand(n, -1, -1, -1), w) + x = x.reshape(n * self.q, self.t, -1) + for block in self.model.blocks[self.layer + 1 :]: + x = block(x) + x = self.model.ln_final(x).reshape(n, self.q, self.t, -1) + positions = self.positions.expand(n, -1, -1) + x = x.gather(2, positions[..., None].expand(-1, -1, -1, x.shape[-1])) + return F.linear(x, self.model.token.weight) + + +def candidate_configs(arm): + obj, form, solver = arm.split("-") + rates = (1e-4, 1e-3, 1e-2) if solver == "adam" else (0.1, 0.3, 1.0) + levels = ( + (0.0, 1.0, 10.0, 100.0) + if form == "soft" + else ((0.0, 1e-6, 1e-4, 1e-2) if obj == "repr" else (1e-6, 1e-4, 1e-2, 0.1)) + ) + return [ + dict(lr=lr, level=level, damping=0.01, rank=8, refresh=16, trust_fraction=0.05) + for lr, level in itertools.product(rates, levels) + ] + + +def gaussian_newton_sketch(logits, w, weights, rank, generator): + """E[U^T U] = weighted CE GGN; independent probes per example/logit. + + B = diag(sqrt(p)) - p sqrt(p)^T satisfies BB^T = diag(p)-pp^T. + Frozen probes are differentiated through logits only, never through p. + """ + probability = logits.detach().softmax(-1) + result = [] + for _ in range(rank): + noise = torch.randn(probability.shape, device=w.device, dtype=w.dtype, generator=generator) + raw = probability.sqrt() * noise + probe = raw - probability * raw.sum(-1, keepdim=True) + probe *= weights.sqrt()[..., None] / np.sqrt(rank) + result.append( + torch.autograd.grad(logits, w, probe, retain_graph=True)[0].detach().flatten(1) + ) + return torch.stack(result, 1) + + +def inverse_sketch(v, sketch, damping): + """(damping I + U^T U)^-1 v via an exact rank-r dual solve.""" + shape = v.shape + flat = v.flatten(1) + if sketch is None: + return v / damping + k = sketch @ sketch.transpose(-1, -2) + k.diagonal(dim1=-2, dim2=-1).add_(damping) + coeff = torch.linalg.solve(k.double(), (sketch @ flat[..., None]).double()).to(v.dtype) + return ((flat - (sketch.transpose(-1, -2) @ coeff)[..., 0]) / damping).reshape(shape) + + +def representation_geometry(suffix, rmask, w0): + z = suffix.z + mask = rmask[..., None].expand(-1, -1, z.shape[2]) + # Fixed sequence length; in cross tasks only positions <= last supervised index. + valid = ( + torch.arange(z.shape[2], device=z.device)[None, None, :] + <= suffix.positions.max(-1).values[..., None] + ) + mask = mask * valid + covariance = ( + torch.einsum("nqtk,nqtl,nqt->nkl", z.double(), z.double(), mask.double()) + / mask.sum((1, 2))[:, None, None] + ) + output = torch.einsum("nqtk,dk->nqtd", z, w0) + suffix.model.blocks[suffix.layer].mlp.down.bias + scale = (output.square().sum(-1) * mask).sum((1, 2)) / mask.sum((1, 2)) + covariance = covariance / scale[:, None, None].clamp_min(1e-12) + suffix.repr_factor = ( + z * (mask / (mask.sum((1, 2)) * scale).clamp_min(1e-12)[:, None, None]).sqrt()[..., None] + ) + vals, vecs = torch.linalg.eigh(covariance.double()) + threshold = vals[:, -1:] * 1e-10 + keep = vals > threshold + null = (vecs * (~keep)[:, None, :]) @ vecs.transpose(-1, -2) + return covariance.to(w0.dtype), null.to(w0.dtype), keep.sum(-1), vals + + +def batch_setup(model, layer, tasks, configs): + ids = [t.sets["E"] + t.sets["R"] for t in tasks] + assert len(set(map(len, ids))) == 1 + toks = torch.stack([t.tokens[i] for t, i in zip(tasks, ids, strict=True)]) + positions = torch.stack([t.positions[i] for t, i in zip(tasks, ids, strict=True)]) + labels = torch.stack([t.labels[i] for t, i in zip(tasks, ids, strict=True)]) + suffix = Suffix(model, layer, toks, positions) + n, q, o = labels.shape + ermask = torch.zeros((n, q), device=toks.device) + for row, task in enumerate(tasks): + ermask[row, : len(task.sets["E"])] = 1 + rmask = 1 - ermask + eweight, rweight = ermask / ermask.sum(-1, keepdim=True), rmask / rmask.sum(-1, keepdim=True) + w0 = model.blocks[layer].mlp.down.weight.detach().clone() + with torch.no_grad(): + ref = suffix(w0[None].expand(n, -1, -1)).double().log_softmax(-1) + covariance, null, ranks, spectrum = representation_geometry(suffix, rmask, w0) + return suffix, labels, eweight, rweight, ref, covariance, null, ranks, spectrum, w0 + + +def quantities(logits, w, w0, labels, eweight, rweight, ref, covariance, obj, repr_factor): + logp = logits.double().log_softmax(-1) + ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1) + le, lr = (ce * eweight).sum(-1), (ce * rweight).sum(-1) + if obj == "func": + distance = ((ref.exp() * (ref - logp)).sum(-1).mean(-1) * rweight).sum(-1).clamp_min(0) + else: + delta = w - w0 + change = torch.einsum("nqtk,ndk->nqtd", repr_factor, delta) + distance = change.double().square().sum((1, 2, 3)) + return le, lr, distance + + +@torch.no_grad() +def evaluate_weights(model, layer, tasks, weights): + result = [] + # One run at a time keeps evaluation memory bounded for the 8-layer model. + for task, w in zip(tasks, weights, strict=True): + suffix = Suffix(model, layer, task.tokens, task.positions) + logits = suffix(w[None])[0] + parent_logits = suffix(model.blocks[layer].mlp.down.weight[None])[0] + pred = logits.argmax(-1) + old_pred = parent_logits.argmax(-1) + correct = pred.eq(task.labels).all(-1) + old_correct = old_pred.eq(task.old_labels).all(-1) + if task.labels.shape[1] == 2: + # EOS must be generated after the model's own answer, not the target. + tokens = task.tokens.clone() + lengths = task.positions[:, 0] + 1 + tokens[torch.arange(len(tokens), device=tokens.device), lengths] = pred[:, 0] + generated = Suffix(model, layer, tokens, lengths[:, None])(w[None])[0, :, 0].argmax(-1) + tokens[torch.arange(len(tokens), device=tokens.device), lengths] = old_pred[:, 0] + old_generated = Suffix(model, layer, tokens, lengths[:, None])( + model.blocks[layer].mlp.down.weight[None] + )[0, :, 0].argmax(-1) + correct = pred[:, 0].eq(task.labels[:, 0]) & generated.eq(3) + old_correct = old_pred[:, 0].eq(task.old_labels[:, 0]) & old_generated.eq(3) + nll = -logits.log_softmax(-1).gather(-1, task.labels[..., None])[..., 0].mean(-1) + row = {"sets": {}, "prediction": pred[:, 0].cpu().tolist()} + for key, ids in task.sets.items(): + indices = torch.tensor(ids, device=w.device, dtype=torch.long) + known = old_correct[indices] + row["sets"][key] = { + "n": len(ids), + "correct": int(correct[indices].sum()), + "old_known": int(known.sum()), + "broken": int((known & ~correct[indices]).sum()), + "nll": float(nll[indices].mean()) if ids else None, + } + e, local, u = (row["sets"][x] for x in ("E", "local", "U")) + row["joint"] = e["correct"] == e["n"] and local["broken"] == 0 and u["broken"] == 0 + row["e_joint"] = e["correct"] == e["n"] + pair = task.metadata.get("pair", task.sets["E"][:2]) + a, b, c = (task.metadata[x] for x in ("a", "b", "c")) + row["margins"] = { + "ab": (logits[pair, 0, a] - logits[pair, 0, b]).cpu().tolist(), + "ac": (logits[pair, 0, a] - logits[pair, 0, c]).cpu().tolist(), + "bc": (logits[pair, 0, b] - logits[pair, 0, c]).cpu().tolist(), + } + result.append(row) + return result + + +def edit_batch(model, layer, tasks, arm, configs, steps, directory, evaluate=True): + """Each batch member is an independent run; no cross-run loss/normalization.""" + directory = Path(directory) + if (directory / "complete.json").exists(): + return json.loads((directory / "metrics.json").read_text()) + directory.mkdir(parents=True, exist_ok=True) + obj, form, solver = arm.split("-") + setup = batch_setup(model, layer, tasks, configs) + suffix, labels, ew, rw, ref, cov, null, ranks, spectrum, w0 = setup + device = w0.device + n = len(tasks) + w = w0[None].expand(n, -1, -1).clone().requires_grad_() + m, v = torch.zeros_like(w), torch.zeros_like(w) + lr = torch.tensor([c["lr"] for c in configs], device=device) + level = torch.tensor([c["level"] for c in configs], device=device) + damping = configs[0]["damping"] + rank, refresh = configs[0]["rank"], configs[0]["refresh"] + strict = (level == 0) & (form == "hard") & (obj == "repr") + age = torch.zeros(n, device=device, dtype=torch.long) + failed = torch.zeros_like(age) + active = torch.ones(n, device=device, dtype=torch.bool) + sketch = None + generator = torch.Generator(device=device).manual_seed(271521) + records = [ + dict(task=t.manifest(), config=c, arm=arm, timeline=[]) + for t, c in zip(tasks, configs, strict=True) + ] + traces, checkpoints = [], {} + pair_columns = torch.tensor( + [[(t.sets["E"] + t.sets["R"]).index(i) for i in t.metadata["pair"]] for t in tasks], + device=device, + ) + answers_a = torch.tensor([t.metadata["a"] for t in tasks], device=device) + answers_b = torch.tensor([t.metadata["b"] for t in tasks], device=device) + rows = torch.arange(n, device=device) + counters = dict( + forward_batches=0, + backward_batches=0, + ggn_vjps=0, + line_search_batches=0, + covariance_eigh=1, + train_examples_per_batch=labels.shape[1], + batch_runs=n, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.monotonic() + limit = 11 * steps + 10 + for attempt in range(limit + 1): + if ( + attempt == 0 + or (attempt in NODES and attempt <= steps) + or not active.any() + or attempt == limit + ): + if device.type == "cuda": + torch.cuda.synchronize(device) + metrics = ( + evaluate_weights(model, layer, tasks, w.detach()) + if evaluate + else [dict() for _ in tasks] + ) + for j, metric in enumerate(metrics): + records[j]["timeline"].append( + dict( + attempt=attempt, + accepted=int(age[j]), + seconds=time.monotonic() - start, + **metric, + ) + ) + checkpoints[str(attempt)] = w.detach().cpu().clone() + if attempt and (not active.any() or attempt == limit): + break + if attempt >= steps and torch.all((age >= steps) | ~active): + break + logits = suffix(w) + le, lretain, distance = quantities( + logits, w, w0, labels, ew, rw, ref, cov, obj, suffix.repr_factor + ) + pair_gradients = None + if attempt in NODES: + pair_margin = torch.stack( + [ + logits[rows, pair_columns[:, i], 0, answers_a] + - logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + pair_gradients = torch.stack( + [ + torch.autograd.grad(pair_margin[:, i].sum(), w, retain_graph=True)[0].detach() + for i in range(2) + ], + 1, + ) + counters["backward_batches"] += 2 + data_loss = le + lretain + objective = data_loss + level * distance if form == "soft" else data_loss + if solver == "gn" and (sketch is None or attempt % refresh == 0 or failed.any()): + weights = ((ew + rw) / labels.shape[2])[..., None].expand_as(labels) + if form == "soft" and obj == "func": + weights = ((ew + (1 + level[:, None]) * rw) / labels.shape[2])[..., None].expand_as( + labels + ) + sketch = gaussian_newton_sketch(logits, w, weights, rank, generator) + if strict.any(): + projected = (sketch.reshape(n, rank, *w0.shape) @ null[:, None]).flatten(2) + sketch = torch.where(strict[:, None, None], projected, sketch) + counters["ggn_vjps"] += rank + g = torch.autograd.grad(objective.sum(), w, retain_graph=form == "hard")[0] + counters["backward_batches"] += 1 + if form == "hard": + a = torch.autograd.grad(distance.sum(), w)[0] + counters["backward_batches"] += 1 + else: + a = None + if solver == "adam": + m_new = 0.9 * m + 0.1 * g + v_new = 0.999 * v + 0.001 * g.square() + t = (age + 1).float()[:, None, None] + raw = -(m_new / (1 - 0.9**t)) / ((v_new / (1 - 0.999**t)).sqrt() + 1e-8) + proposal = lr[:, None, None] * raw + else: + if strict.any(): + g = torch.where(strict[:, None, None], g @ null, g) + if obj == "repr" and form == "soft": + # Exact representation Hessian plus damped sketched data GGN, CG. + def hv(x, sketch=sketch): + flat = x.flatten(1) + return ( + damping * x + + (sketch.transpose(-1, -2) @ (sketch @ flat[..., None]))[ + ..., 0 + ].reshape_as(x) + + 2 * level[:, None, None] * (x @ cov) + ) + + direction = torch.zeros_like(g) + residual, search = -g.clone(), -g.clone() + rr = residual.square().sum((-1, -2)) + for _ in range(16): + hp = hv(search) + alpha = rr / (search * hp).sum((-1, -2)).clamp_min(1e-30) + direction += alpha[:, None, None] * search + residual -= alpha[:, None, None] * hp + new_rr = residual.square().sum((-1, -2)) + search = residual + (new_rr / rr.clamp_min(1e-30))[:, None, None] * search + rr = new_rr + proposal = lr[:, None, None] * direction + else: + proposal = -lr[:, None, None] * inverse_sketch(g, sketch, damping) + # Fixed Euclidean trust radius, no hidden per-run gradient scaling. + radius = configs[0]["trust_fraction"] * w0.norm() + proposal *= (radius / proposal.flatten(1).norm(dim=1).clamp_min(1e-12)).clamp(max=1)[ + :, None, None + ] + m_new, v_new = m, v + if form == "hard": + if strict.any(): + proposal = torch.where(strict[:, None, None], proposal @ null, proposal) + metric_a = a if solver == "adam" else inverse_sketch(a, sketch, damping) + # Sequential quadratic subproblem with a linearized ORIGINAL distance. + # Interior restoration avoids accumulating positive second-order drift. + slack = torch.where(distance > 0.8 * level, -0.05 * level, 0.8 * (level - distance)) + excess = (a * proposal).sum((-1, -2)) - slack + correction = excess.clamp_min(0) / (a * metric_a).sum((-1, -2)).clamp_min(1e-20) + adjusted = proposal - correction[:, None, None] * metric_a + proposal = torch.where(strict[:, None, None], proposal, adjusted).to(w.dtype) + proposal = torch.where(active[:, None, None], proposal, torch.zeros_like(proposal)) + accepted = torch.zeros_like(active) + chosen = w.detach().clone() + chosen_logits = logits.detach().clone() + picked_scale = torch.zeros(n, device=device) + actual_d = distance.detach().clone() + for backtrack in range(10): + with torch.no_grad(): + candidate = w.detach() + (0.5**backtrack) * proposal + if strict.any(): + exact = w0 + (candidate - w0) @ null + candidate = torch.where(strict[:, None, None], exact, candidate) + candidate_logits = suffix(candidate) + cle, clr, cd = quantities( + candidate_logits, + candidate, + w0, + labels, + ew, + rw, + ref, + cov, + obj, + suffix.repr_factor, + ) + co = cle + clr + level * cd if form == "soft" else cle + clr + tolerance = torch.where(strict, torch.full_like(level, 1e-10), 1e-8 + 1e-5 * level) + feasible = torch.ones_like(active) if form == "soft" else cd <= level + tolerance + descent = co <= objective.detach() + 1e-7 if solver == "gn" else torch.isfinite(co) + if form == "hard" and solver == "gn": + restoration = ( + (distance.detach() > 0.8 * level) + & (cd < distance.detach() - 1e-4 * level) + & (co <= 1.05 * objective.detach() + 1e-6) + & ~strict + ) + descent = descent | restoration + good = feasible & descent & active & ~accepted & torch.isfinite(co) + chosen[good] = candidate[good] + chosen_logits[good] = candidate_logits[good] + actual_d[good] = cd[good] + picked_scale[good] = 0.5**backtrack + accepted |= good + counters["line_search_batches"] += 1 + if torch.all(accepted | ~active): + break + delta = chosen - w.detach() + if pair_gradients is not None: + predicted = (pair_gradients * delta[:, None]).sum((-1, -2)) + updated_margin = torch.stack( + [ + chosen_logits[rows, pair_columns[:, i], 0, answers_a] + - chosen_logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + observed = updated_margin - pair_margin.detach() + flat = pair_gradients.flatten(2) + kernel = flat @ flat.transpose(-1, -2) + for j in range(n): + records[j]["timeline"][-1]["local_step"] = { + "kernel": kernel[j].cpu().tolist(), + "predicted_margin_change": predicted[j].cpu().tolist(), + "observed_margin_change": observed[j].cpu().tolist(), + "actual_delta_norm": float(delta[j].norm()), + } + + with torch.no_grad(): + w.copy_(chosen) + m.copy_(torch.where(accepted[:, None, None], m_new, m)) + v.copy_(torch.where(accepted[:, None, None], v_new, v)) + age += accepted + failed = torch.where(accepted, torch.zeros_like(failed), failed + 1) + active = (age < steps) & (failed < 10) + traces.append( + torch.stack( + ( + le.detach(), + lretain.detach(), + distance.detach(), + actual_d, + delta.flatten(1).norm(dim=1), + picked_scale, + accepted.float(), + age.float(), + ), + -1, + ).cpu() + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start + counters["forward_batches"] = suffix.forward_calls + counters["elapsed_seconds_including_evaluation"] = elapsed + for j, record in enumerate(records): + record.update( + accepted=int(age[j]), + failed=bool(failed[j] >= 10), + elapsed_batch_seconds=elapsed, + representation_rank=int(ranks[j]), + representation_spectrum=spectrum[j].cpu().tolist(), + ) + write_json(directory / "metrics.json", records) + torch.save( + dict( + weights=w.detach().cpu(), + parent=w0.cpu(), + checkpoints=checkpoints, + m=m.cpu(), + v=v.cpu(), + age=age.cpu(), + sketch=None if sketch is None else sketch.cpu(), + generator_state=generator.get_state(), + arm=arm, + configs=configs, + ), + directory / "state.pt", + ) + np.savez_compressed( + directory / "steps.npz", + values=torch.stack(traces).numpy(), + columns=np.array( + [ + "E_CE", + "R_CE", + "distance_before", + "distance_after", + "delta_norm", + "backtrack_scale", + "accepted", + "accepted_count", + ] + ), + ) + write_json(directory / "cost.json", counters) + write_json( + directory / "complete.json", + dict( + files={ + name: digest(directory / name) + for name in ("metrics.json", "state.pt", "steps.npz", "cost.json") + } + ), + ) + return records diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_direction_cross.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_direction_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..27051c00db64d66676d95dc16a1351dff5d797a6 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_direction_cross.py @@ -0,0 +1,149 @@ +"""Target-complete edits on the original two-chain, eight-layer task.""" + +import numpy as np +import torch + +from .bios_cross import edit_pair, make_cross_world +from .bios_cross_train import tensor_queries +from .bios_direction import ROOT, Task, stable_order + +CROSS_ARMS = ("func-soft-adam", "repr-hard-adam", "func-hard-gn", "func-soft-gn") + + +def cross_tasks(world_id, seed, device): + world = make_cross_world(world_id, ROOT / "data/bios-organization-v1") + tasks = [] + for chain in (0, 1): + edits = edit_pair(world, chain) + for group_index, group in enumerate(edits["groups"]): + members = np.flatnonzero(world.memberships[chain] == group) + eligible = [ + int(p) + for p in members + if not world.exceptions[chain, p] + and world.derived_ids[chain, p] in world.heldout_ids[chain] + ] + person = stable_order(eligible, "focal", world_id, chain, int(group))[0] + root, actual = int(world.root_ids[chain, group]), int(world.actual_ids[chain, person]) + c = int(world.answers[root]) + a = int( + world.city_tokens[world.defaults[chain, edits["groups"][(group_index + 1) % 3]]] + ) + b = int( + world.city_tokens[world.defaults[chain, edits["groups"][(group_index + 2) % 3]]] + ) + assert len({a, b, c}) == 3 and int(world.answers[actual]) == c + e = [root, actual] + d = world.derived_ids[chain, members].tolist() + focal = int(world.derived_ids[chain, person]) + assert focal in world.heldout_ids[chain] + membership = int(world.membership_ids[chain, person]) + local = np.flatnonzero( + (world.person == person) & (np.arange(len(world.answers)) < world.n_base) + ).tolist() + local = [i for i in local if i not in e + [membership]] + # Near facts exclude all direct edits and all affected compositions. + near_pool = list( + set( + world.actual_ids[chain, members].tolist() + + world.membership_ids[chain, members].tolist() + ) + - set(e + [membership] + local) + ) + near = stable_order(near_pool, "near", world_id, chain, int(group))[:48] + reserved = set(e + d + local + near + [membership]) + base_pool = stable_order( + [i for i in range(world.n_base) if i not in reserved], + "base", + world_id, + chain, + int(group), + ) + r = [membership] + base_pool[:47] + v = base_pool[47:95] + far_base = base_pool[95:175] + other_d = stable_order( + [int(i) for i in world.heldout_ids.flatten() if i not in reserved], + "far-d", + world_id, + chain, + int(group), + )[:16] + far = far_base + other_d + u = local + near + far + included = e + r + v + u + d + assert len(included) == len(set(included)) + mapping = {old: new for new, old in enumerate(included)} + sets = { + "E": e, + "R": r, + "V": v, + "U": u, + "local": local, + "U_near": near, + "U_far": far, + "D": d, + "D_heldout": [i for i in d if i in world.heldout_ids[chain]], + "D_focal": [focal], + } + for kind in ("coherent", "independent"): + truth = world.answers.copy() + truth[root], truth[actual], truth[d] = a, a if kind == "coherent" else b, a + assert set(np.flatnonzero(truth != world.answers)) == set(e + d) + data = tensor_queries(world, device, truth) + old = torch.stack( + [ + torch.as_tensor(world.answers[included], device=device), + torch.full((len(included),), 3, device=device), + ], + -1, + ) + tasks.append( + Task( + f"world-{world_id}-seed-{seed}-chain-{chain}-group-{int(group)}-{kind}", + data["tokens"][included], + data["positions"][included], + data["labels"][included], + old, + {k: [mapping[i] for i in ids] for k, ids in sets.items()}, + dict( + world=world_id, + seed=seed, + chain=chain, + group=int(group), + group_index=group_index, + person=person, + kind=kind, + a=a, + b=b, + c=c, + pair=[mapping[actual], mapping[root]], + original_ids=included, + ), + ) + ) + return tasks + + +def bounded_representation_geometry(suffix, rmask, w0): + """Same FP64 covariance as the core; avoid a huge four-axis outer product.""" + z = suffix.z + mask = rmask[..., None].expand(-1, -1, z.shape[2]) + valid = ( + torch.arange(z.shape[2], device=z.device)[None, None, :] + <= suffix.positions.max(-1).values[..., None] + ) + mask = mask * valid + flat = z.double().flatten(1, 2) + covariance = flat.transpose(-1, -2) @ (flat * mask.flatten(1)[..., None]) + covariance = covariance / mask.sum((1, 2))[:, None, None] + output = torch.einsum("nqtk,dk->nqtd", z, w0) + suffix.model.blocks[suffix.layer].mlp.down.bias + scale = (output.square().sum(-1) * mask).sum((1, 2)) / mask.sum((1, 2)) + covariance = covariance / scale[:, None, None].clamp_min(1e-12) + suffix.repr_factor = ( + z * (mask / (mask.sum((1, 2)) * scale).clamp_min(1e-12)[:, None, None]).sqrt()[..., None] + ) + vals, vecs = torch.linalg.eigh(covariance) + keep = vals > vals[:, -1:] * 1e-10 + null = (vecs * (~keep)[:, None, :]) @ vecs.transpose(-1, -2) + return covariance.to(w0.dtype), null.to(w0.dtype), keep.sum(-1), vals diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_direction_formation.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_direction_formation.py new file mode 100644 index 0000000000000000000000000000000000000000..96a3aa141c344b0fea47995c861792eb5d95398a --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_direction_formation.py @@ -0,0 +1,241 @@ +"""Prospective learning-rate interventions and factor measurements on new worlds.""" + +import copy +import json +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_direction import ROOT, digest, edit_batch, minimal_task +from .bios_direction_cross import CROSS_ARMS +from .bios_model import CausalLM, ModelConfig + +TRAIN_NODES = (0, 8, 32, 128, 256, 512, 1024) +TRAIN_ARMS = ("baseline", "qk-0.25", "qk-4", "up-0.25", "up-4", "post-0.25", "post-4") + + +def world_labels(world): + rng = np.random.default_rng(np.random.SeedSequence([271523, world])) + r1 = np.r_[ + np.arange(3), rng.permutation(np.r_[np.repeat(0, 10), np.repeat(1, 10), np.repeat(2, 9)]) + ] + exceptions = np.concatenate( + [ + rng.choice(np.flatnonzero((r1 == v) & (np.arange(32) >= 3)), n, replace=False) + for v, n in enumerate((3, 3, 2)) + ] + ) + r2 = r1.copy() + r2[exceptions] = np.roll(r1[exceptions], -3) + r3 = rng.permutation(np.arange(32) % 3) + labels = np.stack((r1, r2, r3), -1) + assert (r1 == r2).sum() == 24 and np.all(r1[:3] == r2[:3]) + for col in labels.T: + assert np.ptp(np.bincount(col, minlength=3)) <= 1 + return torch.tensor(labels.flatten() + 38, dtype=torch.long) + + +def optimizer_views(model): + """Separate Q/K and V learning rates without changing forward computation. + + Optimizer leaf views share parameter storage; their gradients are assigned + from the original model's autograd gradients. A frozen view gets grad=None, + so its optimizer moments and step count genuinely stop. + """ + groups = {k: [] for k in ("qk", "up", "post", "other")} + mapping = [] + for name, p in model.named_parameters(): + if name.startswith("blocks.0.attention.qkv."): + pieces = [("qk", slice(0, 128)), ("other", slice(128, None))] + else: + group = ( + "up" + if name.startswith("blocks.0.mlp.up.") + else ("post" if name.startswith("blocks.1.") else "other") + ) + pieces = [(group, slice(None))] + for group, region in pieces: + view = nn.Parameter(p.detach()[region]) + groups[group].append(view) + mapping.append((group, p, region, view)) + optimizer = torch.optim.AdamW( + [dict(params=params, lr=0.001, name=name) for name, params in groups.items()], + weight_decay=0.1, + foreach=True, + ) + return optimizer, mapping + + +def multiplier(arm, step): + if arm == "baseline": + return None, 1.0 + group, mode = arm.split("-") + if mode == "freezeearly": + return group, 0.0 if step < 256 else 1.0 + if mode == "freezelate": + return group, 0.0 if step >= 768 else 1.0 + if mode == "freezeall": + return group, 0.0 + return group, float(mode) if step < 256 else 1.0 + + +def factor_measure(model, seed, labels, device): + records = [] + for person in (0, 1, 2): + task = minimal_task(seed, person, "independent", device, labels) + ids = task.metadata["pair"] + captured = {} + + def capture(module, inputs, output, captured=captured): + captured.update(z=inputs[0], h=output) + + handle = model.blocks[0].mlp.down.register_forward_hook(capture) + tokens = task.tokens[ids] + logits = model(tokens)[:, -1] + handle.remove() + a, b, c = (task.metadata[x] for x in ("a", "b", "c")) + margin = logits[:, a] - logits[:, b] + gradients = [] + deltas = [] + for i in range(2): + g, d = torch.autograd.grad( + margin[i], (model.blocks[0].mlp.down.weight, captured["h"]), retain_graph=True + ) + gradients.append(g.detach()) + deltas.append(d[i].detach()) + g = torch.stack(gradients).flatten(1) + kernel = g @ g.T + z = captured["z"].detach() + d = torch.stack(deltas) + rebuilt = torch.einsum("itd,itk->idk", d, z).flatten(1) + error = (rebuilt - g).norm() / g.norm().clamp_min(1e-20) + common = float((kernel[0, 0] + kernel[1, 1] + 2 * kernel[0, 1]) / 2) + difference = float((kernel[0, 0] + kernel[1, 1] - 2 * kernel[0, 1]) / 2) + # Actual GELU slope at the preactivation, not a binary activation mask. + pre = model.blocks[0].mlp.up + activations = {} + + def pre_hook(module, inputs, output, activations=activations): + activations.update(input=inputs[0], pre=output) + + handle = pre.register_forward_hook(pre_hook) + model(tokens) + handle.remove() + y = activations["pre"] + gate = torch.autograd.grad(model.blocks[0].mlp.activation(y).sum(), y)[0].detach() + + def cosine(x): + return float(F.cosine_similarity(x[0].flatten(), x[1].flatten(), dim=0)) + + records.append( + dict( + person=person, + common=common, + difference=difference, + ratio=difference / max(common, 1e-20), + mixing=float((kernel[0, 0] - kernel[1, 1]) / 2), + eigenvalues=torch.linalg.eigvalsh(kernel.double()).tolist(), + feature_cos=cosine(z), + downstream_cos=cosine(d), + gate_cos=cosine(gate), + relation_input_difference=float( + (activations["input"][0] - activations["input"][1]).detach().norm() + ), + feature_difference=float((z[0] - z[1]).norm()), + gate_difference=float((gate[0] - gate[1]).norm()), + reconstruction_error=float(error), + new_target_nll=float(F.cross_entropy(logits, task.labels[ids, 0]).detach()), + margin_ab=margin.detach().tolist(), + kernel=kernel.detach().cpu().tolist(), + ) + ) + return records + + +def train(world, seed, arm, device, out): + out = Path(out) + if (out / "complete.json").exists(): + return + out.mkdir(parents=True, exist_ok=True) + labels = world_labels(world).to(device) + torch.manual_seed(seed) + model = CausalLM(ModelConfig(41, width=64, layers=2, heads=2, context=8)).to(device) + tokens = minimal_task(seed, 0, "independent", device, labels).tokens + opt, mapping = optimizer_views(model) + timeline = [] + for step in range(1025): + if step in TRAIN_NODES: + with torch.no_grad(): + logits = model(tokens)[:, -1] + acc = float(logits.argmax(-1).eq(labels).float().mean()) + loss = float(F.cross_entropy(logits, labels)) + factors = factor_measure(model, seed, labels, device) + timeline.append(dict(step=step, accuracy=acc, loss=loss, factors=factors)) + torch.save( + dict( + model={k: v.detach().cpu() for k, v in model.state_dict().items()}, + config=model.config_dict(), + optimizer=opt.state_dict(), + step=step, + world=world, + seed=seed, + arm=arm, + labels=labels.cpu(), + ), + out / f"model-{step}.pt", + ) + if step == 1024: + break + model.zero_grad(set_to_none=True) + opt.zero_grad(set_to_none=True) + loss = F.cross_entropy(model(tokens)[:, -1], labels) + loss.backward() + selected, factor = multiplier(arm, step) + for group in opt.param_groups: + group["lr"] = 0.001 * (factor if group["name"] == selected else 1.0) + for group, p, region, view in mapping: + view.grad = None if group == selected and factor == 0 else p.grad[region] + opt.step() + write_json(out / "learning.json", timeline) + write_json( + out / "complete.json", + dict( + world=world, + seed=seed, + arm=arm, + files={p.name: digest(p) for p in out.iterdir() if p.suffix in (".json", ".pt")}, + ), + ) + + +def edit_parent(world, seed, train_arm, device, out, edit_arms=CROSS_ARMS, steps=1024): + from .bios_direction import load_parent + + out = Path(out) + saved = torch.load(out / "model-1024.pt", map_location="cpu", weights_only=False) + labels = saved["labels"].to(device) + model = load_parent(out / "model-1024.pt", device) + selected = json.loads( + (ROOT / "docs/development-artifacts/direction-v1/selected.json").read_text() + )["choices"] + tasks = [ + minimal_task(seed, p, k, device, labels) + for p in (0, 1, 2) + for k in ("coherent", "independent") + ] + for task in tasks: + task.metadata.update(world=world, train_arm=train_arm) + for arm in edit_arms: + edit_batch( + model, + 0, + tasks, + arm, + [copy.deepcopy(selected[arm]) for _ in tasks], + steps, + out / "edits" / arm, + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_direction_refresh.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_direction_refresh.py new file mode 100644 index 0000000000000000000000000000000000000000..5f48462e2c66886ef8e483fa7e48986d075ad3fb --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_direction_refresh.py @@ -0,0 +1,355 @@ +"""V1 numerical audit: refresh curvature per trajectory and freeze idle counters. + +This keeps the original randomized batched probe stream, finite objectives, +constraints and solver settings. Unused fresh probe rows are discarded rather +than changing another trajectory's sketch. Frozen v1 artifacts are untouched. +""" + +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_data import write_json +from .bios_direction import ( + NODES, + batch_setup, + digest, + evaluate_weights, + gaussian_newton_sketch, + inverse_sketch, + quantities, +) + + +def refresh_mask(active, failed, attempt, refresh, missing): + due = missing or attempt % refresh == 0 + return active & (torch.full_like(active, due) | (failed > 0)) + + +def update_failure_counts(active, accepted, failed): + return torch.where(active, torch.where(accepted, torch.zeros_like(failed), failed + 1), failed) + + +def edit_batch(model, layer, tasks, arm, configs, steps, directory, evaluate=True): + """Each batch member is an independent run; no cross-run loss/normalization.""" + directory = Path(directory) + if (directory / "complete.json").exists(): + return json.loads((directory / "metrics.json").read_text()) + directory.mkdir(parents=True, exist_ok=True) + obj, form, solver = arm.split("-") + setup = batch_setup(model, layer, tasks, configs) + suffix, labels, ew, rw, ref, cov, null, ranks, spectrum, w0 = setup + device = w0.device + n = len(tasks) + w = w0[None].expand(n, -1, -1).clone().requires_grad_() + m, v = torch.zeros_like(w), torch.zeros_like(w) + lr = torch.tensor([c["lr"] for c in configs], device=device) + level = torch.tensor([c["level"] for c in configs], device=device) + damping = configs[0]["damping"] + rank, refresh = configs[0]["rank"], configs[0]["refresh"] + strict = (level == 0) & (form == "hard") & (obj == "repr") + age = torch.zeros(n, device=device, dtype=torch.long) + failed = torch.zeros_like(age) + active = torch.ones(n, device=device, dtype=torch.bool) + sketch = None + generator = torch.Generator(device=device).manual_seed(271521) + records = [ + dict(task=t.manifest(), config=c, arm=arm, timeline=[]) + for t, c in zip(tasks, configs, strict=True) + ] + traces, checkpoints = [], {} + pair_columns = torch.tensor( + [[(t.sets["E"] + t.sets["R"]).index(i) for i in t.metadata["pair"]] for t in tasks], + device=device, + ) + answers_a = torch.tensor([t.metadata["a"] for t in tasks], device=device) + answers_b = torch.tensor([t.metadata["b"] for t in tasks], device=device) + rows = torch.arange(n, device=device) + counters = dict( + forward_batches=0, + backward_batches=0, + ggn_vjps=0, + line_search_batches=0, + covariance_eigh=1, + train_examples_per_batch=labels.shape[1], + batch_runs=n, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.monotonic() + limit = 11 * steps + 10 + for attempt in range(limit + 1): + if ( + attempt == 0 + or (attempt in NODES and attempt <= steps) + or not active.any() + or attempt == limit + ): + if device.type == "cuda": + torch.cuda.synchronize(device) + metrics = ( + evaluate_weights(model, layer, tasks, w.detach()) + if evaluate + else [dict() for _ in tasks] + ) + for j, metric in enumerate(metrics): + records[j]["timeline"].append( + dict( + attempt=attempt, + accepted=int(age[j]), + seconds=time.monotonic() - start, + **metric, + ) + ) + checkpoints[str(attempt)] = w.detach().cpu().clone() + if attempt and (not active.any() or attempt == limit): + break + if attempt >= steps and torch.all((age >= steps) | ~active): + break + logits = suffix(w) + le, lretain, distance = quantities( + logits, w, w0, labels, ew, rw, ref, cov, obj, suffix.repr_factor + ) + pair_gradients = None + if attempt in NODES: + pair_margin = torch.stack( + [ + logits[rows, pair_columns[:, i], 0, answers_a] + - logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + pair_gradients = torch.stack( + [ + torch.autograd.grad(pair_margin[:, i].sum(), w, retain_graph=True)[0].detach() + for i in range(2) + ], + 1, + ) + counters["backward_batches"] += 2 + data_loss = le + lretain + objective = data_loss + level * distance if form == "soft" else data_loss + refresh_rows = refresh_mask(active, failed, attempt, refresh, sketch is None) + if solver == "gn" and refresh_rows.any(): + weights = ((ew + rw) / labels.shape[2])[..., None].expand_as(labels) + if form == "soft" and obj == "func": + weights = ((ew + (1 + level[:, None]) * rw) / labels.shape[2])[..., None].expand_as( + labels + ) + fresh = gaussian_newton_sketch(logits, w, weights, rank, generator) + if strict.any(): + projected = (fresh.reshape(n, rank, *w0.shape) @ null[:, None]).flatten(2) + fresh = torch.where(strict[:, None, None], projected, fresh) + sketch = ( + fresh if sketch is None else torch.where(refresh_rows[:, None, None], fresh, sketch) + ) + counters["ggn_vjps"] += rank + g = torch.autograd.grad(objective.sum(), w, retain_graph=form == "hard")[0] + counters["backward_batches"] += 1 + if form == "hard": + a = torch.autograd.grad(distance.sum(), w)[0] + counters["backward_batches"] += 1 + else: + a = None + if solver == "adam": + m_new = 0.9 * m + 0.1 * g + v_new = 0.999 * v + 0.001 * g.square() + t = (age + 1).float()[:, None, None] + raw = -(m_new / (1 - 0.9**t)) / ((v_new / (1 - 0.999**t)).sqrt() + 1e-8) + proposal = lr[:, None, None] * raw + else: + if strict.any(): + g = torch.where(strict[:, None, None], g @ null, g) + if obj == "repr" and form == "soft": + # Exact representation Hessian plus damped sketched data GGN, CG. + def hv(x, sketch=sketch): + flat = x.flatten(1) + return ( + damping * x + + (sketch.transpose(-1, -2) @ (sketch @ flat[..., None]))[ + ..., 0 + ].reshape_as(x) + + 2 * level[:, None, None] * (x @ cov) + ) + + direction = torch.zeros_like(g) + residual, search = -g.clone(), -g.clone() + rr = residual.square().sum((-1, -2)) + for _ in range(16): + hp = hv(search) + alpha = rr / (search * hp).sum((-1, -2)).clamp_min(1e-30) + direction += alpha[:, None, None] * search + residual -= alpha[:, None, None] * hp + new_rr = residual.square().sum((-1, -2)) + search = residual + (new_rr / rr.clamp_min(1e-30))[:, None, None] * search + rr = new_rr + proposal = lr[:, None, None] * direction + else: + proposal = -lr[:, None, None] * inverse_sketch(g, sketch, damping) + # Fixed Euclidean trust radius, no hidden per-run gradient scaling. + radius = configs[0]["trust_fraction"] * w0.norm() + proposal *= (radius / proposal.flatten(1).norm(dim=1).clamp_min(1e-12)).clamp(max=1)[ + :, None, None + ] + m_new, v_new = m, v + if form == "hard": + if strict.any(): + proposal = torch.where(strict[:, None, None], proposal @ null, proposal) + metric_a = a if solver == "adam" else inverse_sketch(a, sketch, damping) + # Sequential quadratic subproblem with a linearized ORIGINAL distance. + # Interior restoration avoids accumulating positive second-order drift. + slack = torch.where(distance > 0.8 * level, -0.05 * level, 0.8 * (level - distance)) + excess = (a * proposal).sum((-1, -2)) - slack + correction = excess.clamp_min(0) / (a * metric_a).sum((-1, -2)).clamp_min(1e-20) + adjusted = proposal - correction[:, None, None] * metric_a + proposal = torch.where(strict[:, None, None], proposal, adjusted).to(w.dtype) + proposal = torch.where(active[:, None, None], proposal, torch.zeros_like(proposal)) + accepted = torch.zeros_like(active) + chosen = w.detach().clone() + chosen_logits = logits.detach().clone() + picked_scale = torch.zeros(n, device=device) + actual_d = distance.detach().clone() + for backtrack in range(10): + with torch.no_grad(): + candidate = w.detach() + (0.5**backtrack) * proposal + if strict.any(): + exact = w0 + (candidate - w0) @ null + candidate = torch.where(strict[:, None, None], exact, candidate) + candidate_logits = suffix(candidate) + cle, clr, cd = quantities( + candidate_logits, + candidate, + w0, + labels, + ew, + rw, + ref, + cov, + obj, + suffix.repr_factor, + ) + co = cle + clr + level * cd if form == "soft" else cle + clr + tolerance = torch.where(strict, torch.full_like(level, 1e-10), 1e-8 + 1e-5 * level) + feasible = torch.ones_like(active) if form == "soft" else cd <= level + tolerance + descent = co <= objective.detach() + 1e-7 if solver == "gn" else torch.isfinite(co) + if form == "hard" and solver == "gn": + restoration = ( + (distance.detach() > 0.8 * level) + & (cd < distance.detach() - 1e-4 * level) + & (co <= 1.05 * objective.detach() + 1e-6) + & ~strict + ) + descent = descent | restoration + good = feasible & descent & active & ~accepted & torch.isfinite(co) + chosen[good] = candidate[good] + chosen_logits[good] = candidate_logits[good] + actual_d[good] = cd[good] + picked_scale[good] = 0.5**backtrack + accepted |= good + counters["line_search_batches"] += 1 + if torch.all(accepted | ~active): + break + delta = chosen - w.detach() + if pair_gradients is not None: + predicted = (pair_gradients * delta[:, None]).sum((-1, -2)) + updated_margin = torch.stack( + [ + chosen_logits[rows, pair_columns[:, i], 0, answers_a] + - chosen_logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + observed = updated_margin - pair_margin.detach() + flat = pair_gradients.flatten(2) + kernel = flat @ flat.transpose(-1, -2) + for j in range(n): + records[j]["timeline"][-1]["local_step"] = { + "kernel": kernel[j].cpu().tolist(), + "predicted_margin_change": predicted[j].cpu().tolist(), + "observed_margin_change": observed[j].cpu().tolist(), + "actual_delta_norm": float(delta[j].norm()), + } + + with torch.no_grad(): + w.copy_(chosen) + m.copy_(torch.where(accepted[:, None, None], m_new, m)) + v.copy_(torch.where(accepted[:, None, None], v_new, v)) + age += accepted + failed = update_failure_counts(active, accepted, failed) + active = (age < steps) & (failed < 10) + traces.append( + torch.stack( + ( + le.detach(), + lretain.detach(), + distance.detach(), + actual_d, + delta.flatten(1).norm(dim=1), + picked_scale, + accepted.float(), + age.float(), + ), + -1, + ).cpu() + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start + counters["forward_batches"] = suffix.forward_calls + counters["elapsed_seconds_including_evaluation"] = elapsed + for j, record in enumerate(records): + record.update( + accepted=int(age[j]), + failed=bool(failed[j] >= 10 and age[j] < steps), + elapsed_batch_seconds=elapsed, + representation_rank=int(ranks[j]), + representation_spectrum=spectrum[j].cpu().tolist(), + ) + write_json(directory / "metrics.json", records) + torch.save( + dict( + weights=w.detach().cpu(), + parent=w0.cpu(), + checkpoints=checkpoints, + m=m.cpu(), + v=v.cpu(), + age=age.cpu(), + sketch=None if sketch is None else sketch.cpu(), + generator_state=generator.get_state(), + arm=arm, + configs=configs, + ), + directory / "state.pt", + ) + np.savez_compressed( + directory / "steps.npz", + values=torch.stack(traces).numpy(), + columns=np.array( + [ + "E_CE", + "R_CE", + "distance_before", + "distance_after", + "delta_norm", + "backtrack_scale", + "accepted", + "accepted_count", + ] + ), + ) + write_json(directory / "cost.json", counters) + write_json( + directory / "complete.json", + dict( + files={ + name: digest(directory / name) + for name in ("metrics.json", "state.pt", "steps.npz", "cost.json") + } + ), + ) + return records diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_edit.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..685a33d6157d090f0afdfaa38b5c2d731eda4d0e --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_edit.py @@ -0,0 +1,381 @@ +"""Fixed-budget development edits with held-out retention and full-answer scoring.""" + +import argparse +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_branch import attach_branch, build_bases, remove_branch +from .bios_data import N_BASE, N_QUERIES, load_world, paired_edit, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_train import code_fingerprint, evaluate, precision, tensor_data + +EDIT_CHECKPOINTS = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512) + + +def score_edit(world, pair, target, arrays, old_correct): + correct = arrays["correct"] + e, d = pair["E"], pair["D"] + root = e[world.relation[e] == 1] + members = e[world.relation[e] == 2] + unseen = np.zeros(N_QUERIES, dtype=bool) + unseen[pair["heldout"]] = True + retention, full_retention = {}, {} + for g in range(4): + ids = (pair["strata"] == g) & old_correct + full_retention[str(g)] = { + "known": int(ids.sum()), + "broken": int((ids & ~correct).sum()), + "rate": float((~correct[ids]).mean()) if ids.any() else None, + } + held = ids & unseen + retention[str(g)] = { + "known": int(held.sum()), + "broken": int((held & ~correct).sum()), + "rate": float((~correct[held]).mean()) if held.any() else None, + } + for name, base in (("2_base", True), ("2_derived", False)): + ids = ( + (pair["strata"] == 2) & old_correct & unseen & ((np.arange(N_QUERIES) < N_BASE) == base) + ) + retention[name] = { + "known": int(ids.sum()), + "broken": int((ids & ~correct).sum()), + "rate": float((~correct[ids]).mean()) if ids.any() else None, + } + rates = [v["rate"] for v in retention.values()] + root_acc, member_acc, d_acc = (float(correct[ids].mean()) for ids in (root, members, d)) + joint = ( + None + if any(rate is None for rate in rates) + else bool( + root_acc == 1 + and member_acc >= 0.95 + and d_acc >= 0.95 + and all(rate <= 0.01 for rate in rates) + ) + ) + return { + "E": float(correct[e].mean()), + "E_root": root_acc, + "E_member": member_acc, + "D": d_acc, + "U_accuracy": float(correct[pair["strata"] >= 0].mean()), + "U_heldout_destruction": retention, + "U_full_destruction": full_retention, + "joint_pass": joint, + "E_target_value_nll": float(arrays["value_nll"][e].mean()), + } + + +def reference_logits(model, data, ids, device): + result = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(ids), 256): + subset = torch.as_tensor(ids[begin : begin + 256], device=device) + result.append(model(data["tokens"][subset], data["positions"][subset]).detach()) + return torch.cat(result) + + +@torch.no_grad() +def capture_down(model, tokens, positions, layer): + captured = {} + + def capture(module, inputs, output): + captured.update( + z=inputs[0].float().clone(), + h=output.float().clone(), + weight=module.weight.detach().float().clone(), + ) + + handle = model.blocks[layer].mlp.down.register_forward_hook(capture) + try: + model(tokens, positions) + finally: + handle.remove() + return captured + + +def edit_case( + model, + baseline, + world, + data_old, + pair, + kind, + scope, + args, + old_correct, + branch_kind=None, + basis=None, +): + suffix = "" if branch_kind is None else f"-{branch_kind}-branch" + out = Path(args.output) / f"support-{pair['support']}-{kind}-{scope}{suffix}" + if (out / "complete.json").exists(): + return json.loads((out / "complete.json").read_text()) + out.mkdir(parents=True, exist_ok=True) + device = data_old["tokens"].device + model.load_state_dict(baseline) + selected = select_parameters(model, scope, args.window) + branch, handles, zero_error = None, [], None + if basis is not None: + probe = torch.as_tensor(pair["E"][:32], device=device) + with torch.no_grad(), precision(device): + before = model(data_old["tokens"][probe], data_old["positions"][probe]) + branch, handles = attach_branch(model, basis, layer=args.window + 1) + selected.extend(branch.parameters()) + with torch.no_grad(), precision(device): + after = model(data_old["tokens"][probe], data_old["positions"][probe]) + zero_error = (before - after).abs().max().item() + if zero_error != 0: + raise ValueError("Branch was not function-preserving at initialization") + target = pair[kind] + data_new = tensor_data(world, device, target) + if device.type == "cuda": + torch.cuda.synchronize(device) + setup_start = time.perf_counter() + calibration = None + if scope == "down": + calibration_ids = torch.as_tensor( + np.concatenate([pair["E"][:32], pair["replay"][:32]]), device=device + ) + calibration = capture_down( + model, + data_old["tokens"][calibration_ids], + data_old["positions"][calibration_ids], + args.window + 1, + ) + old_logits = reference_logits(model, data_old, pair["replay"], device) + if device.type == "cuda": + torch.cuda.synchronize(device) + setup_seconds = time.perf_counter() - setup_start + basis_seconds = getattr(args, "branch_preparation_seconds", 0.0) if basis else 0.0 + setup_flops = matmul_flops(model.config, len(pair["replay"]), backward=False) + optimizer = torch.optim.AdamW( + selected, lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + sample_rng = rng_for(world.seed, 41, pair["support"]) + e_choices = sample_rng.integers(0, len(pair["E"]), size=(args.steps, 128)) + r_choices = sample_rng.integers(0, len(pair["replay"]), size=(args.steps, 128)) + timeline, train_seconds = [], 0.0 + case_config = { + "scope": scope, + "branch": branch_kind, + "branch_parameters": sum(p.numel() for p in branch.parameters()) if branch else 0, + "branch_zero_initialization_max_logit_difference": zero_error, + "kind": kind, + "support": pair["support"], + "selection": pair["selection"], + "steps": args.steps, + "lr": args.lr, + "retention_kl_weight": args.retention, + "window_zero_based": list(range(args.window, args.window + 3)), + "trainable_parameters": sum(p.numel() for p in selected), + "setup_seconds": setup_seconds, + "shared_basis_preparation_seconds": basis_seconds, + "preparation_accounting": ( + "Basis construction is executed once per old checkpoint. Standalone cold-start time " + "below charges that entire common construction; do not sum it across reused branches." + ), + "setup_matmul_flops_estimate": setup_flops, + "flops_limitation": ( + "backward dense matmul upper approximation; not exact frozen-scope operation count" + ), + } + write_json(out / "config.json", case_config) + np.savez_compressed( + out / "sets.npz", + E=pair["E"], + D=pair["D"], + strata=pair["strata"], + replay=pair["replay"], + heldout=pair["heldout"], + target=target, + old_correct=old_correct, + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + checkpoints = sorted({s for s in EDIT_CHECKPOINTS if s <= args.steps} | {args.steps}) + for step in range(args.steps + 1): + if step in checkpoints: + eval_start = time.perf_counter() + _, arrays = evaluate(model, data_old, world, answers=target) + metrics = score_edit(world, pair, target, arrays, old_correct) + np.savez_compressed(out / f"predictions-{step}.npz", **arrays) + point = { + "step": step, + **metrics, + "edit_seconds": train_seconds, + "setup_plus_edit_seconds": setup_seconds + train_seconds, + "cold_start_including_basis_seconds": basis_seconds + setup_seconds + train_seconds, + "setup_plus_edit_matmul_flops_estimate": setup_flops + + step * matmul_flops(model.config, 256), + "target_supervised_tokens": step * 256, + "replay_supervised_tokens": step * 256, + "eval_seconds": time.perf_counter() - eval_start, + } + if calibration is not None: + current = capture_down( + model, + data_old["tokens"][calibration_ids], + data_old["positions"][calibration_ids], + args.window + 1, + ) + observed = current["h"] - calibration["h"] + predicted = F.linear(calibration["z"], current["weight"] - calibration["weight"]) + point["down_calibration"] = { + "feature_max_change": (current["z"] - calibration["z"]).abs().max().item(), + "delta_h_max_error": (observed - predicted).abs().max().item(), + "delta_h_rms_error": (observed - predicted).square().mean().sqrt().item(), + "fixed_prefix_tokens": int( + calibration["z"].shape[0] * calibration["z"].shape[1] + ), + } + timeline.append(point) + write_json(out / "trajectory.json", timeline) + print( + json.dumps( + { + "event": "edit", + "case": out.name, + "step": step, + "E": metrics["E"], + "D": metrics["D"], + "joint": metrics["joint_pass"], + } + ), + flush=True, + ) + if step == args.steps: + break + model.train() + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + reference = old_logits[torch.as_tensor(r_choices[step], device=device)].float() + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits_e = model(data_new["tokens"][ei], data_new["positions"][ei]).float() + logits_r = model(data_old["tokens"][ri], data_old["positions"][ri]).float() + ce = F.cross_entropy( + logits_e.reshape(-1, world.vocab_size), data_new["labels"][ei].reshape(-1) + ) + kl = ( + F.kl_div( + F.log_softmax(logits_r, dim=-1), F.softmax(reference, dim=-1), reduction="none" + ) + .sum(-1) + .mean() + ) + loss = ce + args.retention * kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1.0) + if not torch.isfinite(loss) or not torch.isfinite(norm): + write_json(out / "failure.json", {"step": step, "reason": "nonfinite loss or gradient"}) + raise FloatingPointError("Nonfinite edit") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - start + passed = [p for p in timeline if p["joint_pass"] is True] + result = { + **case_config, + "status": "complete", + "final": timeline[-1], + "first_observed_joint_step": passed[0]["step"] if passed else None, + "budget_censored": (not bool(passed) if timeline[-1]["joint_pass"] is not None else None), + "joint_evaluable": timeline[-1]["joint_pass"] is not None, + } + write_json(out / "complete.json", result) + if handles: + remove_branch(model, handles) + return result + + +def run(args): + torch.set_num_threads(args.threads) + torch.manual_seed(0) + device = torch.device(args.device) + world = load_world(args.world) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_data(world, device) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + write_json( + out / "run.json", {**vars(args), "world_step": checkpoint["step"], **code_fingerprint()} + ) + _, old_arrays = evaluate(model, data, world) + bases = None + if args.branches: + bases, operation_checks = build_bases(model, world, data, layer=args.window + 1) + write_json(out / "branch-operation-checks.json", operation_checks) + args.branch_preparation_seconds = operation_checks.get("construction_seconds", 0.0) + results = [] + for support in args.supports: + pair = paired_edit(world, support=support, k=1) + scopes = getattr(args, "scopes", None) + if scopes is None: + scopes = ["mlp", "all"] + (["down"] if support == 0 else []) + for scope in scopes: + for kind in ("coherent", "exception"): + results.append( + edit_case( + model, + checkpoint["model"], + world, + data, + pair, + kind, + scope, + args, + old_arrays["correct"], + ) + ) + if support == 0 and bases is not None: + for branch_kind, basis in bases.items(): + for kind in ("coherent", "exception"): + results.append( + edit_case( + model, + checkpoint["model"], + world, + data, + pair, + kind, + "mlp", + args, + old_arrays["correct"], + branch_kind, + basis, + ) + ) + write_json(out / "complete.json", {"status": "complete", "cases": results}) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--supports", type=int, nargs="+", default=[0, 1]) + parser.add_argument("--scopes", choices=["mlp", "all", "down"], nargs="+") + parser.add_argument("--steps", type=int, default=512) + parser.add_argument("--window", type=int, default=3) + parser.add_argument("--lr", type=float, default=3e-5) + parser.add_argument("--retention", type=float, default=1.0) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--branches", action="store_true") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_followup.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..c90b76331ad0bbd37276b4a9fe14b865360e7a60 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_followup.py @@ -0,0 +1,381 @@ +"""Small, paired follow-ups using frozen editing and gradient implementations. + +Historical source files are left intact. A process-local, scoped adapter supplies +only a new supervised weight vector to the established P1 training loop. +""" + +import argparse +import fcntl +import itertools +import json +import os +import subprocess +import sys +import time +from contextlib import contextmanager +from pathlib import Path +from types import MethodType + +import numpy as np +import torch + +from . import bios_context_gradient as gradient +from . import bios_mechanism_edit as editing +from .bios_cross import make_cross_world +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = "configs/bios-followup-v1.json" +ROOT_MASSES = {"root125": 0.125, "root250": 0.25, "root500": 0.5} +ORIGINAL_MAKE_ARM = editing.make_arm +ORIGINAL_SOURCE_HASHES = editing.source_hashes + + +def mixture_spec(world, chain, arm, pair=None): + if "-root" not in arm: + return ORIGINAL_MAKE_ARM(world, chain, arm, pair) + kind, tag = arm.split("-", 1) + if kind not in ("coherent", "exception") or tag not in ROOT_MASSES: + raise ValueError("Unknown mixture arm") + spec = ORIGINAL_MAKE_ARM(world, chain, kind, pair) + mass = ROOT_MASSES[tag] + mask = spec["S_root_mask"] + spec["S_weights"] = np.where( + mask, mass * len(mask) / mask.sum(), (1 - mass) * len(mask) / (~mask).sum() + ) + return spec + + +def production_hashes(): + return {**ORIGINAL_SOURCE_HASHES(), Path(__file__).name: editing.file_hash(__file__)} + + +@contextmanager +def mixture_adapter(): + old_make, old_hash = editing.make_arm, editing.source_hashes + editing.make_arm, editing.source_hashes = mixture_spec, production_hashes + try: + yield + finally: + editing.make_arm, editing.source_hashes = old_make, old_hash + + +def uniform_forward(self, x): + """First-layer uniform causal attention, with the full value/projection path.""" + width = x.shape[-1] + value = self.qkv(x)[..., 2 * width :] + mask = gradient.allowed_mask(x.shape[1], False, x.device).to(x.dtype) + mask = mask / mask.sum(-1, keepdim=True) + return self.proj(mask @ value) + + +@contextmanager +def uniform_first_layer(model): + attention = model.blocks[0].attention + original = attention.forward + attention.forward = MethodType(uniform_forward, attention) + try: + yield + finally: + attention.forward = original + + +def load_config(): + config = json.loads((ROOT / CONFIG).read_text()) + if config["root_mass"] != {"uniform": 1 / 31, **ROOT_MASSES}: + raise ValueError("The declared mixture weights differ from the implementation") + return config + + +def frozen_paths(config): + paths = [ + ROOT / CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_followup.py", + ROOT / "tests/test_bios_followup.py", + ROOT / "src/llm_memory_editability/bios_context_gradient.py", + ROOT / "src/llm_memory_editability/bios_mechanism_edit.py", + ROOT / "scripts/run_bios_mechanism_edit.py", + ROOT / config["gradient_config"], + ROOT / "docs/development-artifacts/context-gradient-v1/preregistration-lock.json", + ] + paths += [ROOT / "src/llm_memory_editability" / name for name in editing.parent_source_hashes()] + for world, seed, condition in itertools.product( + config["worlds"], config["seeds"], config["conditions"] + ): + name = f"world-{world}-seed-{seed}-{condition}" + paths += [ROOT / config["parent_root"] / name / "config.json"] + paths += [ROOT / config["balanced_root"] / name / "contract.json"] + return sorted(set(paths)) + + +def freeze(config): + artifacts = ROOT / config["artifacts"] + artifacts.mkdir(parents=True, exist_ok=True) + lock = artifacts / "preregistration-lock.json" + if lock.exists(): + raise FileExistsError("Existing prospective lock cannot be replaced") + protocol = (ROOT / "docs/experimental-protocol.md").read_text().split("## 17. ", 1)[1] + (artifacts / "preregistration.md").write_text("## 17. " + protocol) + sources = {} + for path in frozen_paths(config): + relative = path.relative_to(ROOT) + sources[str(relative)] = editing.file_hash(path) + if relative.parts[0] not in ("results", "data"): + destination = artifacts / "frozen-files" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(path.read_bytes()) + write_json( + lock, + { + "created_at": gradient.stamp(), + "config": config, + "sources": sources, + "protocol_sha256": editing.file_hash(artifacts / "preregistration.md"), + "torch": torch.__version__, + "numpy": np.__version__, + }, + ) + return {"lock": str(lock), "sha256": editing.file_hash(lock)} + + +def verify_lock(config): + artifacts = ROOT / config["artifacts"] + path = artifacts / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Frozen configuration/runtime mismatch") + for source, digest in lock["sources"].items(): + if editing.file_hash(ROOT / source) != digest: + raise ValueError("Frozen source mismatch: " + source) + if editing.file_hash(artifacts / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Frozen protocol mismatch") + return editing.file_hash(path) + + +def run_edit(config, world, seed, condition, device): + verify_lock(config) + if (world, seed, condition) not in itertools.product( + config["worlds"], config["seeds"], config["conditions"] + ): + raise ValueError("Edit worker is outside the frozen matrix") + name = f"world-{world}-seed-{seed}-{condition}" + destination = ROOT / config["output"] / "editing" / name + destination.mkdir(parents=True, exist_ok=True) + with (destination / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + with mixture_adapter(): + editing.run_model( + ROOT / config["parent_root"] / name, destination, config["edit"], device + ) + + +def verify_receipt(path): + receipt = json.loads((path / "receipt.json").read_text()) + for name, digest in receipt["files"].items(): + if editing.file_hash(path / name) != digest: + raise ValueError("Gradient receipt mismatch: " + str(path / name)) + + +def run_gradient(config, world_seed, seed, device): + lock_hash = verify_lock(config) + if world_seed not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("Gradient worker is outside the frozen matrix") + original = json.loads((ROOT / config["gradient_config"]).read_text()) + gradient.verify_lock(ROOT, original) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + world = make_cross_world(world_seed, ROOT / original["source_world_root"]) + name = f"world-{world_seed}-seed-{seed}" + source = ROOT / config["gradient_parent"] / name + destination = ROOT / config["output"] / "gradient" / name + destination.mkdir(parents=True, exist_ok=True) + seal = json.loads((source / "complete.json").read_text()) + consumed = {"complete.json": editing.file_hash(source / "complete.json")} + with (destination / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if (destination / "complete.json").exists(): + raise FileExistsError("Completed gradient worker cannot be overwritten") + for step in config["gradient"]["states"]: + checkpoint = source / f"state-{step}.pt" + digest = editing.file_hash(checkpoint) + if digest != seal["files"][checkpoint.name]: + raise ValueError("Archived common state hash mismatch") + consumed[checkpoint.name] = digest + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + if saved["step"] != step: + raise ValueError("Common state step mismatch") + model = CausalLM(ModelConfig(**saved["config"])).to(device) + model.load_state_dict(saved["model"]) + sham = config["gradient"]["sham"] + if (world_seed, seed, step) == (sham["world"], sham["seed"], sham["step"]): + path = destination / "sham" + if not (path / "receipt.json").exists(): + gradient.measure_arm( + model, world, sham["condition"], False, original, device, path + ) + verify_receipt(path) + before = source / f"step-{step}-open-{sham['condition']}" + verify_receipt(before) + errors = {} + for kind in ("answer", "eos"): + with np.load(before / f"{kind}.npz") as a, np.load(path / f"{kind}.npz") as b: + for parameter in a.files: + reference = np.linalg.norm(a[parameter].astype(np.float64)) + difference = np.linalg.norm( + b[parameter].astype(np.float64) - a[parameter] + ) + error = ( + float(difference / reference) if reference else float(difference) + ) + errors[f"{kind}/{parameter}"] = error + if max(errors.values()) > config["gradient"]["sham_relative_tolerance"]: + raise ValueError("Historical-gradient sham failed") + write_json(destination / "sham-check.json", errors) + for condition in config["conditions"]: + path = destination / f"step-{step}-uniform-{condition}" + if not (path / "receipt.json").exists(): + with uniform_first_layer(model): + gradient.measure_arm(model, world, condition, False, original, device, path) + verify_receipt(path) + print(json.dumps({"event": "gradient_arm_complete", "path": str(path)}), flush=True) + del model, saved + verify_lock(config) + write_json( + destination / "complete.json", + { + "complete": True, + "created_at": gradient.stamp(), + "lock_sha256": lock_hash, + "parent": str(source), + "consumed": consumed, + "world": world_seed, + "seed": seed, + "device": str(device), + "gpu": torch.cuda.get_device_name(device), + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "new_uniform_arms": 9, + "files": { + str(p.relative_to(destination)): editing.file_hash(p) + for p in sorted(destination.rglob("*")) + if p.is_file() and p.suffix in ("npz", ".npz", ".json") + }, + }, + ) + + +def jobs(config): + result = [] + for world, seed in itertools.product(config["worlds"], config["seeds"]): + name = f"world-{world}-seed-{seed}" + result.append(("gradient/" + name, ["run-gradient", "--world", world, "--seed", seed])) + for condition in config["conditions"]: + result.append( + ( + "editing/" + name + "-" + condition, + ["run-edit", "--world", world, "--seed", seed, "--condition", condition], + ) + ) + return result + + +def dispatch(config, gpus, slots): + if not gpus or len(set(gpus)) != len(gpus) or slots < 1 or 0 in gpus: + raise ValueError( + "Unique healthy GPUs and positive concurrency required; GPU0 has ECC errors" + ) + lock_hash = verify_lock(config) + destination = ROOT / config["output"] + destination.mkdir(parents=True, exist_ok=True) + with (destination / ".dispatcher.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + pending, complete, failed, active = [], [], [], [] + for name, arguments in jobs(config): + if (destination / name / "complete.json").exists(): + complete.append(name) + else: + pending.append((name, arguments)) + while pending or active: + for item in active[:]: + code = item["process"].poll() + if code is None: + continue + item["log"].close() + good = code == 0 and (destination / item["name"] / "complete.json").exists() + (complete if good else failed).append(item["name"]) + active.remove(item) + if not failed: + for gpu in gpus: + while pending and sum(i["gpu"] == gpu for i in active) < slots: + name, arguments = pending.pop(0) + out = destination / name + out.mkdir(parents=True, exist_ok=True) + command = [sys.executable, "-m", "llm_memory_editability.bios_followup"] + command += [str(a) for a in arguments] + log = (out / "run.log").open("a") + env = { + **os.environ, + "PYTHONPATH": str(ROOT / "src"), + "CUDA_VISIBLE_DEVICES": str(gpu), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + process = subprocess.Popen( + command, cwd=ROOT, env=env, stdout=log, stderr=log + ) + write_json( + out / "launch.json", + { + "pid": process.pid, + "gpu": gpu, + "command": command, + "started": gradient.stamp(), + }, + ) + active.append({"name": name, "gpu": gpu, "process": process, "log": log}) + write_json( + destination / "status.json", + { + "state": "failed" if failed else "running" if active or pending else "complete", + "lock_sha256": lock_hash, + "complete": complete, + "failed": failed, + "pending": len(pending), + "active": [ + {"name": i["name"], "gpu": i["gpu"], "pid": i["process"].pid} + for i in active + ], + "updated": gradient.stamp(), + }, + ) + if failed and not active: + raise RuntimeError("Worker failure; unstarted jobs retained") + if pending or active: + time.sleep(5) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=("freeze", "dispatch", "run-edit", "run-gradient")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--condition") + parser.add_argument("--gpus", type=int, nargs="+") + parser.add_argument("--slots-per-gpu", type=int, default=1) + parser.add_argument("--device", default="cuda:0") + args = parser.parse_args() + torch.set_num_threads(2) + config = load_config() + if args.mode == "freeze": + print(json.dumps(freeze(config))) + elif args.mode == "dispatch": + dispatch(config, args.gpus, args.slots_per_gpu) + elif args.mode == "run-edit": + run_edit(config, args.world, args.seed, args.condition, torch.device(args.device)) + else: + run_gradient(config, args.world, args.seed, torch.device(args.device)) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_measure.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_measure.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf7c45f10b2be179635d21d0f3a7fde2ee6ca6c --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_measure.py @@ -0,0 +1,286 @@ +"""Pre-edit activation geometry and controlled mean-component interventions. + +Company means are candidate shared components, not assumed learned mechanisms. +All donors, recipients and controls depend only on the old world and fixed seeds. +""" + +import argparse +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import EOS, load_world, rng_for, write_json +from .bios_model import CausalLM, ModelConfig +from .bios_train import code_fingerprint, precision, tensor_data + + +@torch.no_grad() +def activation_summary(model, world, data): + device = data["tokens"].device + collected = [[] for _ in model.blocks] + detailed = {} + first_batch = [True] + handles = [] + # Actual-city atomic queries have final prompt position 3. + for layer, block in enumerate(model.blocks): + + def capture(_module, _inputs, output, layer=layer): + collected[layer].append(output[:, 3].float().cpu()) + if first_batch[0]: + detailed[f"z_positions_layer_{layer}"] = ( + output[:128, [1, 2, 3]].float().cpu().numpy() + ) + + handles.append(block.mlp.activation.register_forward_hook(capture)) + + def capture_mlp(_module, inputs, output, layer=layer): + if first_batch[0]: + detailed[f"x_positions_layer_{layer}"] = ( + inputs[0][:128, [1, 2, 3]].float().cpu().numpy() + ) + detailed[f"h_positions_layer_{layer}"] = ( + output[:128, [1, 2, 3]].float().cpu().numpy() + ) + + handles.append(block.mlp.register_forward_hook(capture_mlp)) + with precision(device): + for begin in range(2112, 4160, 256): + model( + data["prompts"][begin : begin + 256], data["lengths"][begin : begin + 256, None] - 1 + ) + first_batch[0] = False + for handle in handles: + handle.remove() + activations = [torch.cat(parts) for parts in collected] + summaries, means = [], [] + for layer, z in enumerate(activations): + mu = torch.stack([z[world.employers == c].mean(0) for c in range(64)]) + centered = mu - z.mean(0) + residual = z - mu[world.employers] + shared_variance = centered.square().mean().item() + individual_variance = residual.square().mean().item() + cosine = F.cosine_similarity(z, mu[world.employers], dim=-1) + summaries.append( + { + "layer": layer, + "mean_norm": z.norm(dim=-1).mean().item(), + "company_mean_variance": shared_variance, + "within_company_variance": individual_variance, + "shared_variance_fraction": shared_variance + / (shared_variance + individual_variance + 1e-20), + "member_to_company_cosine": cosine.mean().item(), + } + ) + means.append(mu) + detailed["query_ids"] = np.arange(2112, 2240) + detailed["token_positions"] = np.array([1, 2, 3]) + return summaries, means, activations, detailed + + +def probe_plan(world): + rng = rng_for(world.seed, 51) + recipients = rng.permutation(64)[:8] + result = [] + for c in recipients: + same = np.flatnonzero((world.defaults == world.defaults[c]) & (np.arange(64) != c))[0] + donor = rng.choice(np.flatnonzero(world.defaults != world.defaults[c])) + wrong = rng.choice( + np.flatnonzero(~np.isin(world.defaults, [world.defaults[c], world.defaults[donor]])) + ) + unrelated = rng.choice(np.flatnonzero(~np.isin(np.arange(64), [c, donor, same, wrong]))) + members = np.flatnonzero(world.employers == c) + other = np.flatnonzero(world.employers == unrelated) + ids = np.concatenate([2112 + members, 6208 + members, 2112 + other]) + # 6208 is the first birth-city row: employer 2048 + defaults 64 + actual/date 4096. + group = np.concatenate( + [np.where(world.exceptions[members], 1, 0), np.full(32, 2), np.full(32, 3)] + ) + result.append( + { + "recipient": int(c), + "donor": int(donor), + "same_answer": int(same), + "wrong_donor": int(wrong), + "unrelated": int(unrelated), + "ids": ids, + "group": group, + } + ) + return result + + +@torch.no_grad() +def causal_probes(model, world, data, means, behavior=False): + device = data["tokens"].device + results = [] + for plan_index, plan in enumerate(probe_plan(world)): + ids = torch.as_tensor(plan["ids"], device=device) + tokens = data["prompts"][ids] + positions = data["lengths"][ids, None] - 1 + donor_answer = int(world.city_tokens[world.defaults[plan["donor"]]]) + + def observe( + tokens=tokens, positions=positions, donor_answer=donor_answer, ids=ids, plan=plan + ): + with precision(device): + logits = model(tokens, positions)[:, 0].float() + probability = logits.softmax(-1)[:, donor_answer] + if not behavior: + return probability, None + first = logits.argmax(-1) + continuation = torch.zeros((len(ids), 6), dtype=torch.long, device=device) + continuation[:, :5] = tokens + rows = torch.arange(len(ids), device=device) + lengths = data["lengths"][ids] + continuation[rows, lengths] = first + ended = model(continuation, lengths[:, None])[:, 0].argmax(-1).eq(EOS) + truth = torch.as_tensor(world.answers[plan["ids"]], device=device) + return probability, { + "old_correct": (first.eq(truth) & ended).cpu().numpy(), + "donor_generated": (first.eq(donor_answer) & ended).cpu().numpy(), + "ended": ended.cpu().numpy(), + } + + baseline, baseline_behavior = observe() + for layer, mu_cpu in enumerate(means): + mu = mu_cpu.to(device) + c = plan["recipient"] + desired = mu[plan["donor"]] - mu[c] + generator = torch.Generator(device=device).manual_seed( + world.seed * 10000 + 100 * plan_index + layer + ) + random = torch.randn(desired.shape, generator=generator, device=device) + random = random * (desired.norm() / random.norm().clamp_min(1e-20)) + shifts = { + "donor": desired, + "same_answer_donor": mu[plan["same_answer"]] - mu[c], + "wrong_donor": mu[plan["wrong_donor"]] - mu[c], + "random_equal_norm": random, + "ablation": -(mu[c] - mu.mean(0)), + } + for kind, shift in shifts.items(): + + def patch(_module, _inputs, output, shift=shift): + edited = output.clone() + edited[:, 3] = edited[:, 3] + shift.to(output.dtype) + return edited + + handle = model.blocks[layer].mlp.activation.register_forward_hook(patch) + try: + changed, changed_behavior = observe() + finally: + handle.remove() + delta = (changed - baseline).cpu().numpy() + by_group = { + name: float(delta[plan["group"] == group].mean()) + for group, name in enumerate( + ( + "same_company_nonexception", + "old_exception", + "independent_attribute", + "unrelated_company", + ) + ) + } + result = { + "recipient": c, + "donor": plan["donor"], + "layer": layer, + "intervention": kind, + "shift_norm": shift.norm().item(), + **by_group, + "selective_shared_score": by_group["same_company_nonexception"] + - (by_group["independent_attribute"] + by_group["unrelated_company"]) / 2, + } + if behavior: + result["generation"] = {} + for group, name in enumerate(by_group): + mask = plan["group"] == group + known = mask & baseline_behavior["old_correct"] + result["generation"][name] = { + "n": int(mask.sum()), + "baseline_old_accuracy": float( + baseline_behavior["old_correct"][mask].mean() + ), + "changed_old_accuracy": float( + changed_behavior["old_correct"][mask].mean() + ), + "donor_generated_delta": float( + changed_behavior["donor_generated"][mask].mean() + - baseline_behavior["donor_generated"][mask].mean() + ), + "old_known": int(known.sum()), + "old_broken": int((known & ~changed_behavior["old_correct"]).sum()), + "nontermination_rate": float((~changed_behavior["ended"][mask]).mean()), + } + results.append(result) + return results + + +def run(args): + started = time.perf_counter() + torch.set_num_threads(4) + device = torch.device(args.device) + world = load_world(args.world) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + model.eval() + data = tensor_data(world, device) + summary, means, activations, detailed = activation_summary(model, world, data) + probes = causal_probes(model, world, data, means, behavior=args.behavior) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + out / "actual-city-activations.npz", + **{f"z_{i}": z.numpy() for i, z in enumerate(activations)}, + ) + np.savez_compressed(out / "input-activation-output-position-sample.npz", **detailed) + write_json( + out / "measurements.json", + { + "step": checkpoint["step"], + "device": str(device), + "precision": "BF16 autocast" if device.type == "cuda" else "FP32 CPU diagnostic", + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": hashlib.sha256(Path(args.checkpoint).read_bytes()).hexdigest(), + "measurement_seconds": time.perf_counter() - started, + "torch_version": torch.__version__, + "hardware": torch.cuda.get_device_name(device) if device.type == "cuda" else "CPU", + "behavior": args.behavior, + **code_fingerprint(), + "geometry": summary, + "probes": probes, + "scope": ( + "candidate company-mean components at final query token; " + "exploratory development measurement" + ), + }, + ) + print( + json.dumps( + {"event": "measurement_complete", "step": checkpoint["step"], "probes": len(probes)} + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument( + "--behavior", action="store_true", help="Also score complete generated answers" + ) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_mechanism_causal.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_mechanism_causal.py new file mode 100644 index 0000000000000000000000000000000000000000..8ac824d1ef628725bf1ee9ca778d381516508a80 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_mechanism_causal.py @@ -0,0 +1,969 @@ +"""Locked P4 necessity and downstream restoration diagnostics. + +Q is fitted only on actual queries in an archived exception case's S union R, +grouped by the model's own membership predictions. Truth-matched donor queries +are a subsequent diagnostic, never calibration. Restoring a same-query clean +downstream signal tests recovery from an artificial lesion, not edit repair. +""" + +import csv +import json +from pathlib import Path + +import numpy as np +import torch + +from .bios_causal_paths import make_donor_plan +from .bios_cross import CHAINS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_mechanism_interventions import ( + Site, + attach_state_operation, + calibration_plan, + downstream_routing_site, + fit_predicted_group_bases, + match_delta_norm, + projection_component, + query_site_roles, + remove_projection, + restore_projection, + valid_predicted_groups, +) +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import file_sha256 +from .bios_train import precision + +SOURCE = Site(0, 2) +DOWNSTREAM = Site(1, 2) +RANK = 32 +FAMILIES = ( + "default", + "actual", + "other_chain_default", + "attribute_3", + "attribute_4", + "attribute_5", + "attribute_6", + "membership", + "other_chain_actual", + "group_root", +) +ARMS = ( + "clean", + "sham", + "target_remove", + "random_remove", + "complement_remove", + "rescue_only", + "remove_rescue", + "remove_wrong_source_rescue", + "remove_random_rescue", +) +TRANSFER_TYPES = ( + "different_group_same_actual_different_default", + "different_group_same_default", + "different_group_same_default_same_actual", +) +TRANSFER_ARMS = ( + "sham", + "full_donor", + "full_norm_random", + "projected_target", + "projected_random", + "projected_complement", +) + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen diagnostic contract changed: {path}") + else: + write_json(path, value) + + +def _same_arrays(path, arrays): + if path.exists(): + with np.load(path) as existing: + if set(existing.files) != set(arrays) or any( + not np.array_equal(existing[key], value) for key, value in arrays.items() + ): + raise ValueError(f"Diagnostic plan changed: {path}") + else: + atomic_numpy_save(path, **arrays) + + +def _sources(): + directory = Path(__file__).parent + names = ( + "bios_mechanism_causal.py", + "bios_mechanism_interventions.py", + "bios_causal_paths.py", + "bios_cross.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_path_diagnostics.py", + ) + sources = {name: file_sha256(directory / name) for name in names} + runner = directory.parents[1] / "scripts/analyze_bios_mechanism_causal.py" + sources["runner"] = file_sha256(runner) + return sources + + +def validate_lock(lock): + if (lock.get("mechanism"), lock.get("layer"), lock.get("position")) != ("default_path", 0, 2): + raise ValueError("This runner only instantiates the locked default_path L0/pos2 candidate") + if lock.get("known_only") is not False or not lock.get("locked_at_utc"): + raise ValueError("An all-eligible, timestamped candidate lock is required") + + +def make_probe_plan(world, chain, recipients): + """Same people and fixed queries in every intervention, without knowledge filtering.""" + recipients = np.asarray(recipients, dtype=np.int64) + ids = [ + world.derived_ids[chain, recipients], + world.actual_ids[chain, recipients], + world.derived_ids[1 - chain, recipients], + ] + for relation in (3, 4, 5, 6): + candidates = np.flatnonzero(world.relation == relation) + by_person = np.full(len(world.actual_ids[chain]), -1, dtype=np.int64) + by_person[world.person[candidates]] = candidates + if (by_person[recipients] < 0).any(): + raise ValueError("An independent control query is missing") + ids.append(by_person[recipients]) + ids.extend([world.membership_ids[chain, recipients], world.actual_ids[1 - chain, recipients]]) + person_families = len(ids) + roots = world.root_ids[chain] + query_ids = np.concatenate([*ids, roots]) + return { + "query_id": query_ids, + "person": np.r_[np.tile(recipients, person_families), np.full(len(roots), -1)], + "family": np.r_[ + np.repeat(np.arange(person_families), len(recipients)), + np.full(len(roots), person_families), + ], + # -1 means not applicable; root facts are not ordinary people. + "recipient_old_exception": np.r_[ + np.tile(world.exceptions[chain, recipients].astype(np.int8), person_families), + np.full(len(roots), -1, dtype=np.int8), + ], + "answer": world.answers[query_ids], + } + + +def wrong_source_indices(families): + """Fixed one-person cyclic shift within each family, never chosen by answers.""" + families = np.asarray(families) + index = np.arange(len(families)) + for family in np.unique(families): + selected = np.flatnonzero(families == family) + if len(selected) < 2: + raise ValueError("Wrong-source controls require at least two queries per family") + index[selected] = np.roll(selected, 1) + return index + + +def make_transfer_plan(world, chain, per_population=64): + """Truth matching is restricted to this explicitly labeled offline diagnostic.""" + old = make_donor_plan(world, chain, per_population) + original = old["pair_type"] == 1 + recipients = old["recipient"][original] + train = world.person[world.train_ids[chain]] + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + rng = rng_for(world.seed, 978, chain) + donor_rows = [old["donor"][original]] + count_rows = [old["candidate_count"][original]] + for same_actual in (False, True): + donors, counts = [], [] + for recipient in recipients: + mask = (group[train] != group[recipient]) & (default[train] == default[recipient]) + if same_actual: + mask &= actual[train] == actual[recipient] + candidates = train[mask] + donors.append(rng.choice(candidates) if len(candidates) else -1) + counts.append(len(candidates)) + donor_rows.append(np.asarray(donors)) + count_rows.append(np.asarray(counts)) + donor = np.concatenate(donor_rows).astype(np.int64) + recipient = np.tile(recipients, len(TRANSFER_TYPES)) + safe = np.maximum(donor, 0) + return { + "case_id": np.arange(len(donor)), + "recipient": recipient, + "donor": donor, + "pair_type": np.repeat(np.arange(len(TRANSFER_TYPES)), len(recipients)), + "candidate_count": np.concatenate(count_rows), + "recipient_old_exception": world.exceptions[chain, recipient], + "same_actual": (actual[safe] == actual[recipient]) & (donor >= 0), + "same_default": (default[safe] == default[recipient]) & (donor >= 0), + "recipient_default": default[recipient], + "recipient_actual": actual[recipient], + "donor_default": np.where(donor >= 0, default[safe], -1), + "donor_actual": np.where(donor >= 0, actual[safe], -1), + } + + +def generate_queries( + model, prompts, lengths, device, batch_size=256, *, operations=None, capture_sites=() +): + """Two free generation passes with identical pre-answer operations, no answer input. + + operations(begin,end) returns (label, site, operation) triples. Every operation + returns its intended delta and availability; realized post-cast norms are + measured separately. Both passes are retained so norm matching is auditable. + """ + if len(prompts) == 0 or batch_size < 1: + raise ValueError("Generation needs nonempty queries and a positive batch size") + lengths = np.asarray(lengths) + if prompts.shape != (len(lengths), 5) or not np.isin(lengths, [4, 5]).all(): + raise ValueError("Unexpected symbolic query shape") + arrays = {"prediction": [], "ended": []} + for site in capture_sites: + query_site_roles(lengths, site.position) + arrays[f"state_{site.layer}_{site.position}"] = [] + calls = 0 + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + end = min(begin + batch_size, len(prompts)) + p = torch.as_tensor(prompts[begin:end], device=device) + n = torch.as_tensor(lengths[begin:end], device=device) + hooks, traces, captures = [], {}, {} + try: + for label, site, operation in () if operations is None else operations(begin, end): + query_site_roles(lengths[begin:end], site.position) + + def measured(value, operation=operation): + changed, trace = operation(value) + return changed, {**trace, "realized_delta": changed.float() - value.float()} + + hook, trace = attach_state_operation(model, site, measured) + hooks.append(hook) + traces[label] = trace + for site in capture_sites: + key = f"state_{site.layer}_{site.position}" + captures[key] = [] + + def capture( + _module, _inputs, output, key=key, position=site.position, captures=captures + ): + captures[key].append(output[:, position].detach().float()) + + hooks.append(model.blocks[site.layer].register_forward_hook(capture)) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + calls += 2 + arrays["prediction"].append(first.cpu().numpy()) + arrays["ended"].append(second.eq(EOS).cpu().numpy()) + for key, states in captures.items(): + arrays[key].append(states[0].cpu().numpy()) + drift = torch.linalg.vector_norm(states[1] - states[0], dim=-1) + arrays.setdefault(f"{key}_pass_drift", []).append(drift.cpu().numpy()) + for label, trace in traces.items(): + if len(trace) != 2: + raise ValueError( + "Every intervention must occur in both free-generation passes" + ) + for kind in ("delta", "realized_delta"): + norms = torch.stack( + [torch.linalg.vector_norm(t[kind].float(), dim=-1) for t in trace], + dim=1, + ) + arrays.setdefault(f"{label}_{kind}_norm", []).append(norms.cpu().numpy()) + valid = torch.stack([t["valid"] for t in trace], dim=1) + arrays.setdefault(f"{label}_valid", []).append(valid.cpu().numpy()) + finally: + for hook in hooks: + hook.remove() + result = {key: np.concatenate(value) for key, value in arrays.items()} + result.update( + forward_calls=np.asarray(calls), + forward_examples=np.asarray(2 * len(prompts)), + padded_token_positions=np.asarray(11 * len(prompts)), + logical_token_positions=np.asarray(int((2 * lengths + 1).sum())), + ) + return result + + +def _identity_trace(value): + return value, { + "delta": torch.zeros_like(value, dtype=torch.float32), + "valid": torch.ones(len(value), dtype=torch.bool, device=value.device), + } + + +def lesion_operations( + arm, source_bases, downstream_bases, clean_downstream, wrong_index, seed, device +): + """Return a deterministic batch factory. Wrong-source choice never sees truth.""" + if arm not in ARMS: + raise ValueError("Unknown necessity/restoration arm") + if arm == "clean": + return lambda _begin, _end: [] + if arm == "sham": + return lambda _begin, _end: [("source", SOURCE, _identity_trace)] + source = {key: basis.tensors(device) for key, basis in source_bases.items()} + downstream = ( + None + if downstream_bases is None + else {key: basis.tensors(device) for key, basis in downstream_bases.items()} + ) + needs_downstream = "rescue" in arm + if needs_downstream and downstream is None: + raise ValueError("Downstream basis is unavailable; recovery cannot be estimated") + wrong_index = np.asarray(wrong_index) + if len(wrong_index) != len(clean_downstream): + raise ValueError("Wrong-source plan length mismatch") + coefficients = ( + np.random.default_rng(seed) + .standard_normal((len(clean_downstream), source_bases["random"].rank)) + .astype(np.float32) + ) + + def factory(begin, end): + ops = [] + if arm == "clean": + return ops + if arm == "sham": + return [("source", SOURCE, _identity_trace)] + if arm != "rescue_only": + kind = ( + arm.removesuffix("_remove") + if arm in ("random_remove", "complement_remove") + else "target" + ) + q, mean, _ = source[kind] + tq, tm, _ = source["target"] + + def remove(value): + reference = ( + None + if kind == "target" + else torch.linalg.vector_norm(projection_component(value, tq, tm), dim=-1) + ) + return remove_projection(value, q, mean, reference) + + ops.append(("source", SOURCE, remove)) + if needs_downstream: + clean = torch.as_tensor(clean_downstream[begin:end], device=device) + wrong = torch.as_tensor(clean_downstream[wrong_index[begin:end]], device=device) + tq = downstream["target"][0] + rq = downstream["random"][0] + noise = torch.as_tensor(coefficients[begin:end], device=device) @ rq.T + + def recover(value): + _, same_query_trace = restore_projection(value, clean, tq) + correct_delta = same_query_trace["delta"] + reference = torch.linalg.vector_norm(correct_delta, dim=-1) + if arm == "remove_wrong_source_rescue": + return restore_projection(value, wrong, tq, reference) + if arm == "remove_random_rescue": + delta, valid = match_delta_norm(noise, reference) + return value + delta.to(value.dtype), {"delta": delta, "valid": valid} + return restore_projection(value, clean, tq) + + ops.append(("downstream", DOWNSTREAM, recover)) + return ops + + return factory + + +def transfer_operations(arm, bases, recipient, donor, seed, device): + """A locked-basis manipulation check, never a basis-fitting input.""" + if arm not in TRANSFER_ARMS or recipient.shape != donor.shape: + raise ValueError("Invalid donor manipulation") + if arm.startswith("projected_") and bases is None: + raise ValueError("Projected donor diagnostic requires an available source basis") + full_delta = donor.astype(np.float32) - recipient.astype(np.float32) + if arm == "sham": + delta, valid = np.zeros_like(full_delta), np.ones(len(donor), dtype=bool) + elif arm == "full_donor": + delta, valid = full_delta, np.ones(len(donor), dtype=bool) + else: + if arm == "full_norm_random": + raw = np.random.default_rng(seed).standard_normal(full_delta.shape).astype(np.float32) + reference = np.linalg.norm(full_delta, axis=-1) + else: + tq = bases["target"].q + target_delta = (full_delta @ tq) @ tq.T + reference = np.linalg.norm(target_delta, axis=-1) + q = bases[arm.removeprefix("projected_")].q + raw = (full_delta @ q) @ q.T + matched, available = match_delta_norm(torch.from_numpy(raw), torch.from_numpy(reference)) + delta, valid = matched.numpy(), available.numpy() + + def factory(begin, end): + change = torch.as_tensor(delta[begin:end], device=device) + available = torch.as_tensor(valid[begin:end], device=device) + + def operation(value): + return value + change.to(value.dtype), {"delta": change, "valid": available} + + return [("source", SOURCE, operation)] + + return factory + + +def _availability(arrays): + valid = np.ones(len(arrays["prediction"]), dtype=bool) + for key, value in arrays.items(): + if key.endswith("_valid"): + valid &= value.all(axis=1) + return valid + + +def score_rows(arrays, baseline, plan, arm, labels=FAMILIES, label_key="family"): + """All eligible rows first; original-correct strata remain descriptive only.""" + base_correct = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + correct = (arrays["prediction"] == plan["answer"]) & arrays["ended"] + available = _availability(arrays) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available + n, nb = int(chosen.sum()), int((chosen & base_correct).sum()) + before, after = int((chosen & base_correct).sum()), int((chosen & correct).sum()) + row = { + "arm": arm, + "family": family, + "population": population, + "requested": int(requested.sum()), + "available": n, + "unavailable": int((requested & ~available).sum()), + "baseline_correct": before, + "correct": after, + "accuracy": after / n if n else None, + "delta_accuracy": (after - before) / n if n else None, + "known_became_wrong": int((chosen & base_correct & ~correct).sum()), + "wrong_became_correct": int((chosen & ~base_correct & correct).sum()), + "known_denominator": nb, + "known_retention": int((chosen & base_correct & correct).sum()) / nb + if nb + else None, + "termination_error": int((chosen & ~arrays["ended"]).sum()), + "prediction_changed": int( + ( + chosen + & ( + (arrays["prediction"] != baseline["prediction"]) + | (arrays["ended"] != baseline["ended"]) + ) + ).sum() + ), + } + for label in ("source", "downstream"): + for kind in ("delta", "realized_delta"): + key = f"{label}_{kind}_norm" + row[f"mean_{key}"] = ( + float(arrays[key][chosen, 0].mean()) if n and key in arrays else None + ) + rows.append(row) + return rows + + +def paired_score_rows( + left, right, baseline, plan, left_name, right_name, labels=FAMILIES, label_key="family" +): + """Contrasts use a common availability mask, never unmatched denominators.""" + correct_left = (left["prediction"] == plan["answer"]) & left["ended"] + correct_right = (right["prediction"] == plan["answer"]) & right["ended"] + correct_clean = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + available_left, available_right = _availability(left), _availability(right) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available_left & available_right + n = int(chosen.sum()) + nl, nr = int((chosen & correct_left).sum()), int((chosen & correct_right).sum()) + known_right_wrong = chosen & correct_clean & ~correct_right + denominator = int(known_right_wrong.sum()) + rows.append( + { + "left": left_name, + "right": right_name, + "family": family, + "population": population, + "requested": int(requested.sum()), + "common_available": n, + "left_unavailable": int((requested & ~available_left).sum()), + "right_unavailable": int((requested & ~available_right).sum()), + "left_correct": nl, + "right_correct": nr, + "accuracy_difference": (nl - nr) / n if n else None, + "right_wrong_left_correct": int((chosen & ~correct_right & correct_left).sum()), + "right_correct_left_wrong": int((chosen & correct_right & ~correct_left).sum()), + "original_known_right_wrong": denominator, + "original_known_right_wrong_left_recovered": int( + (known_right_wrong & correct_left).sum() + ), + "conditional_recovery_auxiliary": int((known_right_wrong & correct_left).sum()) + / denominator + if denominator + else None, + } + ) + return rows + + +def _check_predictions(generated, archived, ids): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], archived[key][ids]): + raise ValueError(f"Clean frozen-model generation differs from archive: {key}") + + +def _cost(arrays): + return { + key: int(arrays[key]) + for key in ( + "forward_calls", + "forward_examples", + "padded_token_positions", + "logical_token_positions", + ) + } + + +def _cached_generate(path, model, world, ids, device, batch_size, **kwargs): + if path.exists(): + with np.load(path) as stored: + result = dict(stored) + if not np.array_equal(result.pop("query_id"), ids): + raise ValueError("Cached generation query plan differs") + return result + result = generate_queries( + model, world.prompts[ids], world.lengths[ids], device, batch_size, **kwargs + ) + atomic_numpy_save(path, query_id=ids, **result) + return result + + +def _fit_chain(model, world, chain, pair, dest, device, batch_size, archived): + plan = calibration_plan( + world.actual_ids[chain], + world.person, + world.membership_ids[chain], + pair["E"], + pair["replay"], + ) + _same_arrays( + dest / "calibration-plan.npz", {key: np.asarray(value) for key, value in plan.items()} + ) + actual = _cached_generate( + dest / "calibration-actual.npz", + model, + world, + plan["actual_query_ids"], + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + membership = _cached_generate( + dest / "calibration-membership.npz", + model, + world, + plan["membership_query_ids"], + device, + batch_size, + ) + _check_predictions(actual, archived, plan["actual_query_ids"]) + _check_predictions(membership, archived, plan["membership_query_ids"]) + prefix = f"{CHAINS[chain]}:" + allowed = np.array( + [i for i, label in enumerate(world.token_labels) if label.startswith(prefix)] + ) + groups, valid = valid_predicted_groups(membership["prediction"], membership["ended"], allowed) + _same_arrays(dest / "self-predicted-groups.npz", {"prediction": groups, "valid": valid}) + bases, reports, basis_arrays = {}, {}, {} + for label, site in (("source", SOURCE), ("downstream", DOWNSTREAM)): + basis, report = fit_predicted_group_bases( + actual[f"state_{site.layer}_{site.position}"], groups, valid, rank=RANK, seed=74 + chain + ) + bases[label], reports[label] = basis, report + if basis is not None: + for kind, value in basis.items(): + for field in ("q", "mean", "scale"): + basis_arrays[f"{label}_{kind}_{field}"] = getattr(value, field) + _same_arrays(dest / "bases.npz", basis_arrays) + information = { + "S_count": len(pair["E"]), + "R_count": len(pair["replay"]), + "actual_queries": len(plan["actual_query_ids"]), + "additional_membership_queries": len(plan["membership_query_ids"]), + "derived_calibration_queries": 0, + "true_memberships_supplied": False, + "membership_syntax_rule": prefix, + "invalid_groups_never_replaced": True, + "calibration_cost": {"actual": _cost(actual), "membership": _cost(membership)}, + "basis_reports": reports, + "variant": "group_means", + "basis_sha256": file_sha256(dest / "bases.npz"), + } + _freeze_json(dest / "calibration.json", information) + # Truth is read only after Q and its information contract are frozen. These + # labels score calibration quality; they never select rows or alter Q. + membership_correct = ( + membership["prediction"] == world.answers[plan["membership_query_ids"]] + ) & membership["ended"] + _freeze_json( + dest / "calibration-diagnostics.json", + { + "role": "offline scoring after frozen Q; never fitting or row selection", + "queries": len(groups), + "valid_predictions": int(valid.sum()), + "valid_rate": float(valid.mean()), + "correct_predictions": int(membership_correct.sum()), + "accuracy": float(membership_correct.mean()), + "accuracy_given_valid_auxiliary": float(membership_correct[valid].mean()) + if valid.any() + else None, + "basis_sha256": information["basis_sha256"], + }, + ) + return bases + + +def run_chain(model, world, chain, pair, dest, device, batch_size, per_population, archived): + dest.mkdir(parents=True, exist_ok=True) + bases = _fit_chain(model, world, chain, pair, dest, device, batch_size, archived) + transfer = make_transfer_plan(world, chain, per_population) + _same_arrays(dest / "transfer-plan.npz", transfer) + recipients = transfer["recipient"][transfer["pair_type"] == 0] + plan = make_probe_plan(world, chain, recipients) + plan["wrong_source_index"] = wrong_source_indices(plan["family"]) + plan["wrong_source_query_id"] = plan["query_id"][plan["wrong_source_index"]] + plan["wrong_source_same_answer"] = plan["answer"] == plan["answer"][plan["wrong_source_index"]] + _same_arrays(dest / "probe-plan.npz", plan) + ids = plan["query_id"] + query_site_roles(world.lengths[ids], SOURCE.position) + if downstream_routing_site(SOURCE, len(model.blocks), world.lengths[ids] - 1) != DOWNSTREAM: + raise ValueError("Candidate/downstream site mismatch") + clean = _cached_generate( + dest / "clean.npz", + model, + world, + ids, + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + _check_predictions(clean, archived, ids) + rows, states, costs, arm_arrays = [], {}, {"clean": _cost(clean)}, {} + clean_down = clean[f"state_{DOWNSTREAM.layer}_{DOWNSTREAM.position}"] + for arm in ARMS: + if arm not in ("clean", "sham") and bases["source"] is None: + states[arm] = "unavailable_source_rank" + continue + if "rescue" in arm and bases["downstream"] is None: + states[arm] = "unavailable_downstream_rank" + continue + if arm == "clean": + generated = clean + else: + operations = lesion_operations( + arm, + bases["source"], + bases["downstream"], + clean_down, + plan["wrong_source_index"], + [world.seed, 979, chain], + device, + ) + generated = _cached_generate( + dest / f"{arm}.npz", model, world, ids, device, batch_size, operations=operations + ) + if arm in ("sham", "rescue_only"): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], clean[key]): + raise ValueError(f"No-lesion control changed output: {arm}/{key}") + rows.extend(score_rows(generated, clean, plan, arm)) + costs[arm], states[arm] = _cost(generated), "complete" + arm_arrays[arm] = generated + comparisons = [ + (arm, "clean") + for arm in ("sham", "target_remove", "random_remove", "complement_remove", "rescue_only") + ] + comparisons += [("target_remove", arm) for arm in ("random_remove", "complement_remove")] + comparisons += [ + (arm, "target_remove") + for arm in ("remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue") + ] + comparisons += [ + ("remove_rescue", arm) for arm in ("remove_wrong_source_rescue", "remove_random_rescue") + ] + paired_rows = [] + for left, right in comparisons: + if left in arm_arrays and right in arm_arrays: + paired_rows.extend( + paired_score_rows(arm_arrays[left], arm_arrays[right], clean, plan, left, right) + ) + # Donor activations are read only after both bases and their provenance are frozen. + valid = transfer["donor"] >= 0 + selected = {key: value[valid] for key, value in transfer.items()} + people = np.unique(np.r_[selected["recipient"], selected["donor"]]) + donor_ids = world.derived_ids[chain, people] + donor_clean = _cached_generate( + dest / "transfer-clean.npz", + model, + world, + donor_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + _check_predictions(donor_clean, archived, donor_ids) + ri, di = ( + np.searchsorted(people, selected["recipient"]), + np.searchsorted(people, selected["donor"]), + ) + source_state = donor_clean[f"state_{SOURCE.layer}_{SOURCE.position}"] + donor_baseline = {key: donor_clean[key][ri] for key in ("prediction", "ended")} + donor_plan = {**selected, "answer": selected["recipient_default"]} + transfer_rows, transfer_status = [], {} + costs["transfer_clean"] = _cost(donor_clean) + for arm in TRANSFER_ARMS: + if arm.startswith("projected_") and bases["source"] is None: + transfer_status[arm] = "unavailable_source_rank" + continue + ops = transfer_operations( + arm, + bases["source"], + source_state[ri], + source_state[di], + [world.seed, 980, chain], + device, + ) + generated = _cached_generate( + dest / f"transfer-{arm}.npz", + model, + world, + world.derived_ids[chain, selected["recipient"]], + device, + batch_size, + operations=ops, + ) + if arm == "sham": + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], donor_baseline[key]): + raise ValueError("Transfer sham changed output") + scored = score_rows( + generated, donor_baseline, donor_plan, arm, labels=TRANSFER_TYPES, label_key="pair_type" + ) + for row in scored: + code = TRANSFER_TYPES.index(row["family"]) + chosen = (selected["pair_type"] == code) & _availability(generated) + requested = transfer["pair_type"] == code + if row["population"] != "all": + exception = row["population"] == "old_exception" + chosen &= selected["recipient_old_exception"] == exception + requested &= transfer["recipient_old_exception"] == exception + row["plan_requested"] = int(requested.sum()) + row["missing_donors"] = int((requested & ~valid).sum()) + for role in ("recipient_actual", "donor_default", "donor_actual"): + matched = (generated["prediction"] == selected[role]) & generated["ended"] + base_matched = (donor_baseline["prediction"] == selected[role]) & donor_baseline[ + "ended" + ] + row[f"matches_{role}"] = int((chosen & matched).sum()) + row[f"baseline_matches_{role}"] = int((chosen & base_matched).sum()) + # Donor's own clean response is descriptive, not an eligibility filter. + row["donor_answered_default"] = int( + ( + chosen + & donor_clean["ended"][di] + & (donor_clean["prediction"][di] == selected["donor_default"]) + ).sum() + ) + transfer_rows.extend(scored) + transfer_status[arm], costs[f"transfer_{arm}"] = "complete", _cost(generated) + for filename, contents in ( + ("necessity.csv", rows), + ("paired-necessity.csv", paired_rows), + ("transfer.csv", transfer_rows), + ): + with (dest / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + dest / "status.json", + { + "arms": states, + "transfer_arms": transfer_status, + "evaluation_cost": costs, + "information_boundary": "truth-matched donor states are diagnostic only", + }, + ) + return {"chain": CHAINS[chain], "arms": states, "transfer_arms": transfer_status} + + +def scientific_outputs(output): + """Seal only producer-owned artifacts, excluding mutable queue logs and locks.""" + names = { + "calibration-plan.npz", + "calibration-actual.npz", + "calibration-membership.npz", + "self-predicted-groups.npz", + "bases.npz", + "calibration.json", + "calibration-diagnostics.json", + "transfer-plan.npz", + "probe-plan.npz", + "transfer-clean.npz", + "necessity.csv", + "paired-necessity.csv", + "transfer.csv", + "status.json", + } + names.update(f"{arm}.npz" for arm in ARMS) + names.update(f"transfer-{arm}.npz" for arm in TRANSFER_ARMS) + paths = [output / "contract.json"] + for chain in CHAINS: + paths.extend( + output / chain / name for name in sorted(names) if (output / chain / name).exists() + ) + return {str(path.relative_to(output)): file_sha256(path) for path in paths} + + +def run_model(run, output, lock_path, *, device="cuda", batch_size=256, per_population=64): + """One original pre-edit checkpoint, both chains; separate outputs, restartable nodes.""" + run, output, lock_path = Path(run).resolve(), Path(output).resolve(), Path(lock_path).resolve() + if output == run or run in output.parents: + raise ValueError("Never write diagnostics inside the frozen parent") + lock = json.loads(lock_path.read_text()) + validate_lock(lock) + config = json.loads((run / "config.json").read_text()) + if ( + config["world"] not in (0, 1) + or config["model"]["width"] not in (256, 768) + or config["seed"] not in (0, 1) + or config["condition"] not in (*CHAINS, "neither") + ): + raise ValueError("The original 24-model development matrix is required") + step = config["study"]["steps"] + if step != 15360 or per_population != 64: + raise ValueError("The parent step and 64+64 recipient budget are fixed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent runtime differs: {key}") + device = torch.device(device) + weights = run / f"model-{step}.pt" + contract = { + "run": str(run), + "step": step, + "world": config["world"], + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "parent_config_sha256": file_sha256(run / "config.json"), + "parent_weights_sha256": file_sha256(weights), + "lock": lock, + "lock_sha256": file_sha256(lock_path), + "sources": _sources(), + "source_site": [0, 2], + "downstream_site": [1, 2], + "rank": RANK, + "per_population": per_population, + "batch_size": batch_size, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": device.type, + "checkpoint_role": "pre_edit_clean_only", + "calibration": "S_union_R_actual_queries_with_self_predicted_membership_groups", + "families": list(FAMILIES), + "arms": list(ARMS), + "transfer_types": list(TRANSFER_TYPES), + "transfer_arms": list(TRANSFER_ARMS), + "wrong_source_rule": "cyclic_previous_query_within_family_no_truth_or_prediction_selection", + "cross_query_reference": "The actual-calibration mean is reused for all query families", + "recovery_source": "Same checkpoint and same query clean post-L1/pos2 target projection", + "rescue_only_role": "No-lesion downstream sham; cannot establish necessity", + "random_recovery": "Random rank32 downstream basis; same-query recovery delta norm", + "rank_failure": "Unavailable, never padded or replaced; report coverage by organization", + "interpretation": ( + "Artificial-lesion behavior recovery; no claim of edit repair " + "or organizational specificity" + ), + } + output.mkdir(parents=True, exist_ok=True) + _freeze_json(output / "contract.json", contract) + complete_path = output / "complete.json" + if complete_path.exists(): + complete = json.loads(complete_path.read_text()) + for name, digest in complete["outputs"].items(): + if file_sha256(output / name) != digest: + raise ValueError(f"Completed diagnostic artifact changed: {name}") + return complete + repository = Path(__file__).resolve().parents[2] + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent generated world changed") + saved = torch.load(weights, map_location="cpu", weights_only=False) + final = json.loads((run / "learning-complete.json").read_text()) + if ( + saved["config"] != config["model"] + or saved["step"] != step + or state_hash(saved["model"]) != final["model_sha256"] + ): + raise ValueError("Parent model identity mismatch") + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + with np.load(run / f"predictions-{step}.npz") as stored: + archived = {key: stored[key] for key in ("prediction", "ended")} + completed = [] + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + reference = run / "edits" / f"{name}-exception-mlp" + with np.load(reference / "sets.npz") as old: + for key in ("E", "replay", "exception"): + if not np.array_equal(old[key], pair[key]): + raise ValueError( + f"Original exception calibration permission changed: {name}/{key}" + ) + if not (reference / "complete.json").exists(): + raise ValueError("Original exception case is incomplete") + completed.append( + run_chain( + model, + world, + chain, + pair, + output / name, + device, + batch_size, + per_population, + archived, + ) + ) + print( + json.dumps({"event": "necessity_chain_complete", "run": str(run), "chain": name}), + flush=True, + ) + if _sources() != contract["sources"]: + raise ValueError("Diagnostic implementation changed during execution") + outputs = scientific_outputs(output) + complete = {"status": "complete", "chains": completed, "outputs": outputs} + write_json(complete_path, complete) + return complete diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..322ecd4a965475d9878cbb14cb7a3eee131cf9ca --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py @@ -0,0 +1,1082 @@ +"""P4 v2: unchanged interventions with explicit local numerical baselines. + +Q is fitted only on actual queries in an archived exception case's S union R, +grouped by the model's own membership predictions. Truth-matched donor queries +are a subsequent diagnostic, never calibration. Restoring a same-query clean +downstream signal tests recovery from an artificial lesion, not edit repair. +""" + +import csv +import json +from pathlib import Path + +import numpy as np +import torch + +from .bios_causal_paths import make_donor_plan +from .bios_cross import CHAINS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_mechanism_interventions import ( + Site, + attach_state_operation, + calibration_plan, + downstream_routing_site, + fit_predicted_group_bases, + match_delta_norm, + projection_component, + query_site_roles, + remove_projection, + restore_projection, + valid_predicted_groups, +) +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import file_sha256 +from .bios_train import precision + +SOURCE = Site(0, 2) +DOWNSTREAM = Site(1, 2) +RANK = 32 +NUMERICAL_POLICY = { + "version": "p4-numerical-policy-v2", + "original_identity_gate": "20608 queries; original order/batch512; exact archive values/EOS", + "subset_baseline": "Same query/order/batch local clean for every causal contrast", + "archive_subset_difference": "All queries and both outputs retained; no exclusions", + "donor_baseline": "Extra clean replay in duplicated recipient order and intervention batch", + "local_sham_and_rescue_only": "Strict exact value/EOS equality; never relaxed", + "restore_reference": "Unchanged v1 first-pass pre-answer source; pass drift remains recorded", + "scientific_design": "Candidate, rank, calibration, intervention, pairing, strata unchanged", + "precision": "Unchanged BF16 autocast; FP32 weights; TF32 allowed as in original training", +} +FAMILIES = ( + "default", + "actual", + "other_chain_default", + "attribute_3", + "attribute_4", + "attribute_5", + "attribute_6", + "membership", + "other_chain_actual", + "group_root", +) +ARMS = ( + "clean", + "sham", + "target_remove", + "random_remove", + "complement_remove", + "rescue_only", + "remove_rescue", + "remove_wrong_source_rescue", + "remove_random_rescue", +) +TRANSFER_TYPES = ( + "different_group_same_actual_different_default", + "different_group_same_default", + "different_group_same_default_same_actual", +) +TRANSFER_ARMS = ( + "sham", + "full_donor", + "full_norm_random", + "projected_target", + "projected_random", + "projected_complement", +) + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen diagnostic contract changed: {path}") + else: + write_json(path, value) + + +def _same_arrays(path, arrays): + if path.exists(): + with np.load(path) as existing: + if set(existing.files) != set(arrays) or any( + not np.array_equal(existing[key], value) for key, value in arrays.items() + ): + raise ValueError(f"Diagnostic plan changed: {path}") + else: + atomic_numpy_save(path, **arrays) + + +def _sources(): + directory = Path(__file__).parent + names = ( + "bios_mechanism_causal_v2.py", + "bios_mechanism_causal.py", + "bios_mechanism_interventions.py", + "bios_causal_paths.py", + "bios_cross.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_path_diagnostics.py", + ) + sources = {name: file_sha256(directory / name) for name in names} + runner = directory.parents[1] / "scripts/analyze_bios_mechanism_causal_v2.py" + sources["runner"] = file_sha256(runner) + return sources + + +def validate_lock(lock): + if (lock.get("mechanism"), lock.get("layer"), lock.get("position")) != ("default_path", 0, 2): + raise ValueError("This runner only instantiates the locked default_path L0/pos2 candidate") + if lock.get("known_only") is not False or not lock.get("locked_at_utc"): + raise ValueError("An all-eligible, timestamped candidate lock is required") + + +def make_probe_plan(world, chain, recipients): + """Same people and fixed queries in every intervention, without knowledge filtering.""" + recipients = np.asarray(recipients, dtype=np.int64) + ids = [ + world.derived_ids[chain, recipients], + world.actual_ids[chain, recipients], + world.derived_ids[1 - chain, recipients], + ] + for relation in (3, 4, 5, 6): + candidates = np.flatnonzero(world.relation == relation) + by_person = np.full(len(world.actual_ids[chain]), -1, dtype=np.int64) + by_person[world.person[candidates]] = candidates + if (by_person[recipients] < 0).any(): + raise ValueError("An independent control query is missing") + ids.append(by_person[recipients]) + ids.extend([world.membership_ids[chain, recipients], world.actual_ids[1 - chain, recipients]]) + person_families = len(ids) + roots = world.root_ids[chain] + query_ids = np.concatenate([*ids, roots]) + return { + "query_id": query_ids, + "person": np.r_[np.tile(recipients, person_families), np.full(len(roots), -1)], + "family": np.r_[ + np.repeat(np.arange(person_families), len(recipients)), + np.full(len(roots), person_families), + ], + # -1 means not applicable; root facts are not ordinary people. + "recipient_old_exception": np.r_[ + np.tile(world.exceptions[chain, recipients].astype(np.int8), person_families), + np.full(len(roots), -1, dtype=np.int8), + ], + "answer": world.answers[query_ids], + } + + +def wrong_source_indices(families): + """Fixed one-person cyclic shift within each family, never chosen by answers.""" + families = np.asarray(families) + index = np.arange(len(families)) + for family in np.unique(families): + selected = np.flatnonzero(families == family) + if len(selected) < 2: + raise ValueError("Wrong-source controls require at least two queries per family") + index[selected] = np.roll(selected, 1) + return index + + +def make_transfer_plan(world, chain, per_population=64): + """Truth matching is restricted to this explicitly labeled offline diagnostic.""" + old = make_donor_plan(world, chain, per_population) + original = old["pair_type"] == 1 + recipients = old["recipient"][original] + train = world.person[world.train_ids[chain]] + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + rng = rng_for(world.seed, 978, chain) + donor_rows = [old["donor"][original]] + count_rows = [old["candidate_count"][original]] + for same_actual in (False, True): + donors, counts = [], [] + for recipient in recipients: + mask = (group[train] != group[recipient]) & (default[train] == default[recipient]) + if same_actual: + mask &= actual[train] == actual[recipient] + candidates = train[mask] + donors.append(rng.choice(candidates) if len(candidates) else -1) + counts.append(len(candidates)) + donor_rows.append(np.asarray(donors)) + count_rows.append(np.asarray(counts)) + donor = np.concatenate(donor_rows).astype(np.int64) + recipient = np.tile(recipients, len(TRANSFER_TYPES)) + safe = np.maximum(donor, 0) + return { + "case_id": np.arange(len(donor)), + "recipient": recipient, + "donor": donor, + "pair_type": np.repeat(np.arange(len(TRANSFER_TYPES)), len(recipients)), + "candidate_count": np.concatenate(count_rows), + "recipient_old_exception": world.exceptions[chain, recipient], + "same_actual": (actual[safe] == actual[recipient]) & (donor >= 0), + "same_default": (default[safe] == default[recipient]) & (donor >= 0), + "recipient_default": default[recipient], + "recipient_actual": actual[recipient], + "donor_default": np.where(donor >= 0, default[safe], -1), + "donor_actual": np.where(donor >= 0, actual[safe], -1), + } + + +def generate_queries( + model, prompts, lengths, device, batch_size=256, *, operations=None, capture_sites=() +): + """Two free generation passes with identical pre-answer operations, no answer input. + + operations(begin,end) returns (label, site, operation) triples. Every operation + returns its intended delta and availability; realized post-cast norms are + measured separately. Both passes are retained so norm matching is auditable. + """ + if len(prompts) == 0 or batch_size < 1: + raise ValueError("Generation needs nonempty queries and a positive batch size") + lengths = np.asarray(lengths) + if prompts.shape != (len(lengths), 5) or not np.isin(lengths, [4, 5]).all(): + raise ValueError("Unexpected symbolic query shape") + arrays = {"prediction": [], "ended": []} + for site in capture_sites: + query_site_roles(lengths, site.position) + arrays[f"state_{site.layer}_{site.position}"] = [] + calls = 0 + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + end = min(begin + batch_size, len(prompts)) + p = torch.as_tensor(prompts[begin:end], device=device) + n = torch.as_tensor(lengths[begin:end], device=device) + hooks, traces, captures = [], {}, {} + try: + for label, site, operation in () if operations is None else operations(begin, end): + query_site_roles(lengths[begin:end], site.position) + + def measured(value, operation=operation): + changed, trace = operation(value) + return changed, {**trace, "realized_delta": changed.float() - value.float()} + + hook, trace = attach_state_operation(model, site, measured) + hooks.append(hook) + traces[label] = trace + for site in capture_sites: + key = f"state_{site.layer}_{site.position}" + captures[key] = [] + + def capture( + _module, _inputs, output, key=key, position=site.position, captures=captures + ): + captures[key].append(output[:, position].detach().float()) + + hooks.append(model.blocks[site.layer].register_forward_hook(capture)) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + calls += 2 + arrays["prediction"].append(first.cpu().numpy()) + arrays["ended"].append(second.eq(EOS).cpu().numpy()) + for key, states in captures.items(): + arrays[key].append(states[0].cpu().numpy()) + drift = torch.linalg.vector_norm(states[1] - states[0], dim=-1) + arrays.setdefault(f"{key}_pass_drift", []).append(drift.cpu().numpy()) + for label, trace in traces.items(): + if len(trace) != 2: + raise ValueError( + "Every intervention must occur in both free-generation passes" + ) + for kind in ("delta", "realized_delta"): + norms = torch.stack( + [torch.linalg.vector_norm(t[kind].float(), dim=-1) for t in trace], + dim=1, + ) + arrays.setdefault(f"{label}_{kind}_norm", []).append(norms.cpu().numpy()) + valid = torch.stack([t["valid"] for t in trace], dim=1) + arrays.setdefault(f"{label}_valid", []).append(valid.cpu().numpy()) + finally: + for hook in hooks: + hook.remove() + result = {key: np.concatenate(value) for key, value in arrays.items()} + result.update( + forward_calls=np.asarray(calls), + forward_examples=np.asarray(2 * len(prompts)), + padded_token_positions=np.asarray(11 * len(prompts)), + logical_token_positions=np.asarray(int((2 * lengths + 1).sum())), + ) + return result + + +def _identity_trace(value): + return value, { + "delta": torch.zeros_like(value, dtype=torch.float32), + "valid": torch.ones(len(value), dtype=torch.bool, device=value.device), + } + + +def lesion_operations( + arm, source_bases, downstream_bases, clean_downstream, wrong_index, seed, device +): + """Return a deterministic batch factory. Wrong-source choice never sees truth.""" + if arm not in ARMS: + raise ValueError("Unknown necessity/restoration arm") + if arm == "clean": + return lambda _begin, _end: [] + if arm == "sham": + return lambda _begin, _end: [("source", SOURCE, _identity_trace)] + source = {key: basis.tensors(device) for key, basis in source_bases.items()} + downstream = ( + None + if downstream_bases is None + else {key: basis.tensors(device) for key, basis in downstream_bases.items()} + ) + needs_downstream = "rescue" in arm + if needs_downstream and downstream is None: + raise ValueError("Downstream basis is unavailable; recovery cannot be estimated") + wrong_index = np.asarray(wrong_index) + if len(wrong_index) != len(clean_downstream): + raise ValueError("Wrong-source plan length mismatch") + coefficients = ( + np.random.default_rng(seed) + .standard_normal((len(clean_downstream), source_bases["random"].rank)) + .astype(np.float32) + ) + + def factory(begin, end): + ops = [] + if arm == "clean": + return ops + if arm == "sham": + return [("source", SOURCE, _identity_trace)] + if arm != "rescue_only": + kind = ( + arm.removesuffix("_remove") + if arm in ("random_remove", "complement_remove") + else "target" + ) + q, mean, _ = source[kind] + tq, tm, _ = source["target"] + + def remove(value): + reference = ( + None + if kind == "target" + else torch.linalg.vector_norm(projection_component(value, tq, tm), dim=-1) + ) + return remove_projection(value, q, mean, reference) + + ops.append(("source", SOURCE, remove)) + if needs_downstream: + clean = torch.as_tensor(clean_downstream[begin:end], device=device) + wrong = torch.as_tensor(clean_downstream[wrong_index[begin:end]], device=device) + tq = downstream["target"][0] + rq = downstream["random"][0] + noise = torch.as_tensor(coefficients[begin:end], device=device) @ rq.T + + def recover(value): + _, same_query_trace = restore_projection(value, clean, tq) + correct_delta = same_query_trace["delta"] + reference = torch.linalg.vector_norm(correct_delta, dim=-1) + if arm == "remove_wrong_source_rescue": + return restore_projection(value, wrong, tq, reference) + if arm == "remove_random_rescue": + delta, valid = match_delta_norm(noise, reference) + return value + delta.to(value.dtype), {"delta": delta, "valid": valid} + return restore_projection(value, clean, tq) + + ops.append(("downstream", DOWNSTREAM, recover)) + return ops + + return factory + + +def transfer_operations(arm, bases, recipient, donor, seed, device): + """A locked-basis manipulation check, never a basis-fitting input.""" + if arm not in TRANSFER_ARMS or recipient.shape != donor.shape: + raise ValueError("Invalid donor manipulation") + if arm.startswith("projected_") and bases is None: + raise ValueError("Projected donor diagnostic requires an available source basis") + full_delta = donor.astype(np.float32) - recipient.astype(np.float32) + if arm == "sham": + delta, valid = np.zeros_like(full_delta), np.ones(len(donor), dtype=bool) + elif arm == "full_donor": + delta, valid = full_delta, np.ones(len(donor), dtype=bool) + else: + if arm == "full_norm_random": + raw = np.random.default_rng(seed).standard_normal(full_delta.shape).astype(np.float32) + reference = np.linalg.norm(full_delta, axis=-1) + else: + tq = bases["target"].q + target_delta = (full_delta @ tq) @ tq.T + reference = np.linalg.norm(target_delta, axis=-1) + q = bases[arm.removeprefix("projected_")].q + raw = (full_delta @ q) @ q.T + matched, available = match_delta_norm(torch.from_numpy(raw), torch.from_numpy(reference)) + delta, valid = matched.numpy(), available.numpy() + + def factory(begin, end): + change = torch.as_tensor(delta[begin:end], device=device) + available = torch.as_tensor(valid[begin:end], device=device) + + def operation(value): + return value + change.to(value.dtype), {"delta": change, "valid": available} + + return [("source", SOURCE, operation)] + + return factory + + +def _availability(arrays): + valid = np.ones(len(arrays["prediction"]), dtype=bool) + for key, value in arrays.items(): + if key.endswith("_valid"): + valid &= value.all(axis=1) + return valid + + +def score_rows(arrays, baseline, plan, arm, labels=FAMILIES, label_key="family"): + """All eligible rows first; original-correct strata remain descriptive only.""" + base_correct = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + correct = (arrays["prediction"] == plan["answer"]) & arrays["ended"] + available = _availability(arrays) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available + n, nb = int(chosen.sum()), int((chosen & base_correct).sum()) + before, after = int((chosen & base_correct).sum()), int((chosen & correct).sum()) + row = { + "arm": arm, + "family": family, + "population": population, + "requested": int(requested.sum()), + "available": n, + "unavailable": int((requested & ~available).sum()), + "baseline_correct": before, + "correct": after, + "accuracy": after / n if n else None, + "delta_accuracy": (after - before) / n if n else None, + "known_became_wrong": int((chosen & base_correct & ~correct).sum()), + "wrong_became_correct": int((chosen & ~base_correct & correct).sum()), + "known_denominator": nb, + "known_retention": int((chosen & base_correct & correct).sum()) / nb + if nb + else None, + "termination_error": int((chosen & ~arrays["ended"]).sum()), + "prediction_changed": int( + ( + chosen + & ( + (arrays["prediction"] != baseline["prediction"]) + | (arrays["ended"] != baseline["ended"]) + ) + ).sum() + ), + } + for label in ("source", "downstream"): + for kind in ("delta", "realized_delta"): + key = f"{label}_{kind}_norm" + row[f"mean_{key}"] = ( + float(arrays[key][chosen, 0].mean()) if n and key in arrays else None + ) + rows.append(row) + return rows + + +def paired_score_rows( + left, right, baseline, plan, left_name, right_name, labels=FAMILIES, label_key="family" +): + """Contrasts use a common availability mask, never unmatched denominators.""" + correct_left = (left["prediction"] == plan["answer"]) & left["ended"] + correct_right = (right["prediction"] == plan["answer"]) & right["ended"] + correct_clean = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + available_left, available_right = _availability(left), _availability(right) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available_left & available_right + n = int(chosen.sum()) + nl, nr = int((chosen & correct_left).sum()), int((chosen & correct_right).sum()) + known_right_wrong = chosen & correct_clean & ~correct_right + denominator = int(known_right_wrong.sum()) + rows.append( + { + "left": left_name, + "right": right_name, + "family": family, + "population": population, + "requested": int(requested.sum()), + "common_available": n, + "left_unavailable": int((requested & ~available_left).sum()), + "right_unavailable": int((requested & ~available_right).sum()), + "left_correct": nl, + "right_correct": nr, + "accuracy_difference": (nl - nr) / n if n else None, + "right_wrong_left_correct": int((chosen & ~correct_right & correct_left).sum()), + "right_correct_left_wrong": int((chosen & correct_right & ~correct_left).sum()), + "original_known_right_wrong": denominator, + "original_known_right_wrong_left_recovered": int( + (known_right_wrong & correct_left).sum() + ), + "conditional_recovery_auxiliary": int((known_right_wrong & correct_left).sum()) + / denominator + if denominator + else None, + } + ) + return rows + + +def _check_predictions(generated, archived, ids): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], archived[key][ids]): + raise ValueError(f"Clean frozen-model generation differs from archive: {key}") + + +def record_archive_comparison(path, generated, archived, ids): + """Archive differences are audited, never used for calibration or row selection.""" + ids = np.asarray(ids) + if generated["prediction"].shape != ids.shape or generated["ended"].shape != ids.shape: + raise ValueError("Local generation shape differs from its declared query plan") + if generated["ended"].dtype != bool or archived["ended"].dtype != bool: + raise ValueError("Archive and local termination masks must be boolean") + _same_arrays( + path, + { + "query_id": ids, + "local_prediction": generated["prediction"], + "local_ended": generated["ended"], + "archive_prediction": archived["prediction"][ids], + "archive_ended": archived["ended"][ids], + "prediction_changed": generated["prediction"] != archived["prediction"][ids], + "ended_changed": generated["ended"] != archived["ended"][ids], + }, + ) + + +def verify_original_replay(model, world, archived, output, device): + """Strong identity/numerical gate; original query order and batch remain exact.""" + ids = np.arange(len(world.answers)) + replay = _cached_generate(output / "original-replay.npz", model, world, ids, device, 512) + _check_predictions(replay, archived, ids) + _freeze_json( + output / "original-replay.json", + { + "status": "exact_archive_value_and_EOS_replay", + "queries": len(ids), + "batch_size": 512, + "prediction_differences": 0, + "ended_differences": 0, + "extra_identity_gate_cost": _cost(replay), + "raw_sha256": file_sha256(output / "original-replay.npz"), + }, + ) + return replay + + +def _cost(arrays): + return { + key: int(arrays[key]) + for key in ( + "forward_calls", + "forward_examples", + "padded_token_positions", + "logical_token_positions", + ) + } + + +def _cached_generate(path, model, world, ids, device, batch_size, **kwargs): + if path.exists(): + with np.load(path) as stored: + result = dict(stored) + if not np.array_equal(result.pop("query_id"), ids): + raise ValueError("Cached generation query plan differs") + return result + result = generate_queries( + model, world.prompts[ids], world.lengths[ids], device, batch_size, **kwargs + ) + atomic_numpy_save(path, query_id=ids, **result) + return result + + +def _fit_chain(model, world, chain, pair, dest, device, batch_size, archived): + plan = calibration_plan( + world.actual_ids[chain], + world.person, + world.membership_ids[chain], + pair["E"], + pair["replay"], + ) + _same_arrays( + dest / "calibration-plan.npz", {key: np.asarray(value) for key, value in plan.items()} + ) + actual = _cached_generate( + dest / "calibration-actual.npz", + model, + world, + plan["actual_query_ids"], + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + membership = _cached_generate( + dest / "calibration-membership.npz", + model, + world, + plan["membership_query_ids"], + device, + batch_size, + ) + record_archive_comparison( + dest / "archive-calibration-actual.npz", actual, archived, plan["actual_query_ids"] + ) + record_archive_comparison( + dest / "archive-calibration-membership.npz", + membership, + archived, + plan["membership_query_ids"], + ) + prefix = f"{CHAINS[chain]}:" + allowed = np.array( + [i for i, label in enumerate(world.token_labels) if label.startswith(prefix)] + ) + groups, valid = valid_predicted_groups(membership["prediction"], membership["ended"], allowed) + _same_arrays(dest / "self-predicted-groups.npz", {"prediction": groups, "valid": valid}) + bases, reports, basis_arrays = {}, {}, {} + for label, site in (("source", SOURCE), ("downstream", DOWNSTREAM)): + basis, report = fit_predicted_group_bases( + actual[f"state_{site.layer}_{site.position}"], groups, valid, rank=RANK, seed=74 + chain + ) + bases[label], reports[label] = basis, report + if basis is not None: + for kind, value in basis.items(): + for field in ("q", "mean", "scale"): + basis_arrays[f"{label}_{kind}_{field}"] = getattr(value, field) + _same_arrays(dest / "bases.npz", basis_arrays) + information = { + "S_count": len(pair["E"]), + "R_count": len(pair["replay"]), + "actual_queries": len(plan["actual_query_ids"]), + "additional_membership_queries": len(plan["membership_query_ids"]), + "derived_calibration_queries": 0, + "true_memberships_supplied": False, + "membership_syntax_rule": prefix, + "invalid_groups_never_replaced": True, + "calibration_cost": {"actual": _cost(actual), "membership": _cost(membership)}, + "basis_reports": reports, + "variant": "group_means", + "basis_sha256": file_sha256(dest / "bases.npz"), + } + _freeze_json(dest / "calibration.json", information) + # Truth is read only after Q and its information contract are frozen. These + # labels score calibration quality; they never select rows or alter Q. + membership_correct = ( + membership["prediction"] == world.answers[plan["membership_query_ids"]] + ) & membership["ended"] + _freeze_json( + dest / "calibration-diagnostics.json", + { + "role": "offline scoring after frozen Q; never fitting or row selection", + "queries": len(groups), + "valid_predictions": int(valid.sum()), + "valid_rate": float(valid.mean()), + "correct_predictions": int(membership_correct.sum()), + "accuracy": float(membership_correct.mean()), + "accuracy_given_valid_auxiliary": float(membership_correct[valid].mean()) + if valid.any() + else None, + "basis_sha256": information["basis_sha256"], + }, + ) + return bases + + +def run_chain(model, world, chain, pair, dest, device, batch_size, per_population, archived): + dest.mkdir(parents=True, exist_ok=True) + bases = _fit_chain(model, world, chain, pair, dest, device, batch_size, archived) + transfer = make_transfer_plan(world, chain, per_population) + _same_arrays(dest / "transfer-plan.npz", transfer) + recipients = transfer["recipient"][transfer["pair_type"] == 0] + plan = make_probe_plan(world, chain, recipients) + plan["wrong_source_index"] = wrong_source_indices(plan["family"]) + plan["wrong_source_query_id"] = plan["query_id"][plan["wrong_source_index"]] + plan["wrong_source_same_answer"] = plan["answer"] == plan["answer"][plan["wrong_source_index"]] + _same_arrays(dest / "probe-plan.npz", plan) + ids = plan["query_id"] + query_site_roles(world.lengths[ids], SOURCE.position) + if downstream_routing_site(SOURCE, len(model.blocks), world.lengths[ids] - 1) != DOWNSTREAM: + raise ValueError("Candidate/downstream site mismatch") + clean = _cached_generate( + dest / "clean.npz", + model, + world, + ids, + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + record_archive_comparison(dest / "archive-probe-clean.npz", clean, archived, ids) + rows, states, costs, arm_arrays = [], {}, {"clean": _cost(clean)}, {} + clean_down = clean[f"state_{DOWNSTREAM.layer}_{DOWNSTREAM.position}"] + for arm in ARMS: + if arm not in ("clean", "sham") and bases["source"] is None: + states[arm] = "unavailable_source_rank" + continue + if "rescue" in arm and bases["downstream"] is None: + states[arm] = "unavailable_downstream_rank" + continue + if arm == "clean": + generated = clean + else: + operations = lesion_operations( + arm, + bases["source"], + bases["downstream"], + clean_down, + plan["wrong_source_index"], + [world.seed, 979, chain], + device, + ) + generated = _cached_generate( + dest / f"{arm}.npz", model, world, ids, device, batch_size, operations=operations + ) + if arm in ("sham", "rescue_only"): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], clean[key]): + raise ValueError(f"No-lesion control changed output: {arm}/{key}") + rows.extend(score_rows(generated, clean, plan, arm)) + costs[arm], states[arm] = _cost(generated), "complete" + arm_arrays[arm] = generated + comparisons = [ + (arm, "clean") + for arm in ("sham", "target_remove", "random_remove", "complement_remove", "rescue_only") + ] + comparisons += [("target_remove", arm) for arm in ("random_remove", "complement_remove")] + comparisons += [ + (arm, "target_remove") + for arm in ("remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue") + ] + comparisons += [ + ("remove_rescue", arm) for arm in ("remove_wrong_source_rescue", "remove_random_rescue") + ] + paired_rows = [] + for left, right in comparisons: + if left in arm_arrays and right in arm_arrays: + paired_rows.extend( + paired_score_rows(arm_arrays[left], arm_arrays[right], clean, plan, left, right) + ) + # Donor activations are read only after both bases and their provenance are frozen. + valid = transfer["donor"] >= 0 + selected = {key: value[valid] for key, value in transfer.items()} + people = np.unique(np.r_[selected["recipient"], selected["donor"]]) + donor_ids = world.derived_ids[chain, people] + donor_clean = _cached_generate( + dest / "transfer-clean.npz", + model, + world, + donor_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + record_archive_comparison(dest / "archive-transfer-cache.npz", donor_clean, archived, donor_ids) + ri, di = ( + np.searchsorted(people, selected["recipient"]), + np.searchsorted(people, selected["donor"]), + ) + source_state = donor_clean[f"state_{SOURCE.layer}_{SOURCE.position}"] + # v2: the causal baseline has exactly the intervention query order and batch shape. + # The donor/recipient source cache and intervention delta definitions stay unchanged. + local_ids = world.derived_ids[chain, selected["recipient"]] + transfer_local = _cached_generate( + dest / "transfer-local-clean.npz", + model, + world, + local_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + record_archive_comparison( + dest / "archive-transfer-local-clean.npz", transfer_local, archived, local_ids + ) + _same_arrays( + dest / "transfer-reference-drift.npz", + { + "query_id": local_ids, + "cache_vs_local_state_norm": np.linalg.norm( + source_state[ri] - transfer_local["state_0_2"], axis=1 + ), + "cache_prediction": donor_clean["prediction"][ri], + "cache_ended": donor_clean["ended"][ri], + "local_prediction": transfer_local["prediction"], + "local_ended": transfer_local["ended"], + }, + ) + donor_baseline = {key: transfer_local[key] for key in ("prediction", "ended")} + donor_plan = {**selected, "answer": selected["recipient_default"]} + transfer_rows, transfer_status = [], {} + costs["transfer_clean"] = _cost(donor_clean) + costs["transfer_local_clean"] = _cost(transfer_local) + for arm in TRANSFER_ARMS: + if arm.startswith("projected_") and bases["source"] is None: + transfer_status[arm] = "unavailable_source_rank" + continue + ops = transfer_operations( + arm, + bases["source"], + source_state[ri], + source_state[di], + [world.seed, 980, chain], + device, + ) + generated = _cached_generate( + dest / f"transfer-{arm}.npz", + model, + world, + world.derived_ids[chain, selected["recipient"]], + device, + batch_size, + operations=ops, + ) + if arm == "sham": + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], donor_baseline[key]): + raise ValueError("Transfer sham changed output") + scored = score_rows( + generated, donor_baseline, donor_plan, arm, labels=TRANSFER_TYPES, label_key="pair_type" + ) + for row in scored: + code = TRANSFER_TYPES.index(row["family"]) + chosen = (selected["pair_type"] == code) & _availability(generated) + requested = transfer["pair_type"] == code + if row["population"] != "all": + exception = row["population"] == "old_exception" + chosen &= selected["recipient_old_exception"] == exception + requested &= transfer["recipient_old_exception"] == exception + row["plan_requested"] = int(requested.sum()) + row["missing_donors"] = int((requested & ~valid).sum()) + for role in ("recipient_actual", "donor_default", "donor_actual"): + matched = (generated["prediction"] == selected[role]) & generated["ended"] + base_matched = (donor_baseline["prediction"] == selected[role]) & donor_baseline[ + "ended" + ] + row[f"matches_{role}"] = int((chosen & matched).sum()) + row[f"baseline_matches_{role}"] = int((chosen & base_matched).sum()) + # Donor's own clean response is descriptive, not an eligibility filter. + row["donor_answered_default"] = int( + ( + chosen + & donor_clean["ended"][di] + & (donor_clean["prediction"][di] == selected["donor_default"]) + ).sum() + ) + transfer_rows.extend(scored) + transfer_status[arm], costs[f"transfer_{arm}"] = "complete", _cost(generated) + for filename, contents in ( + ("necessity.csv", rows), + ("paired-necessity.csv", paired_rows), + ("transfer.csv", transfer_rows), + ): + with (dest / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + dest / "status.json", + { + "arms": states, + "transfer_arms": transfer_status, + "evaluation_cost": costs, + "information_boundary": "truth-matched donor states are diagnostic only", + }, + ) + archive_rows = {} + for path in sorted(dest.glob("archive-*.npz")): + with np.load(path) as comparison: + archive_rows[path.stem] = { + "queries": len(comparison["query_id"]), + "prediction_differences": int(comparison["prediction_changed"].sum()), + "ended_differences": int(comparison["ended_changed"].sum()), + "case_exclusion": False, + } + write_json(dest / "archive-discrepancies.json", archive_rows) + return {"chain": CHAINS[chain], "arms": states, "transfer_arms": transfer_status} + + +def scientific_outputs(output): + """Seal only producer-owned artifacts, excluding mutable queue logs and locks.""" + names = { + "archive-calibration-actual.npz", + "archive-calibration-membership.npz", + "archive-probe-clean.npz", + "archive-transfer-cache.npz", + "archive-transfer-local-clean.npz", + "archive-discrepancies.json", + "transfer-local-clean.npz", + "transfer-reference-drift.npz", + "calibration-plan.npz", + "calibration-actual.npz", + "calibration-membership.npz", + "self-predicted-groups.npz", + "bases.npz", + "calibration.json", + "calibration-diagnostics.json", + "transfer-plan.npz", + "probe-plan.npz", + "transfer-clean.npz", + "necessity.csv", + "paired-necessity.csv", + "transfer.csv", + "status.json", + } + names.update(f"{arm}.npz" for arm in ARMS) + names.update(f"transfer-{arm}.npz" for arm in TRANSFER_ARMS) + paths = [ + output / "contract.json", + output / "original-replay.npz", + output / "original-replay.json", + ] + for chain in CHAINS: + paths.extend( + output / chain / name for name in sorted(names) if (output / chain / name).exists() + ) + return {str(path.relative_to(output)): file_sha256(path) for path in paths} + + +def run_model(run, output, lock_path, *, device="cuda", batch_size=256, per_population=64): + """One original pre-edit checkpoint, both chains; separate outputs, restartable nodes.""" + run, output, lock_path = Path(run).resolve(), Path(output).resolve(), Path(lock_path).resolve() + if output == run or run in output.parents: + raise ValueError("Never write diagnostics inside the frozen parent") + lock = json.loads(lock_path.read_text()) + validate_lock(lock) + config = json.loads((run / "config.json").read_text()) + if ( + config["world"] not in (0, 1) + or config["model"]["width"] not in (256, 768) + or config["seed"] not in (0, 1) + or config["condition"] not in (*CHAINS, "neither") + ): + raise ValueError("The original 24-model development matrix is required") + step = config["study"]["steps"] + if step != 15360 or per_population != 64: + raise ValueError("The parent step and 64+64 recipient budget are fixed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent runtime differs: {key}") + device = torch.device(device) + weights = run / f"model-{step}.pt" + contract = { + "numerical_policy": NUMERICAL_POLICY, + "run": str(run), + "step": step, + "world": config["world"], + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "parent_config_sha256": file_sha256(run / "config.json"), + "parent_weights_sha256": file_sha256(weights), + "lock": lock, + "lock_sha256": file_sha256(lock_path), + "sources": _sources(), + "source_site": [0, 2], + "downstream_site": [1, 2], + "rank": RANK, + "per_population": per_population, + "batch_size": batch_size, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": device.type, + "checkpoint_role": "pre_edit_clean_only", + "calibration": "S_union_R_actual_queries_with_self_predicted_membership_groups", + "families": list(FAMILIES), + "arms": list(ARMS), + "transfer_types": list(TRANSFER_TYPES), + "transfer_arms": list(TRANSFER_ARMS), + "wrong_source_rule": "cyclic_previous_query_within_family_no_truth_or_prediction_selection", + "cross_query_reference": "The actual-calibration mean is reused for all query families", + "recovery_source": "Same checkpoint and same query clean post-L1/pos2 target projection", + "rescue_only_role": "No-lesion downstream sham; cannot establish necessity", + "random_recovery": "Random rank32 downstream basis; same-query recovery delta norm", + "rank_failure": "Unavailable, never padded or replaced; report coverage by organization", + "interpretation": ( + "Artificial-lesion behavior recovery; no claim of edit repair " + "or organizational specificity" + ), + } + output.mkdir(parents=True, exist_ok=True) + _freeze_json(output / "contract.json", contract) + complete_path = output / "complete.json" + if complete_path.exists(): + complete = json.loads(complete_path.read_text()) + for name, digest in complete["outputs"].items(): + if file_sha256(output / name) != digest: + raise ValueError(f"Completed diagnostic artifact changed: {name}") + return complete + repository = Path(__file__).resolve().parents[2] + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent generated world changed") + saved = torch.load(weights, map_location="cpu", weights_only=False) + final = json.loads((run / "learning-complete.json").read_text()) + if ( + saved["config"] != config["model"] + or saved["step"] != step + or state_hash(saved["model"]) != final["model_sha256"] + ): + raise ValueError("Parent model identity mismatch") + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + with np.load(run / f"predictions-{step}.npz") as stored: + archived = {key: stored[key] for key in ("prediction", "ended")} + verify_original_replay(model, world, archived, output, device) + completed = [] + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + reference = run / "edits" / f"{name}-exception-mlp" + with np.load(reference / "sets.npz") as old: + for key in ("E", "replay", "exception"): + if not np.array_equal(old[key], pair[key]): + raise ValueError( + f"Original exception calibration permission changed: {name}/{key}" + ) + if not (reference / "complete.json").exists(): + raise ValueError("Original exception case is incomplete") + completed.append( + run_chain( + model, + world, + chain, + pair, + output / name, + device, + batch_size, + per_population, + archived, + ) + ) + print( + json.dumps({"event": "necessity_chain_complete", "run": str(run), "chain": name}), + flush=True, + ) + if _sources() != contract["sources"]: + raise ValueError("Diagnostic implementation changed during execution") + outputs = scientific_outputs(output) + complete = {"status": "complete", "chains": completed, "outputs": outputs} + write_json(complete_path, complete) + return complete diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_mechanism_edit.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_mechanism_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..6e51c693528d73250f62b70686f96b42b7eb9e4f --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_mechanism_edit.py @@ -0,0 +1,611 @@ +"""P1 counterfactual edits with frozen parent models and exact restart state. + +The supervised pool S is fixed at 93 facts. E_changed, propagation D, and +unchanged U are recomputed from each arm's truth, independently of that pool. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_cross_train import evaluate, tensor_queries +from .bios_cross_train import source_hashes as parent_source_hashes +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +ARMS = ("old-fact-rehearsal", "root-only", "actual-only", "class-balanced-exception") +OPTIONAL_ARM = "all-freeze-embedding" +REFERENCE_ARMS = ("coherent", "exception") +DEFAULT_STUDY = { + "protocol": "v2.8-development-mechanism-P1", + "widths": [256, 768], + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "arms": list(ARMS), + "edit_steps": 512, + "edit_checkpoints": [0, 32, 128, 512], + "edit_lr": 3e-5, + "retention_kl": 1.0, + "batch_size": 128, + "save_every": 32, + "gradient_steps": [0, 31, 127, 511], +} + + +def load_study(path=None, arms=None): + study = json.loads(json.dumps(DEFAULT_STUDY)) + if path: + supplied = json.loads(Path(path).read_text()) + unknown = set(supplied) - set(study) + if unknown: + raise ValueError(f"Unknown P1 configuration keys: {sorted(unknown)}") + study.update(supplied) + if arms is not None: + study["arms"] = list(arms) + if not study["arms"] or len(set(study["arms"])) != len(study["arms"]): + raise ValueError("At least one unique arm is required") + if set(study["arms"]) - set((*ARMS, OPTIONAL_ARM)): + raise ValueError("Unknown P1 arm") + if study["edit_steps"] < 1 or study["batch_size"] != 128 or study["save_every"] < 1: + raise ValueError("Positive budgets and the original batch size 128 are required") + checkpoints = study["edit_checkpoints"] + if not checkpoints or checkpoints != sorted(set(checkpoints)) or checkpoints[0] != 0: + raise ValueError("Checkpoints must be unique, ordered, and include zero") + if checkpoints[-1] != study["edit_steps"]: + raise ValueError("The final checkpoint must equal the fixed edit budget") + if study["edit_lr"] <= 0 or study["retention_kl"] < 0: + raise ValueError("Invalid optimization settings") + for key in ("widths", "worlds", "seeds", "conditions"): + if not study[key] or len(set(study[key])) != len(study[key]): + raise ValueError(f"Nonempty, unique matrix entries required: {key}") + if set(study["conditions"]) - set(CONDITIONS): + raise ValueError("Unknown organization condition") + return study + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def source_hashes(): + result = parent_source_hashes() + result[Path(__file__).name] = file_hash(__file__) + runner = Path(__file__).resolve().parents[2] / "scripts/run_bios_mechanism_edit.py" + result[runner.name] = file_hash(runner) + return result + + +def sampling_streams(world, chain, steps=512, batch_size=128): + """Match the original generator, including the order of its two draws.""" + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + supervised = rng.integers(len(pair["E"]), size=(steps, batch_size)) + replay = rng.integers(len(pair["replay"]), size=(steps, batch_size)) + return supervised, replay + + +def make_arm(world, chain, arm, pair=None): + if arm not in (*ARMS, OPTIONAL_ARM, *REFERENCE_ARMS): + raise ValueError(f"Unknown arm: {arm}") + pair = edit_pair(world, chain) if pair is None else pair + supervised = pair["E"].copy() + root = np.intersect1d(supervised, world.root_ids[chain]) + actual = np.intersect1d(supervised, world.actual_ids[chain]) + assert (len(supervised), len(root), len(actual)) == (93, 3, 90) + target = world.answers.copy() + if arm == "root-only": + target[root] = pair["exception"][root] + elif arm == "actual-only": + target[actual] = pair["exception"][actual] + elif arm in ("exception", "class-balanced-exception", OPTIONAL_ARM): + target[supervised] = pair["exception"][supervised] + elif arm == "coherent": + target[supervised] = pair["coherent"][supervised] + # Recompute derived truth, rather than copying the original D declaration. + for task in range(2): + target[world.derived_ids[task]] = target[world.root_ids[task, world.memberships[task]]] + changed = target != world.answers + e = np.flatnonzero(changed & (world.relation < 10)) + d = np.flatnonzero(changed & (world.relation >= 10)) + u = np.flatnonzero(~changed) + if not np.isin(e, supervised).all() or not np.array_equal( + target[pair["replay"]], world.answers[pair["replay"]] + ): + raise ValueError("Supervision or common retention pool violates the truth contract") + if np.intersect1d(pair["replay"], supervised).size: + raise ValueError("The replay pool overlaps S") + selected_people = np.isin(world.memberships[chain], pair["groups"]) + selected_facts = (world.person >= 0) & selected_people[np.maximum(world.person, 0)] + old_exceptions = np.zeros(len(world.answers), dtype=bool) + old_exceptions[world.actual_ids[chain, selected_people & world.exceptions[chain]]] = True + relevant = np.isin(world.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(world.answers), -1, dtype=np.int64) + strata[~changed & old_exceptions] = 0 + strata[~changed & selected_facts & ~old_exceptions] = 1 + strata[~changed & ~selected_facts & relevant] = 2 + strata[~changed & ~selected_facts & ~relevant] = 3 + assert np.array_equal(strata >= 0, ~changed) + supervised_unchanged = np.intersect1d(supervised, u) + probe_unchanged = np.intersect1d(pair["D"], u) + supplied = np.union1d(supervised, pair["replay"]) + # Keep the archived heldout pool; add newly unchanged D, which is never trained. + heldout = np.setdiff1d( + np.intersect1d(np.union1d(pair["heldout"], probe_unchanged), u), supplied + ) + weights = np.ones(len(supervised), dtype=np.float64) + root_mask = np.isin(supervised, root) + if arm == "class-balanced-exception": + weights[root_mask] = len(supervised) / (2 * len(root)) + weights[~root_mask] = len(supervised) / (2 * len(actual)) + return { + "target": target, + "S": supervised, + "S_root": root, + "S_actual": actual, + "S_root_mask": root_mask, + "S_weights": weights, + "E_changed": e, + "E_changed_root": np.intersect1d(e, root), + "E_changed_actual": np.intersect1d(e, actual), + "D": d, + "D_conflict": np.intersect1d(d, pair["conflict_D"]), + "D_probe": pair["D"], + "D_probe_conflict": pair["conflict_D"], + "D_probe_unchanged": probe_unchanged, + "U": u, + "strata": strata, + "heldout": heldout, + "unseen": np.setdiff1d(u, supplied), + "S_unchanged": supervised_unchanged, + "replay": pair["replay"], + "other_chain": np.flatnonzero( + ~changed & np.isin(world.relation, [7, 8, 9, 11] if chain == 0 else [0, 1, 2, 10]) + ), + "independent": np.flatnonzero(~changed & np.isin(world.relation, [3, 4, 5, 6])), + "groups": pair["groups"], + } + + +def accuracy(correct, ids): + return { + "n": len(ids), + "correct": int(correct[ids].sum()), + "accuracy": float(correct[ids].mean()) if len(ids) else None, + } + + +def retention(correct, old_correct, ids): + known = ids[old_correct[ids]] + broken = int((~correct[known]).sum()) + return { + "n": len(ids), + "known": len(known), + "unknown": len(ids) - len(known), + "broken": broken, + "rate": broken / len(known) if len(known) else None, + } + + +def arm_metrics(world, spec, arrays, old_correct): + correct = arrays["correct"] + result = { + name: accuracy(correct, spec[name]) + for name in ( + "S", + "S_root", + "S_actual", + "E_changed", + "E_changed_root", + "E_changed_actual", + "D", + "D_conflict", + "D_probe", + ) + } + for name in ("D", "D_conflict", "D_probe", "D_probe_conflict"): + for split, pool in (("trained", world.train_ids), ("heldout", world.heldout_ids)): + result[f"{name}_{split}"] = accuracy(correct, np.intersect1d(spec[name], pool)) + for name, pool in ( + ("full", spec["U"]), + ("heldout", spec["heldout"]), + ("unseen", spec["unseen"]), + ): + result[f"U_{name}"] = retention(correct, old_correct, pool) + result[f"U_{name}_strata"] = { + str(group): retention( + correct, old_correct, np.intersect1d(pool, np.flatnonzero(spec["strata"] == group)) + ) + for group in range(4) + } + for name in ("S_unchanged", "D_probe_unchanged", "replay", "other_chain", "independent"): + result[f"U_{name}"] = retention(correct, old_correct, spec[name]) + return result + + +def weighted_supervision(logits, labels, weights): + """Average over sampled examples, never renormalize observed class mass.""" + losses = F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), reduction="none") + per_example = losses.reshape(len(labels), -1).mean(-1) + return (per_example * weights).mean(), per_example + + +def select_edit_parameters(model, arm): + if arm != OPTIONAL_ARM: + return select_parameters(model, "mlp", 3) + selected = select_parameters(model, "all") + model.token.weight.requires_grad_(False) + return [parameter for parameter in selected if parameter.requires_grad] + + +def _gradient_norm(loss, selected): + gradients = torch.autograd.grad(loss, selected, retain_graph=True, allow_unused=True) + total = sum(g.detach().float().square().sum() for g in gradients if g is not None) + return float(torch.sqrt(total)) if isinstance(total, torch.Tensor) else 0.0 + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen contract mismatch: {path}") + else: + write_json(path, value) + + +def _contract_hash(contract): + return hashlib.sha256(json.dumps(contract, sort_keys=True).encode()).hexdigest() + + +def _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device): + return { + "model": model.state_dict(), + "config": model.config_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "contract_sha256": _contract_hash(contract), + "timeline": timeline, + "update_stats": stats, + "seconds": seconds, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + } + + +def run_case(model, baseline_state, world, data, old_arrays, chain, arm, dest, study, parent): + """Run or resume one fixed-budget case; no evaluation result changes training.""" + dest = Path(dest) + dest.mkdir(parents=True, exist_ok=True) + device = data["tokens"].device + spec = make_arm(world, chain, arm) + e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"], study["batch_size"]) + contract = { + "parent": parent, + "study": study, + "chain": CHAINS[chain], + "arm": arm, + "sources": source_hashes(), + "sets_sha256": {key: array_hash(value) for key, value in spec.items()}, + "edit_sampling_sha256": array_hash(e_choices), + "replay_sampling_sha256": array_hash(r_choices), + "old_correct_sha256": array_hash(old_arrays["correct"]), + } + _freeze_json(dest / "contract.json", contract) + if (dest / "complete.json").exists(): + completed = json.loads((dest / "complete.json").read_text()) + if completed["contract_sha256"] != _contract_hash(contract): + raise ValueError("Completion contract mismatch") + return completed + model.load_state_dict(baseline_state) + selected = select_edit_parameters(model, arm) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(spec["replay"]), 256): + ids = torch.as_tensor(spec["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + new_data = tensor_queries(world, device, spec["target"]) + atomic_numpy_save( + dest / "sets.npz", + **spec, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, stats, seconds = 0, [], [], 0.0 + resume_path = dest / "resume.pt" + if resume_path.exists(): + state = torch.load(resume_path, map_location="cpu", weights_only=False) + if state["contract_sha256"] != _contract_hash(contract): + raise ValueError("Resume contract mismatch") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + first, timeline, stats, seconds = ( + state["step"], + state["timeline"], + state["update_stats"], + state["seconds"], + ) + if len(stats) != first or first > study["edit_steps"]: + raise ValueError("Invalid restart progress") + torch.set_rng_state(state["torch_rng"]) + if device.type == "cuda": + torch.cuda.set_rng_state(state["cuda_rng"], device) + weights = torch.as_tensor(spec["S_weights"], device=device, dtype=torch.float32) + root_mask = torch.as_tensor(spec["S_root_mask"], device=device) + for step in range(first, study["edit_steps"] + 1): + if step in study["edit_checkpoints"] and not any(p["step"] == step for p in timeline): + arrays = evaluate(model, data, spec["target"]) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + timeline.append( + { + "step": step, + **arm_metrics(world, spec, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + ) + write_json(dest / "trajectory.json", timeline) + if step % study["save_every"] == 0 or step in study["edit_checkpoints"]: + atomic_torch_save( + _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device), + resume_path, + ) + write_json(dest / "update-stats.json", stats) + if step == study["edit_steps"]: + break + model.train() + optimizer.zero_grad(set_to_none=True) + choices = torch.as_tensor(e_choices[step], device=device) + ei = torch.as_tensor(spec["S"][e_choices[step]], device=device) + replay_choices = torch.as_tensor(r_choices[step], device=device) + ri = torch.as_tensor(spec["replay"][r_choices[step]], device=device) + roots = root_mask[choices] + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce, per_example = weighted_supervision(logits, new_data["labels"][ei], weights[choices]) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[replay_choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + study["retention_kl"] * kl + point = { + "step": step + 1, + "root_samples": int(roots.sum()), + "actual_samples": int((~roots).sum()), + "ce": float(ce.detach()), + "kl": float(kl.detach()), + "loss": float(loss.detach()), + } + if step in study["gradient_steps"]: + for name, mask in (("root", roots), ("actual", ~roots)): + component = (per_example * weights[choices] * mask).mean() + point[f"{name}_ce_gradient_norm"] = _gradient_norm(component, selected) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite P1 edit") + point["total_gradient_norm"] = float(norm) + point["gradient_clipped"] = bool(norm > 1) + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + stats.append(point) + if (step + 1) % 128 == 0: + print( + json.dumps({"event": "progress", "case": dest.name, "step": step + 1}), flush=True + ) + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": study["edit_steps"]}, + dest / "model-final.pt", + ) + completed = { + "status": "complete", + "contract_sha256": _contract_hash(contract), + "final_model_sha256": state_hash(model.state_dict()), + "parameters_updated": sum(p.numel() for p in selected), + "final": timeline[-1], + "root_samples": sum(p["root_samples"] for p in stats), + "actual_samples": sum(p["actual_samples"] for p in stats), + "clipped_updates": sum(p["gradient_clipped"] for p in stats), + } + if source_hashes() != contract["sources"]: + raise ValueError("P1 source files changed during this edit") + write_json(dest / "complete.json", completed) + return completed + + +def rescore_references(world, baseline, out, study, old_correct, parent): + """Archive provenance and recompute metrics without mutating historical files.""" + for chain, name in enumerate(CHAINS): + e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"]) + pair = edit_pair(world, chain) + for arm in REFERENCE_ARMS: + source = baseline / "edits" / f"{name}-{arm}-mlp" + spec = make_arm(world, chain, arm, pair) + with np.load(source / "sets.npz") as archived: + for key, expected in ( + ("E", spec["S"]), + ("replay", spec["replay"]), + ("edit_sampling", e_choices), + ("replay_sampling", r_choices), + ("old_correct", old_correct), + (arm, spec["target"]), + ): + if not np.array_equal(archived[key], expected): + raise ValueError(f"Reference reuse contract failed for {source}/{key}") + if not (source / "complete.json").exists(): + raise ValueError(f"Historical reference is incomplete: {source}") + timeline, hashes = [], {} + for step in study["edit_checkpoints"]: + path = source / f"predictions-{step}.npz" + with np.load(path) as stored: + arrays = {key: stored[key] for key in ("prediction", "ended", "correct")} + recomputed = (arrays["prediction"] == spec["target"]) & arrays["ended"] + if not np.array_equal(arrays["correct"], recomputed): + raise ValueError("Historical prediction correctness mismatch") + timeline.append({"step": step, **arm_metrics(world, spec, arrays, old_correct)}) + hashes[path.name] = file_hash(path) + dest = out / "references" / f"{name}-{arm}-mlp" + dest.mkdir(parents=True, exist_ok=True) + _freeze_json( + dest / "contract.json", {"parent": parent, "source": str(source), "files": hashes} + ) + atomic_numpy_save(dest / "sets.npz", **spec, old_correct=old_correct) + write_json(dest / "trajectory.json", timeline) + + +def run_model(baseline, output, study, device): + baseline, output = Path(baseline).resolve(), Path(output).resolve() + if output == baseline or baseline in output.parents: + raise ValueError("P1 results must not be written inside a frozen parent directory") + output.mkdir(parents=True, exist_ok=True) + config_path = baseline / "config.json" + config = json.loads(config_path.read_text()) + if config["sources"] != parent_source_hashes(): + raise ValueError("Frozen parent training sources have changed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent and P1 runtime differ: {key}") + parent_study = config["study"] + for key in ("edit_steps", "edit_checkpoints", "edit_lr", "retention_kl"): + if study[key] != parent_study[key]: + raise ValueError(f"Historical reference configuration differs: {key}") + parent_step = parent_study["steps"] + weights_path = baseline / f"model-{parent_step}.pt" + saved = torch.load(weights_path, map_location="cpu", weights_only=False) + if saved["config"] != config["model"] or saved["step"] != parent_step: + raise ValueError("Parent weight configuration mismatch") + final = json.loads((baseline / "learning-complete.json").read_text()) + if state_hash(saved["model"]) != final["model_sha256"]: + raise ValueError("Parent model state hash mismatch") + world = make_cross_world(config["world"]) + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent world does not match the current generated truth") + parent = { + "directory": str(baseline), + "config_sha256": file_hash(config_path), + "weights_sha256": file_hash(weights_path), + "model_sha256": final["model_sha256"], + "width": config["model"]["width"], + "world": config["world"], + "seed": config["seed"], + "condition": config["condition"], + "step": parent_step, + } + runtime = { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "python": platform.python_version(), + "numpy": np.__version__, + "device_type": device.type, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "precision": "BF16 autocast; FP32 weights and optimizer" + if device.type == "cuda" + else "FP32", + } + contract = {"parent": parent, "study": study, "sources": source_hashes(), "runtime": runtime} + _freeze_json(output / "contract.json", contract) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.cuda.manual_seed_all(config["seed"]) + torch.manual_seed(config["seed"]) + model = CausalLM(ModelConfig(**saved["config"])).to(device) + model.load_state_dict(saved["model"]) + data = tensor_queries(world, device) + old_arrays = evaluate(model, data, world.answers) + with np.load(baseline / f"predictions-{parent_step}.npz") as archived: + for key in ("correct", "prediction", "ended"): + if not np.array_equal(old_arrays[key], archived[key]): + raise ValueError(f"Parent predictions changed under this runtime: {key}") + atomic_numpy_save(output / "baseline-predictions.npz", **old_arrays) + write_json( + output / "runtime.json", + {**runtime, "device": str(device), "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES")}, + ) + rescore_references(world, baseline, output, study, old_arrays["correct"], parent) + completed = [] + for chain, name in enumerate(CHAINS): + for arm in study["arms"]: + dest = output / "edits" / f"{name}-{arm}" + result = run_case( + model, saved["model"], world, data, old_arrays, chain, arm, dest, study, parent + ) + completed.append(f"{name}-{arm}") + write_json( + output / "status.json", + {"state": "running", "complete": completed, "updated": time.time()}, + ) + print( + json.dumps( + {"event": "edit_complete", "case": dest.name, "D": result["final"]["D"]} + ), + flush=True, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "contract_sha256": _contract_hash(contract), + "edit_cases": len(completed), + "cases": completed, + "references": 4, + }, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config") + parser.add_argument("--arms", nargs="+", choices=(*ARMS, OPTIONAL_ARM)) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + args = parser.parse_args() + study = load_study(args.config, args.arms) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + try: + run_model(args.baseline, out, study, torch.device(args.device)) + except Exception as exc: + write_json(out / "failure.json", {"type": type(exc).__name__, "message": str(exc)}) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py new file mode 100644 index 0000000000000000000000000000000000000000..4d87971e01bb7f679239d58f88ea4ac1b054eb88 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py @@ -0,0 +1,375 @@ +"""Uninstantiated P4 projection diagnostics and equal-parameter branches. + +These operators do not choose a real layer, fit a real model's basis, read world +membership truth, or run an experiment. The caller must freeze a candidate and +an information budget first. Group means are not, by themselves, evidence of +an organizational representation. +""" + +from dataclasses import dataclass + +import numpy as np +import torch + + +@dataclass(frozen=True) +class Site: + layer: int + position: int + + +@dataclass(frozen=True) +class Basis: + q: np.ndarray + mean: np.ndarray + scale: np.ndarray + + @property + def rank(self): + return self.q.shape[1] + + def tensors(self, device): + return tuple( + torch.as_tensor(value, dtype=torch.float32, device=device) + for value in (self.q, self.mean, self.scale) + ) + + +def calibration_plan(actual_query_ids, person_by_query, membership_query_ids, supervised, replay): + """Only actual queries in S union R; bridge IDs specify additional self-queries. + + All arguments are query/identity metadata. No group truth or answers are + accepted. In particular this never constructs a derived query to fit Q. + """ + allowed = np.union1d(supervised, replay) + actual = np.intersect1d(actual_query_ids, allowed) + people = np.asarray(person_by_query)[actual] + if (people < 0).any() or len(np.unique(people)) != len(people): + raise ValueError("Calibration must contain one actual query per valid person") + membership = np.asarray(membership_query_ids)[people] + return { + "actual_query_ids": actual, + "person_ids": people, + "membership_query_ids": membership, + "logical_actual_queries": len(actual), + "logical_additional_membership_queries": len(membership), + "derived_calibration_queries": 0, + } + + +def valid_predicted_groups(prediction, ended, allowed_group_tokens): + prediction, ended = np.asarray(prediction), np.asarray(ended) + if prediction.ndim != 1 or ended.shape != prediction.shape or ended.dtype != bool: + raise ValueError("Group predictions require one value and a boolean termination mask") + valid = ended & np.isin(prediction, allowed_group_tokens) + # Invalid predictions are recorded, never replaced with the true group. + return np.where(valid, prediction, -1), valid + + +def _row_span(values, relative_tolerance=1e-6, absolute_tolerance=1e-8): + _, singular, vh = np.linalg.svd(values, full_matrices=False) + threshold = ( + max(absolute_tolerance, relative_tolerance * singular[0]) + if len(singular) + else absolute_tolerance + ) + numerical_rank = int((singular > threshold).sum()) + return vh[:numerical_rank].T, singular, numerical_rank + + +def _orthogonal_residual(values, q): + return values - (values @ q) @ q.T if q.shape[1] else values.copy() + + +def _normalized_basis(q, calibration): + projected = calibration @ q + mean, std = projected.mean(0), projected.std(0) + floor = max(float(np.sqrt(np.mean(std * std))) * 0.01, 1e-8) + std = np.maximum(std, floor) + unit = (projected - mean) / std + total_std = float(np.sqrt(np.mean(np.sum(unit * unit, axis=-1)))) + if not np.isfinite(total_std) or total_std <= 1e-8: + raise ValueError("A nonzero calibration variance is required") + basis = Basis( + q.astype(np.float32), mean.astype(np.float32), (std * total_std).astype(np.float32) + ) + if not np.allclose(basis.q.T @ basis.q, np.eye(q.shape[1]), atol=1e-5): + raise ValueError("The constructed basis is not orthonormal") + return basis + + +def fit_predicted_group_bases( + activations, + predicted_groups, + valid, + *, + rank=32, + seed=74, + variant="group_means", + predicted_answers=None, + answer_valid=None, +): + """Construct a target, orthogonal within-group complement, and random basis. + + Main method input: permitted actual-query states and model-predicted groups. + The optional answer-centered variant is a diagnostic until separately + preregistered. It uses model predictions from those same actual queries; + it does not request default/derived answer truth or extra derived states. + Rank failure returns unavailable; random directions never fill missing rank. + """ + x = np.asarray(activations, dtype=np.float64) + groups, used = np.asarray(predicted_groups), np.asarray(valid).copy() + if x.ndim != 2 or groups.shape != (len(x),) or used.shape != groups.shape or used.dtype != bool: + raise ValueError("Mismatched calibration arrays") + if not np.isfinite(x).all() or rank < 1 or rank > x.shape[1]: + raise ValueError("Finite activations and a feasible positive rank are required") + if (groups[used] < 0).any(): + raise ValueError("Invalid group predictions cannot be marked valid") + if variant not in ("group_means", "answer_centered_diagnostic"): + raise ValueError("Unknown basis variant") + answers = None + if variant == "answer_centered_diagnostic": + if predicted_answers is None or answer_valid is None: + raise ValueError("Answer centering requires model answers and validity flags") + answers, av = np.asarray(predicted_answers), np.asarray(answer_valid) + if answers.shape != groups.shape or av.shape != groups.shape or av.dtype != bool: + raise ValueError("Mismatched predicted answer arrays") + used &= av + report = { + "available": False, + "variant": variant, + "rank_requested": rank, + "calibration_rows": len(x), + "used_rows": int(used.sum()), + "invalid_rows": int((~used).sum()), + "uses_group_truth": False, + "uses_derived_calibration": False, + "random_seed": seed, + } + if not used.any(): + return None, {**report, "reason": "No valid model-predicted calibration groups"} + values, labels = x[used], groups[used] + unique, inverse = np.unique(labels, return_inverse=True) + group_means = np.stack([values[inverse == index].mean(0) for index in range(len(unique))]) + target_matrix = group_means - group_means.mean(0) + answer_span = np.empty((x.shape[1], 0)) + if answers is not None: + answer_labels = answers[used] + answer_means = np.stack( + [values[answer_labels == label].mean(0) for label in np.unique(answer_labels)] + ) + answer_span, _, _ = _row_span(answer_means - answer_means.mean(0)) + target_matrix = _orthogonal_residual(target_matrix, answer_span) + target_span, singular, target_rank = _row_span(target_matrix) + report.update( + predicted_groups=len(unique), + answer_span_rank=answer_span.shape[1], + target_numerical_rank=target_rank, + target_singular_values=singular.tolist(), + ) + if target_rank < rank: + return None, { + **report, + "reason": "Target has fewer than the required independent directions", + } + target = target_span[:, :rank] + residual = values - group_means[inverse] + residual = _orthogonal_residual(_orthogonal_residual(residual, answer_span), target) + complement_span, complement_singular, complement_rank = _row_span(residual) + report.update( + complement_numerical_rank=complement_rank, + complement_singular_values=complement_singular.tolist(), + ) + if complement_rank < rank: + return None, { + **report, + "reason": "Complement has fewer than the required independent directions", + } + if x.shape[1] - answer_span.shape[1] < rank: + return None, {**report, "reason": "Insufficient common admissible dimension"} + random_values = np.random.default_rng(seed).standard_normal((x.shape[1], rank)) + random_values = _orthogonal_residual(random_values.T, answer_span).T + random, triangular = np.linalg.qr(random_values, mode="reduced") + if (np.abs(np.diag(triangular)) < 1e-8).any(): + return None, {**report, "reason": "Random control is numerically rank deficient"} + bases = { + name: _normalized_basis(q, values) + for name, q in ( + ("target", target), + ("complement", complement_span[:, :rank]), + ("random", random), + ) + } + report["normalization"] = { + name: { + "rank": basis.rank, + "total_variance": float( + np.mean(np.sum(((values @ basis.q - basis.mean) / basis.scale) ** 2, axis=1)) + ), + "answer_span_overlap": float(np.linalg.norm(answer_span.T @ basis.q)), + } + for name, basis in bases.items() + } + return bases, {**report, "available": True, "reason": None} + + +def projection_component(values, q, mean): + # Explicit FP32 is necessary: .float() alone does not disable an outer + # autocast context for matrix products in a forward hook. + with torch.autocast(device_type=values.device.type, enabled=False): + return (values.float() @ q.float() - mean.float()) @ q.float().T + + +def match_delta_norm(delta, reference_norms, tolerance=1e-12): + """Zero-length controls with a positive target norm are explicitly unusable.""" + norms = torch.linalg.vector_norm(delta.float(), dim=-1) + reference_norms = torch.as_tensor(reference_norms, dtype=norms.dtype, device=norms.device) + if reference_norms.shape != norms.shape or bool((reference_norms < 0).any()): + raise ValueError("One nonnegative reference norm is required per case") + valid = (norms > tolerance) | (reference_norms <= tolerance) + scale = torch.where( + valid, reference_norms / norms.clamp_min(tolerance), torch.zeros_like(norms) + ) + return delta * scale[:, None], valid + + +def remove_projection(values, q, mean, reference_norms=None): + delta = -projection_component(values, q, mean) + valid = torch.ones(len(values), device=values.device, dtype=torch.bool) + if reference_norms is not None: + delta, valid = match_delta_norm(delta, reference_norms) + return values + delta.to(values.dtype), {"delta": delta, "valid": valid} + + +def restore_projection(values, clean_source, q, reference_norms=None): + """Restore only a fixed later-site projection, not an entire clean activation. + + clean_source must be from the same declared checkpoint and clean query, or + an explicitly labeled wrong-source control. A pre-edit source in an edited + model is a separate diagnostic and may undo the edit; it is never implicit. + """ + if values.shape != clean_source.shape: + raise ValueError("Restoration source and receiving states must have the same shape") + with torch.autocast(device_type=values.device.type, enabled=False): + delta = ((clean_source.float() - values.float()) @ q.float()) @ q.float().T + valid = torch.ones(len(values), device=values.device, dtype=torch.bool) + if reference_norms is not None: + delta, valid = match_delta_norm(delta, reference_norms) + return values + delta.to(values.dtype), {"delta": delta, "valid": valid} + + +def validate_restoration_sites(source, receiver, layers, answer_positions, allow_readout=False): + """A later relational post-block must still have a path to the value readout.""" + if not (0 <= source.layer < receiver.layer < layers): + raise ValueError("Restoration must be at a strictly later block, never the ablation point") + if source.position < 0 or receiver.position < 0: + raise ValueError("Token positions must be nonnegative") + if receiver.position < source.position: + raise ValueError("The receiving token is causally before the source token") + answer_positions = np.asarray(answer_positions) + if (answer_positions < receiver.position).any(): + raise ValueError("The receiving state cannot include an answer token") + if receiver.layer == layers - 1: + if (receiver.position < answer_positions).any(): + raise ValueError("Final-block earlier-token patches cannot affect value readout") + if not allow_readout: + raise ValueError("Final answer-marker restoration is a readout control, not routing") + return {"readout_control": receiver.layer == layers - 1} + + +def downstream_routing_site(source, layers, answer_positions): + """Prespecified L+1/same-token rescue; late candidates have no such rescue.""" + if source.layer > layers - 3: + raise ValueError("This late candidate has no nonterminal same-token routing rescue") + receiver = Site(source.layer + 1, source.position) + validate_restoration_sites(source, receiver, layers, answer_positions) + return receiver + + +def query_site_roles(lengths, position): + lengths = np.asarray(lengths) + if not np.isin(lengths, [4, 5]).all() or position not in (2, 3, 4): + raise ValueError("Only the declared basic/derived symbolic query forms are supported") + if (position >= lengths).any(): + raise ValueError("An intervention cannot use a future answer-token position") + return np.where( + position == lengths - 1, + "answer_marker", + "first_relation" if position == 2 else "second_relation", + ) + + +def attach_state_operation(model, site, operation): + """Attach a batch-local operation; caller supplies fixed source/control states. + + Operations return (new_state, diagnostics). Prompt and EOS passes may use + the same pre-answer operation; future answer tokens must never be sources. + """ + if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: + raise ValueError("Invalid intervention site") + traces = [] + + def intervene(_module, _inputs, output): + if site.position >= output.shape[1]: + raise ValueError("Intervention site is outside this query") + changed, trace = operation(output[:, site.position]) + if changed.shape != output[:, site.position].shape: + raise ValueError("An intervention changed the residual dimension") + result = output.clone() + result[:, site.position] = changed + traces.append(trace) + return result + + return model.blocks[site.layer].register_forward_hook(intervene), traces + + +def attach_equal_branch(model, basis, site, bottleneck=32, seed=73): + """The main experiment adds this branch to a common trainable MLP scope.""" + from .bios_branch import ResidualBranch + + if hasattr(model, "edit_branch"): + raise ValueError("An edit branch is already attached") + if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: + raise ValueError("Invalid branch site") + if site.position not in (2, 3): + raise ValueError("Method branches are restricted to locked relation candidates 2/3") + device = next(model.parameters()).device + branch = ResidualBranch(*basis.tensors(device), width=bottleneck, seed=seed) + model.add_module("edit_branch", branch) + + def add(_module, _inputs, output): + if site.position >= output.shape[1]: + raise ValueError("Branch site is outside this query") + changed = output.clone() + changed[:, site.position] += branch(output[:, site.position]) + return changed + + handle = model.blocks[site.layer].register_forward_hook(add) + expected = bottleneck * (basis.rank + model.config.width) + if sum(parameter.numel() for parameter in branch.parameters()) != expected: + raise ValueError("Unequal branch parameter count") + return branch, handle + + +def select_branch_parameters(model, branch, *, train_common_mlp=True, start=3): + from .bios_model import select_parameters + + if model.edit_branch is not branch: + raise ValueError("The branch is not attached to this model") + if train_common_mlp: + selected = select_parameters(model, "mlp", start) + else: + selected = [] + for parameter in model.parameters(): + parameter.requires_grad_(False) + parameter.grad = None + for parameter in branch.parameters(): + parameter.requires_grad_(True) + parameter.grad = None + selected.append(parameter) + return selected + + +def remove_equal_branch(model, handle): + handle.remove() + delattr(model, "edit_branch") diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_model.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7190d562883dec0d900e7ac14e894975f76499fb --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_model.py @@ -0,0 +1,120 @@ +"""Ordinary causal GPT-2-style language model used by protocol v2.3.""" + +import math +from dataclasses import asdict, dataclass + +import torch +from torch import nn +from torch.nn import functional as F + + +@dataclass(frozen=True) +class ModelConfig: + vocab_size: int + width: int = 768 + layers: int = 8 + heads: int = 12 + context: int = 128 + + +class Attention(nn.Module): + def __init__(self, config): + super().__init__() + self.heads = config.heads + self.qkv = nn.Linear(config.width, 3 * config.width) + self.proj = nn.Linear(config.width, config.width) + + def forward(self, x): + batch, length, width = x.shape + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +class MLP(nn.Module): + def __init__(self, width): + super().__init__() + self.up = nn.Linear(width, 4 * width) + self.activation = nn.GELU(approximate="tanh") + self.down = nn.Linear(4 * width, width) + + def forward(self, x): + return self.down(self.activation(self.up(x))) + + +class Block(nn.Module): + def __init__(self, config): + super().__init__() + self.ln1, self.ln2 = nn.LayerNorm(config.width), nn.LayerNorm(config.width) + self.attention = Attention(config) + self.mlp = MLP(config.width) + + def forward(self, x): + x = x + self.attention(self.ln1(x)) + return x + self.mlp(self.ln2(x)) + + +class CausalLM(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.token = nn.Embedding(config.vocab_size, config.width) + self.position = nn.Embedding(config.context, config.width) + self.blocks = nn.ModuleList([Block(config) for _ in range(config.layers)]) + self.ln_final = nn.LayerNorm(config.width) + self.apply(self._initialize) + for block in self.blocks: + for module in (block.attention.proj, block.mlp.down): + nn.init.normal_(module.weight, std=0.02 / math.sqrt(2 * config.layers)) + + @staticmethod + def _initialize(module): + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, std=0.02) + if isinstance(module, nn.Linear): + nn.init.zeros_(module.bias) + elif isinstance(module, nn.LayerNorm): + nn.init.ones_(module.weight) + nn.init.zeros_(module.bias) + + def forward(self, tokens, positions=None): + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + for block in self.blocks: + x = block(x) + 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 config_dict(self): + return asdict(self.config) + + +def select_parameters(model, scope, start=3): + if scope not in {"all", "mlp", "down"}: + raise ValueError("Scope must be all, mlp or down") + selected = list(model.parameters()) if scope == "all" else [] + if scope == "mlp": + selected = [p for block in model.blocks[start : start + 3] for p in block.mlp.parameters()] + elif scope == "down": + selected = [model.blocks[start + 1].mlp.down.weight] + ids = {id(p) for p in selected} + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) in ids) + parameter.grad = None + return selected + + +def matmul_flops(config, batch, sequence=6, output_positions=2, backward=True): + """Executed-shape dense/attention FLOPs estimate; excludes elementwise operations. + + Multiplication and addition each count as one. Backward uses a factor of two + forwards, a conventional upper approximation also used for frozen parameters. + This is not a hardware counter or a cross-editor exact FLOP measurement. + """ + d, layers, vocab = config.width, config.layers, config.vocab_size + forward = layers * (24 * batch * sequence * d * d + 4 * batch * sequence * sequence * d) + forward += 2 * batch * output_positions * d * vocab + return forward * (3 if backward else 1) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_organization.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_organization.py new file mode 100644 index 0000000000000000000000000000000000000000..a64a674326bdc2e7202a987e0ac941b40640d912 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_organization.py @@ -0,0 +1,256 @@ +"""Equal-presentation bioS corpora differing only in document organization. + +A joins a person's six facts to the true employer default. B keeps the person's +facts together but supplies an unrelated company's default. C keeps B's exact +actual/default pair and moves the other five personal facts to distinct company +origins. No fact is falsified; every condition uses the same presentation pool. +""" + +import numpy as np + +from .bios_data import EOS, N_BASE, N_COMPANIES, N_PEOPLE, RELATIONS, array_hash, rng_for + +CONDITIONS = ("A", "B", "C") +CONDITION_NAMES = {"A": "relation_linked", "B": "person_grouped", "C": "shuffled"} +PERSONAL_RELATIONS = (0, 2, 3, 4, 5, 6) +N_PRESENTATIONS = N_PEOPLE * len(RELATIONS) + + +def _fact_lookup(world): + """Look up fact IDs without depending on the current contiguous numbering.""" + lookup = np.full((7, N_PEOPLE), -1, dtype=np.int64) + for relation in range(7): + ids = np.flatnonzero(world.relation[:N_BASE] == relation) + subjects = world.company[ids] if relation == 1 else world.person[ids] + lookup[relation, subjects] = ids + return lookup + + +def make_documents(world, condition, organization_seed=0): + """Return (2048, 7) fact IDs in canonical relation order. + + Organization is fixed across epochs. Random group ordering and within-group + assignment use a separate seed, shared across all three conditions. C's + seven company origins are distinct, including its unlinked default. + """ + if condition not in CONDITIONS: + raise ValueError(f"Unknown organization condition: {condition}") + if organization_seed < 0: + raise ValueError("organization_seed must be nonnegative") + lookup = _fact_lookup(world) + documents = np.empty((N_PEOPLE, 7), dtype=np.int64) + people = np.arange(N_PEOPLE) + for relation in PERSONAL_RELATIONS: + documents[:, relation] = lookup[relation, people] + documents[:, 1] = lookup[1, world.employers] + if condition == "A": + return documents + + rng = rng_for(world.seed, 101, organization_seed) + members = np.stack( + [rng.permutation(np.flatnonzero(world.employers == c)) for c in range(N_COMPANIES)] + ) + if members.shape != (N_COMPANIES, 32): + raise ValueError("Organization protocol requires 64 companies with 32 people each") + # Independent company cycles per employee-rank lane avoid a stable unrelated + # company partner. Every cycle is a derangement and visits every company. + cycles = np.stack([rng.permutation(N_COMPANIES) for _ in range(32)]) + lane = np.arange(32)[:, None] + anchors = members[cycles, lane] + documents[anchors, 1] = lookup[1, np.roll(cycles, -1, axis=1)] + if condition == "C": + for shift, relation in enumerate((0, 3, 4, 5, 6), start=2): + donor_members = members.copy() + # Each donor person contributes exactly one fact of this relation. + for row in donor_members: + rng.shuffle(row) + donors = donor_members[np.roll(cycles, -shift, axis=1), lane] + documents[anchors, relation] = lookup[relation, donors] + return documents + + +def apply_epoch(documents, world_seed, epoch): + """Apply a shared row permutation and cyclic slot rotation (zero-based epoch). + + Every seven complete epochs, every presentation visits all seven positions. + The permutation depends on the world and epoch, never on the condition. + """ + documents = np.asarray(documents) + if documents.shape != (N_PEOPLE, 7) or epoch < 0: + raise ValueError("Expected canonical (2048, 7) documents and nonnegative epoch") + rows = rng_for(world_seed, 102, epoch).permutation(N_PEOPLE) + return np.roll(documents[rows], epoch % 7, axis=1) + + +def document_epoch(world, condition, epoch, organization_seed=0): + return apply_epoch(make_documents(world, condition, organization_seed), world.seed, epoch) + + +def render_documents(world, ids): + """Render facts with cross-fact causal attention, answer/EOS-only supervision. + + Each row is one document, independently batched; no inter-document attention + is required. Positions select logits that predict the next answer/EOS token. + """ + ids = np.asarray(ids, dtype=np.int64) + if ids.ndim != 2 or ids.shape[1] != 7 or np.any((ids < 0) | (ids >= N_BASE)): + raise ValueError("Expected seven base fact IDs per document") + tokens = np.empty((*ids.shape, 6), dtype=np.int64) + tokens[:, :, :4] = world.prompts[ids, :4] + tokens[:, :, 4] = world.answers[ids] + tokens[:, :, 5] = EOS + positions = (np.arange(7)[:, None] * 6 + np.array([3, 4])).ravel() + labels = np.stack([world.answers[ids], np.full_like(ids, EOS)], axis=-1) + return { + "tokens": tokens.reshape(len(ids), 42), + "positions": np.broadcast_to(positions, (len(ids), 14)).copy(), + "labels": labels.reshape(len(ids), 14), + "fact_ids": ids.copy(), + } + + +def presentation_ids(world, documents): + """Assign each shared presentation to exactly one canonical document slot. + + Personal presentation IDs are 7*person+relation. The 32 default copies use + 7*employee+1, assigned in sorted row order. This assignment is made before + epoch rotation, and permits a fixed text/template for every presentation. + """ + documents = np.asarray(documents, dtype=np.int64) + if documents.shape != (N_PEOPLE, 7): + raise ValueError("Expected canonical (2048, 7) documents") + if not np.all(world.relation[documents] == np.arange(7)): + raise ValueError("Presentation assignment requires canonical relation order") + ids = world.person[documents] * 7 + world.relation[documents] + for company in range(N_COMPANIES): + rows = np.flatnonzero(world.company[documents[:, 1]] == company) + people = np.flatnonzero(world.employers == company) + if len(rows) != len(people): + raise ValueError("Each company default must have 32 presentations") + ids[rows, 1] = people * 7 + 1 + if not np.array_equal(np.sort(ids.ravel()), np.arange(N_PRESENTATIONS)): + raise ValueError("Presentations were lost or duplicated") + return ids + + +def audit_organizations(world, documents): + """Fail on confounds and report the measured organization intervention.""" + if set(documents) != set(CONDITIONS): + raise ValueError("Audit requires A, B and C") + expected_counts = np.where(world.relation[:N_BASE] == 1, 32, 1) + expected_answers = np.bincount( + world.answers[:N_BASE], weights=expected_counts, minlength=world.vocab_size + ).astype(np.int64) + conditions = {} + for condition, ids in documents.items(): + if ids.shape != (N_PEOPLE, 7) or not np.all(world.relation[ids] == np.arange(7)): + raise ValueError("Invalid document shape or relation slots") + counts = np.bincount(ids.ravel(), minlength=N_BASE) + if not np.array_equal(counts, expected_counts): + raise ValueError("Per-fact presentation counts differ") + answers = np.bincount(world.answers[ids].ravel(), minlength=world.vocab_size) + if not np.array_equal(answers, expected_answers): + raise ValueError("Answer-token presentation counts differ") + companies, people = world.company[ids], world.person[ids] + same_company = companies[:, :, None] == companies[:, None, :] + same_person = (people[:, :, None] == people[:, None, :]) & (people[:, :, None] >= 0) + personal = people[:, PERSONAL_RELATIONS] + all_personal_same = np.all(personal == personal[:, :1], axis=1) + if condition in ("A", "B") and not all_personal_same.all(): + raise ValueError("Person aggregation was broken") + if condition == "A" and not np.all(companies == companies[:, :1]): + raise ValueError("A contains a broken employer/default link") + if condition in ("B", "C") and np.any(companies[:, 1] == companies[:, 2]): + raise ValueError("Unrelated default accidentally matches actual person's employer") + if condition == "C" and np.any( + np.sort(companies, axis=1)[:, 1:] == np.sort(companies, axis=1)[:, :-1] + ): + raise ValueError("C contains two facts with the same company origin") + pids = presentation_ids(world, ids) + slots = np.zeros((N_BASE, 7), dtype=np.int64) + for epoch in range(7): + arranged = apply_epoch(ids, world.seed, epoch) + for slot in range(7): + np.add.at(slots[:, slot], arranged[:, slot], 1) + if not np.array_equal(slots, np.repeat(expected_counts[:, None], 7, axis=1)): + raise ValueError("Per-fact positions are not balanced over seven epochs") + default_actual_same = world.answers[ids[:, 1]] == world.answers[ids[:, 2]] + conditions[condition] = { + "name": CONDITION_NAMES[condition], + "documents": len(ids), + "presentations": int(ids.size), + "unique_base_facts": int(np.count_nonzero(counts)), + "document_tokens": 42, + "supervised_tokens_per_document": 14, + "total_input_tokens_per_epoch": int(ids.size * 6), + "total_supervised_tokens_per_epoch": int(ids.size * 2), + "facts_sha256": array_hash(ids), + "presentation_ids_sha256": array_hash(pids), + "exposure_sha256": array_hash(counts), + "answer_histogram_sha256": array_hash(answers), + "seven_epoch_fact_slot_sha256": array_hash(slots), + "company_origin_cooccurrence": same_company.mean(axis=0).tolist(), + "person_origin_cooccurrence": same_person.mean(axis=0).tolist(), + "all_personal_same_fraction": float(all_personal_same.mean()), + "default_actual_same_answer_count": int(default_actual_same.sum()), + "default_actual_same_answer_rate": float(default_actual_same.mean()), + "relation_counts": { + relation: int((world.relation[ids] == i).sum()) + for i, relation in enumerate(RELATIONS) + }, + } + if not np.array_equal(documents["B"][:, 1:3], documents["C"][:, 1:3]): + raise ValueError("B and C must share exactly the same default/actual fact pairs") + return { + "schema": "bios-organization-v1", + "world_seed": world.seed, + "truth_sha256": array_hash(world.answers), + "relation_slot_order": list(RELATIONS), + "same_truth_and_per_fact_presentations": True, + "position_balance_period_epochs": 7, + "same_default_actual_pairs_B_C": True, + "templates_and_aliases": "symbolic tokens fixed; English view uses common presentations", + "conditions": conditions, + } + + +def english_fact(world, fact_id, variant=0): + """Readable supplemental view; this text is not used in symbolic training.""" + if not 0 <= fact_id < N_BASE: + raise ValueError("Expected a base fact") + relation = int(world.relation[fact_id]) + subject = ( + world.names["companies"][int(world.company[fact_id])] + if relation == 1 + else (world.names["people"][int(world.person[fact_id])]) + ) + kind, raw = world.token_labels[int(world.answers[fact_id])].split(":", 1) + fields = { + "company": "companies", + "city": "cities", + "university": "universities", + "major": "majors", + } + value = raw if kind == "date" else world.names[fields[kind]][int(raw)] + templates = ( + ("{s} works for {v}.", "{s}'s employer is {v}.", "{v} employs {s}."), + ( + "{s}'s default work city is {v}.", + "{s} uses {v} as the default work city.", + "The default work city for {s} is {v}.", + ), + ( + "{s}'s actual work city is {v}.", + "{s} actually works in {v}.", + "The actual work city of {s} is {v}.", + ), + ("{s} was born on {v}.", "{s}'s birth date is {v}.", "The birth date of {s} is {v}."), + ("{s} was born in {v}.", "{s}'s birth city is {v}.", "The birth city of {s} is {v}."), + ("{s} attended {v}.", "{s}'s university is {v}.", "{s} studied at {v}."), + ( + "{s} majored in {v}.", + "{s}'s academic major is {v}.", + "The academic major of {s} is {v}.", + ), + ) + return templates[relation][variant % 3].format(s=subject, v=value) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_organization_train.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_organization_train.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5d2bba261629aecc04944afd599bb827c634a8 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_organization_train.py @@ -0,0 +1,521 @@ +"""Matched A/B/C organization training; independent of the legacy SA/AS runs. + +An update contains 16 separate seven-fact causal documents and 28 isolated old +derived queries. Their supervised tokens are weighted 80:20. Each document is +a separate batch row, so attention never crosses document boundaries. +""" + +import argparse +import fcntl +import hashlib +import json +import math +import os +import platform +import random +import time +import traceback +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import ( + N_BASE, + N_PEOPLE, + N_QUERIES, + RELATIONS, + array_hash, + load_world, + rng_for, + write_json, +) +from .bios_model import CausalLM, ModelConfig, matmul_flops +from .bios_organization import apply_epoch, make_documents, render_documents +from .bios_train import code_fingerprint, evaluate, precision, tensor_data + +DOCUMENT_BATCH = 16 +DERIVED_BATCH = 28 +STEPS_PER_EPOCH = N_PEOPLE // DOCUMENT_BATCH +DEFAULT_STEPS = 14336 +WARMUP_EPOCHS = 16 +CHECKPOINTS = (0, 896, 1792, 3584, 7168, 10752, 14336, 21504, 28672) + + +def checkpoint_steps(steps): + if steps < 1: + raise ValueError("steps must be positive") + return sorted({step for step in CHECKPOINTS if step <= steps} | {steps}) + + +def derived_schedule(world_seed, steps, pool=None): + """Condition-independent stream; exhaust each permutation before repeating.""" + rng = rng_for(world_seed, 702) + size = steps * DERIVED_BATCH + pool = np.arange(N_BASE, N_QUERIES) if pool is None else np.asarray(pool) + if not len(pool) or len(np.unique(pool)) != len(pool): + raise ValueError("Derived pool must be nonempty and unique") + if np.any(pool < N_BASE) or np.any(pool >= N_QUERIES): + raise ValueError("Derived pool contains non-derived queries") + cycles = [rng.permutation(pool) for _ in range(math.ceil(size / len(pool)))] + return np.concatenate(cycles)[:size].reshape(steps, DERIVED_BATCH) + + +def learning_rate(step, base_lr): + # A constant rate within each complete epoch also matches per-fact LR exposure. + return base_lr * min((step // STEPS_PER_EPOCH + 1) / WARMUP_EPOCHS, 1.0) + + +def state_hash(state): + digest = hashlib.sha256() + for name, tensor in sorted(state.items()): + value = tensor.detach().cpu().contiguous() + digest.update(name.encode()) + digest.update(str(value.dtype).encode()) + digest.update(str(tuple(value.shape)).encode()) + digest.update(value.numpy().tobytes()) + return digest.hexdigest() + + +def schedule_hash(documents, world_seed, epochs): + digest = hashlib.sha256() + for epoch in range(epochs): + digest.update(np.ascontiguousarray(apply_epoch(documents, world_seed, epoch)).tobytes()) + return digest.hexdigest() + + +def update_flops(config): + return matmul_flops(config, DOCUMENT_BATCH, sequence=42, output_positions=14) + matmul_flops( + config, DERIVED_BATCH, sequence=6, output_positions=2 + ) + + +def two_context_backward(model, documents, isolated, derived_ids, device): + """Compute the exact per-token joint objective without retaining both graphs.""" + with precision(device): + logits = model(documents["tokens"], documents["positions"]) + doc_loss = F.cross_entropy(logits.float().flatten(0, 1), documents["labels"].flatten()) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(isolated["tokens"][derived_ids], isolated["positions"][derived_ids]) + derived_loss = F.cross_entropy( + logits.float().flatten(0, 1), isolated["labels"][derived_ids].flatten() + ) + (0.2 * derived_loss).backward() + return doc_loss.detach(), derived_loss.detach() + + +def atomic_torch_save(value, path): + temporary = path.with_suffix(path.suffix + ".tmp") + torch.save(value, temporary) + os.replace(temporary, path) + + +def atomic_numpy_save(path, **arrays): + temporary = path.with_suffix(path.suffix + ".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def core_sources(): + directory = Path(__file__).resolve().parent + names = ( + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization.py", + "bios_organization_train.py", + ) + return {name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in names} + + +def make_config(args, world, model, documents, derived): + steps = args.steps + epochs = math.ceil(steps / STEPS_PER_EPOCH) + return { + "protocol": "v2.4", + "dataset": "bios-organization-v1", + "phase": "development", + "run_kind": "full" + if steps == DEFAULT_STEPS and (args.width, args.layers, args.heads) == (768, 8, 12) + else "smoke", + "condition": args.condition, + "world_seed": world.seed, + "seed": args.seed, + "organization_seed": args.organization_seed, + "steps": steps, + "model": model.config_dict(), + "parameters": sum(p.numel() for p in model.parameters()), + "model_initial_sha256": state_hash(model.state_dict()), + "lr": args.lr, + "optimizer": "AdamW", + "weight_decay": 0.1, + "gradient_clip_norm": 1.0, + "warmup_epochs": WARMUP_EPOCHS, + "warmup_steps": WARMUP_EPOCHS * STEPS_PER_EPOCH, + "lr_rule": "constant within epoch: base_lr * min((epoch + 1) / 16, 1)", + "documents_per_step": DOCUMENT_BATCH, + "facts_per_document": 7, + "derived_queries_per_step": DERIVED_BATCH, + "document_weight": 0.8, + "derived_weight": 0.2, + "document_shape": {"sequence": 42, "supervised_positions": 14}, + "derived_shape": {"sequence": 6, "supervised_positions": 2}, + "context_objective": "answer+EOS only; same-document preceding facts visible causally", + "isolated_objective": "old-world derived QA only; no supporting document", + "cross_document_attention": False, + "evaluation": "all 14400 isolated queries; greedy value then generated EOS", + "steps_per_epoch": STEPS_PER_EPOCH, + "epochs": steps / STEPS_PER_EPOCH, + "checkpoints": checkpoint_steps(steps), + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "lengths_sha256": array_hash(world.lengths), + "documents_sha256": array_hash(documents), + "document_schedule_sha256": schedule_hash(documents, world.seed, epochs), + "derived_schedule_sha256": array_hash(derived), + "planned_atomic_presentations": steps * 112, + "planned_derived_presentations": steps * 28, + "planned_total_presentations": steps * 140, + "planned_document_presentations": steps * DOCUMENT_BATCH, + "planned_input_tokens_including_padding": steps * (16 * 42 + 28 * 6), + "planned_supervised_tokens": steps * (16 * 14 + 28 * 2), + "planned_train_matmul_flops_estimate": steps * update_flops(model.config), + "flops_method": "executed dense/attention shapes; backward=2x forward; excludes " + "elementwise operations, evaluation, padding-free reinterpretation", + "core_source_sha256": core_sources(), + } + + +def run_locked(args, out): + torch.set_num_threads(args.threads) + torch.manual_seed(args.seed) + random.seed(args.seed) + np.random.seed(args.seed) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + world = load_world(args.world) + documents = make_documents(world, args.condition, args.organization_seed) + from .bios_capacity import qa_split, split_metrics + + split_mode = getattr(args, "qa_split", "all") + train_ids, heldout_ids = qa_split(world, split_mode) + derived = derived_schedule(world.seed, args.steps, train_ids) + model = CausalLM(ModelConfig(world.vocab_size, args.width, args.layers, args.heads)).to(device) + config = make_config(args, world, model, documents, derived) + if getattr(args, "study", "legacy") == "capacity-v1": + config["core_source_sha256"]["bios_capacity.py"] = hashlib.sha256( + Path(__file__).with_name("bios_capacity.py").read_bytes() + ).hexdigest() + config.update( + { + "protocol": "v2.5-development", + "run_kind": "capacity-development", + "qa_split": split_mode, + "qa_train_ids": train_ids.tolist(), + "qa_heldout_ids": heldout_ids.tolist(), + "qa_split_policy": "half within company and old-exception stratum; world seed only", + "evaluation": "all base plus separately reported trained/heldout derived queries", + } + ) + config_path = out / "config.json" + if args.resume: + if not config_path.exists() or not (out / "resume.pt").exists(): + raise ValueError("Resume requires config.json and an atomic resume.pt checkpoint") + original = json.loads(config_path.read_text()) + differences = [key for key, value in config.items() if original.get(key) != value] + if differences: + raise ValueError("Resume configuration mismatch: " + ", ".join(differences)) + elif config_path.exists() or any(out.glob("model-*.pt")) or (out / "resume.pt").exists(): + raise ValueError("Output already contains a run; use a fresh directory or --resume") + else: + config.update( + { + "world": str(Path(args.world).resolve()), + "output": str(out.resolve()), + "execution": { + "device": args.device, + "threads": args.threads, + "torch": torch.__version__, + "python": platform.python_version(), + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast on CUDA; FP32 weights/loss/Adam moments", + "deterministic_algorithms": torch.are_deterministic_algorithms_enabled(), + "allow_tf32": torch.backends.cuda.matmul.allow_tf32, + }, + **code_fingerprint(), + } + ) + write_json(config_path, config) + atomic_numpy_save(out / "schedule.npz", documents=documents, derived=derived) + optimizer = torch.optim.AdamW( + model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + isolated = tensor_data(world, device) + counts = np.zeros(N_QUERIES, dtype=np.int64) + slot_counts = np.zeros((N_BASE, 7), dtype=np.int64) + weighted_exposure = np.zeros(N_QUERIES, dtype=np.float64) + timeline, losses = [], [] + train_seconds, first_step = 0.0, 0 + if args.resume: + state = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if state["config_sha256"] != hashlib.sha256(config_path.read_bytes()).hexdigest(): + raise ValueError("Resume checkpoint configuration fingerprint mismatch") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + torch.set_rng_state(state["torch_rng"]) + if device.type == "cuda" and state["cuda_rng"] is not None: + torch.cuda.set_rng_state(state["cuda_rng"], device) + random.setstate(state["python_rng"]) + np.random.set_state(state["numpy_rng"]) + counts, slot_counts = state["counts"], state["slot_counts"] + weighted_exposure = state["weighted_exposure"] + timeline, train_seconds, first_step = ( + state["timeline"], + state["train_seconds"], + state["step"], + ) + resumes_path = out / "resumes.json" + resumes = json.loads(resumes_path.read_text()) if resumes_path.exists() else [] + resumes.append({"from_step": first_step, "device": args.device, **code_fingerprint()}) + write_json(resumes_path, resumes) + if (out / "failure.json").exists(): + os.replace(out / "failure.json", out / f"failure-before-resume-{len(resumes)}.json") + if device.type == "cuda": + torch.cuda.reset_peak_memory_stats(device) + cached_epoch, cached_documents = None, None + active_step = first_step + try: + for step in range(first_step, args.steps + 1): + active_step = step + if step in checkpoint_steps(args.steps) and not (args.resume and step == first_step): + started = time.perf_counter() + metrics, arrays = evaluate(model, isolated, world, batch_size=args.eval_batch_size) + if getattr(args, "study", "legacy") == "capacity-v1": + metrics.update(split_metrics(world, arrays, train_ids, heldout_ids)) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slot_exposure=slot_counts, + lr_weighted_exposure=weighted_exposure, + ) + atomic_torch_save( + { + "model": { + key: value.detach().cpu() for key, value in model.state_dict().items() + }, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + record = { + "step": step, + "epoch": step / STEPS_PER_EPOCH, + **metrics, + "train_seconds": train_seconds, + "train_matmul_flops_estimate": step * update_flops(model.config), + "presentations": int(counts.sum()), + "document_presentations": step * DOCUMENT_BATCH, + "base_presentations": int(counts[:N_BASE].sum()), + "derived_presentations": int(counts[N_BASE:].sum()), + "coverage_base": float((counts[:N_BASE] > 0).mean()), + "coverage_derived": float((counts[N_BASE:] > 0).mean()), + "world_tokens": int((counts * (world.lengths + 2)).sum()), + "input_tokens_including_padding": step * (16 * 42 + 28 * 6), + "supervised_tokens": step * (16 * 14 + 28 * 2), + "exposure_sha256": array_hash(counts), + "slot_exposure_sha256": array_hash(slot_counts), + "lr_weighted_exposure_sha256": array_hash(weighted_exposure), + "lr_weighted_exposure_by_relation": { + relation: float(weighted_exposure[world.relation == i].sum()) + for i, relation in enumerate((*RELATIONS, "derived")) + }, + "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "eval_and_checkpoint_seconds": time.perf_counter() - started, + "mean_training_loss_since_previous": float(np.mean([x[0] for x in losses])) + if losses + else None, + "mean_context_document_loss": float(np.mean([x[1] for x in losses])) + if losses + else None, + "mean_isolated_derived_loss": float(np.mean([x[2] for x in losses])) + if losses + else None, + } + timeline.append(record) + write_json(out / "learning.json", timeline) + atomic_torch_save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) + if device.type == "cuda" + else None, + "python_rng": random.getstate(), + "numpy_rng": np.random.get_state(), + "timeline": timeline, + "counts": counts, + "slot_counts": slot_counts, + "weighted_exposure": weighted_exposure, + "train_seconds": train_seconds, + "step": step, + "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), + }, + out / "resume.pt", + ) + losses = [] + print( + json.dumps( + { + "event": "checkpoint", + "step": step, + "base": metrics["base_accuracy"], + "derived": metrics["derived_accuracy"], + "train_seconds": train_seconds, + } + ), + flush=True, + ) + if step == args.steps: + break + epoch = step // STEPS_PER_EPOCH + if cached_epoch != epoch: + ordered = apply_epoch(documents, world.seed, epoch) + rendered = render_documents(world, ordered) + # One small epoch tensor transfer; training slices never join documents. + cached_documents = { + key: torch.as_tensor(rendered[key], device=device) + for key in ("tokens", "positions", "labels") + } + cached_epoch = epoch + offset = (step % STEPS_PER_EPOCH) * DOCUMENT_BATCH + batch = { + key: value[offset : offset + DOCUMENT_BATCH] + for key, value in cached_documents.items() + } + fact_ids = ordered[offset : offset + DOCUMENT_BATCH] + derived_ids = torch.as_tensor(derived[step], device=device) + lr = learning_rate(step, args.lr) + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + doc_loss, derived_loss = two_context_backward( + model, batch, isolated, derived_ids, device + ) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(doc_loss + derived_loss) or not torch.isfinite(norm): + raise FloatingPointError("Nonfinite document/derived loss or gradient norm") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - started + dloss, qloss = float(doc_loss), float(derived_loss) + losses.append((0.8 * dloss + 0.2 * qloss, dloss, qloss)) + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, derived[step], 1) + np.add.at(slot_counts, (fact_ids, np.arange(7)[None, :]), 1) + np.add.at(weighted_exposure, fact_ids.ravel(), lr) + np.add.at(weighted_exposure, derived[step], lr) + if (step + 1) % 100 == 0: + print( + json.dumps( + { + "event": "progress", + "step": step + 1, + "epoch": (step + 1) / STEPS_PER_EPOCH, + "loss": float(np.mean([x[0] for x in losses[-100:]])), + "train_seconds": train_seconds, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "step": args.steps, + "status": "complete", + "final": timeline[-1], + "exposure_sha256": array_hash(counts), + "slot_exposure_sha256": array_hash(slot_counts), + "model_final_sha256": state_hash(model.state_dict()), + }, + ) + except BaseException as error: + write_json( + out / "failure.json", + { + "step": active_step, + "reason": str(error), + "type": type(error).__name__, + "traceback": traceback.format_exc(), + "train_seconds": train_seconds, + "last_committed_checkpoint": timeline[-1]["step"] if timeline else None, + }, + ) + raise + + +def train(args): + checkpoint_steps(args.steps) + if ( + getattr(args, "qa_split", "all") != "all" + and getattr(args, "study", "legacy") != "capacity-v1" + ): + raise ValueError("Heldout QA requires explicit capacity study") + if args.width < 1 or args.layers < 1 or args.heads < 1 or args.width % args.heads: + raise ValueError("Model dimensions must be positive and width divisible by heads") + if args.lr <= 0 or not math.isfinite(args.lr): + raise ValueError("Learning rate must be finite and positive") + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".train.lock").open("a") as lock: + try: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as error: + raise RuntimeError("Another process is training in this output directory") from error + run_locked(args, out) + + +def parser(): + result = argparse.ArgumentParser(description=__doc__) + result.add_argument("--world", required=True) + result.add_argument("--output", required=True) + result.add_argument("--condition", choices=("A", "B", "C"), required=True) + result.add_argument("--seed", type=int, default=0) + result.add_argument("--organization-seed", type=int, default=0) + result.add_argument("--steps", type=int, default=DEFAULT_STEPS) + result.add_argument("--lr", type=float, default=1e-4) + result.add_argument("--device", default="cuda") + result.add_argument("--threads", type=int, default=4) + result.add_argument("--eval-batch-size", type=int, default=512) + result.add_argument("--width", type=int, default=768) + result.add_argument("--layers", type=int, default=8) + result.add_argument("--heads", type=int, default=12) + result.add_argument("--study", choices=("legacy", "capacity-v1"), default="legacy") + result.add_argument("--qa-split", choices=("all", "half"), default="all") + result.add_argument("--resume", action="store_true") + return result + + +def main(): + train(parser().parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_data.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_data.py new file mode 100644 index 0000000000000000000000000000000000000000..98352c46d29112ab2ac2be7212204897c13aea18 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_data.py @@ -0,0 +1,455 @@ +"""Pinned six-attribute bioS reconstruction for plan 14.27 (not the old graph).""" + +from __future__ import annotations + +import ast +import calendar +import hashlib +import json +import random +from collections import Counter +from pathlib import Path + +import numpy as np + +SOURCE = Path("data/bios-source") +MATERIAL = SOURCE / "data-synthetic-pretrain/Capo-bioS-bioR" +SOURCE_CODE = MATERIAL / "Capo-bioS-bioR.py" +MONTHS = list(calendar.month_name)[1:] +ATTRS = ("date", "birthcity", "university", "field", "workcity", "company") +TASKS = (*ATTRS, "year", "parity", "company_city", "city_company", "comparison") + +# View 0 of the first six tasks is the question wording in Part 3.1, section 2.2. +# Additional tasks and views are an explicit measurement adaptation. +QUESTIONS = { + "date": [ + "What is the birth date of {n}?", + "On what date was {n} born?", + "Give {n}'s full date of birth.", + "When was {n} born?", + "State the birthday, including the year, of {n}.", + "What is {n}'s complete birth date?", + ], + "birthcity": [ + "What is the birth city of {n}?", + "In which city was {n} born?", + "Give {n}'s city of birth.", + "Where was {n} born?", + "Name the birthplace city of {n}.", + "What city is {n}'s birthplace?", + ], + "university": [ + "Which university did {n} study?", + "Where did {n} attend university?", + "Give the university attended by {n}.", + "At which university did {n} study?", + "Name {n}'s university.", + "What university educated {n}?", + ], + "field": [ + "What major did {n} study?", + "What was {n}'s field of study?", + "Give {n}'s university major.", + "In what subject did {n} major?", + "Name the discipline studied by {n}.", + "Which subject did {n} study at university?", + ], + "company": [ + "Which company did {n} work for?", + "Who was {n}'s employer?", + "Give the company employing {n}.", + "At what company did {n} work?", + "Name {n}'s employer.", + "What is the name of the company where {n} worked?", + ], + "workcity": [ + "Where did {n} work?", + "In which city did {n} work?", + "Give {n}'s work city.", + "What city was {n}'s employer based in?", + "Name the city of {n}'s workplace.", + "What was {n}'s city of employment?", + ], + "year": [ + "What is the birth year of {n}?", + "In which year was {n} born?", + "Give only {n}'s birth year.", + "Name the year in {n}'s date of birth.", + "What year marks {n}'s birth?", + "State the year of birth for {n}.", + ], + "parity": [ + "Was {n} born in an even-numbered month?", + "Is {n}'s birth month number even?", + "Does the month of {n}'s birth have an even number?", + "Is the calendar month when {n} was born even-numbered?", + "For {n}, is the birth month one of months 2, 4, 6, 8, 10, or 12?", + "Is the number of {n}'s birth month divisible by two?", + ], + "company_city": [ + "Give {n}'s company, then work city.", + "Name the employer of {n}, followed by its city.", + "For {n}, list company before workplace city.", + "What company employed {n}, and in what city?", + "State {n}'s company and city, in that order.", + "Report {n}'s employer first and work city second.", + ], + "city_company": [ + "Give {n}'s work city, then company.", + "Name the work city of {n}, followed by the employer.", + "For {n}, list workplace city before company.", + "In what city did {n} work, and for what company?", + "State {n}'s work city and company, in that order.", + "Report {n}'s work city first and employer second.", + ], + "comparison": [ + "Who was born earlier, {a} or {b}?", + "Which was born first: {a} or {b}?", + "Between {a} and {b}, name the older person.", + "Whose date of birth is earlier, {a}'s or {b}'s?", + "Compare the birthdays of {a} and {b}. Who is older?", + "Of {a} and {b}, who has the earlier birthday including the year?", + ], +} + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write_json(path, obj): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(obj, indent=2, ensure_ascii=False) + "\n") + temp.replace(path) + + +def load_json(path): + return json.loads(Path(path).read_text()) + + +def verify_source(): + manifest = load_json("configs/bios-source-manifest.json") + for row in manifest["files"]: + if digest(SOURCE / row["path"]) != row["sha256"]: + raise ValueError(f"Official source changed: {row['path']}") + return manifest + + +def source_templates(): + """Read literal templates without importing or changing the upstream source.""" + tree = ast.parse(SOURCE_CODE.read_text()) + fn = next( + n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "get_text_simple3" + ) + values = {} + for node in fn.body: + if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name): + name = node.targets[0].id + if name.startswith("sentence_structures"): + values[int(name[-1]) - 1] = ast.literal_eval(node.value) + return [values[i] for i in range(6)] + + +def date(p): + return f"{MONTHS[p['month'] - 1]} {p['day']}, {p['year']}" + + +def date_key(p): + return p["year"], p["month"], p["day"] + + +def render_sentences(p, templates, ids, order=range(6)): + fields = dict( + birthday=date(p), + birthcity=p["birthcity"], + university=p["university"], + field=p["field"], + company1city=p["workcity"], + company1name=p["company"], + ) + return [ + " " + templates[a][ids[a]].format(name=p["name"] if j == 0 else p["pronoun"], **fields) + for j, a in enumerate(order) + ] + + +def make_people(seed, count): + if count % 10: + raise ValueError("Population must permit exact 50/10/40 splits") + rng = random.Random(seed) + pools = { + key: (MATERIAL / "fields" / f"{key}.txt").read_text().splitlines() + for key in ( + "first_name", + "middle_name", + "last_name", + "city", + "university", + "field", + "company", + ) + } + names, people = set(), [] + for i in range(count): + while True: + name_ids = [ + rng.randrange(len(pools[k])) for k in ("first_name", "middle_name", "last_name") + ] + name = " ".join( + pools[k][v] + for k, v in zip(("first_name", "middle_name", "last_name"), name_ids, strict=True) + ) + if name not in names: + names.add(name) + break + indices = { + k: rng.randrange(len(pools[k])) for k in ("city", "university", "field", "company") + } + company, city = [s.strip() for s in pools["company"][indices["company"]].split(";", 1)] + people.append( + dict( + id=i, + name=name, + name_ids=name_ids, + attribute_ids=indices, + year=rng.randrange(1900, 2100), + month=rng.randrange(1, 13), + day=rng.randrange(1, 29), + birthcity=pools["city"][indices["city"]], + university=pools["university"][indices["university"]], + field=pools["field"][indices["field"]], + company=company, + workcity=city, + pronoun="He" if i % 2 == 0 else "She", + ) + ) + ids = list(range(count)) + random.Random(seed + 1000000).shuffle(ids) + for j, i in enumerate(ids): + people[i]["split"] = ( + "train" if j < count // 2 else ("dev" if j < 6 * count // 10 else "test") + ) + # One balanced comparison row per person. Both participants stay in the same split. + for split in ("train", "dev", "test"): + indices = [p["id"] for p in people if p["split"] == split] + random.Random(seed + len(indices)).shuffle(indices) + for j in range(0, len(indices), 2): + a, b = indices[j : j + 2] + if date_key(people[a]) == date_key(people[b]): + for k in range(j + 2, len(indices)): + c = indices[k] + if date_key(people[a]) != date_key(people[c]): + indices[j + 1], indices[k] = indices[k], indices[j + 1] + b = c + break + else: + raise ValueError("Equal-date terminal pair; choose a new prespecified seed") + people[a]["partner"] = b + people[b]["partner"] = a + return people + + +def answer(p, task, other=None): + if task == "date": + return date(p) + if task == "year": + return str(p["year"]) + if task == "parity": + return "yes" if p["month"] % 2 == 0 else "no" + if task == "company_city": + return f"{p['company']}; {p['workcity']}" + if task == "city_company": + return f"{p['workcity']}; {p['company']}" + if task == "comparison": + return min((p, other), key=date_key)["name"] + return p[task] + + +def question(p, task, view=0, other=None, cot=False): + q = QUESTIONS[task][view].format(n=p["name"], a=p["name"], b=other["name"] if other else "") + return "Question: " + q + (" Explain briefly." if cot else "") + "\nAnswer:" + + +def reasoning(p, task, other=None): + value = answer(p, task, other) + if task == "parity": + return ( + f"{date(p)}; {MONTHS[p['month'] - 1]} is month {p['month']}; " + f"{p['month']} is {'even' if p['month'] % 2 == 0 else 'odd'}; Answer: {value}" + ) + if task == "comparison": + return f"{p['name']}: {date(p)}; {other['name']}: {date(other)}; Answer: {value}" + if task == "year": + return f"{date(p)}; the year is {p['year']}; Answer: {value}" + if task in ("company_city", "city_company"): + return f"company: {p['company']}; work city: {p['workcity']}; Answer: {value}" + return f"{task}: {value}; Answer: {value}" + + +def edit_cases(people, seed): + rng = random.Random(seed + 3000000) + groups = [ + [p for p in people if p["split"] == "test" and p["month"] % 2 == parity] + for parity in (0, 1) + ] + selected = rng.sample(groups[0], 8) + rng.sample(groups[1], 8) + result = [] + for p in selected: + month = rng.choice([m for m in range(1, 13) if m % 2 != p["month"] % 2]) + year = rng.choice([y for y in range(1900, 2100) if y != p["year"]]) + result.append( + dict( + person_id=p["id"], + old_month=p["month"], + old_year=p["year"], + new_month=month, + new_year=year, + day=p["day"], + cells=[ + dict(month=m, year=y) + for m, y in ( + (p["month"], p["year"]), + (month, p["year"]), + (p["month"], year), + (month, year), + ) + ], + ) + ) + return result + + +def prepare_world(cfg, seed, tokenizer): + root = Path(cfg["data_root"]) / f"world-{seed}" + if (root / "audit.json").exists(): + audit = load_json(root / "audit.json") + for f, h in audit["files"].items(): + if digest(root / f) != h: + raise ValueError(f"Data changed: {root / f}") + return audit + root.mkdir(parents=True, exist_ok=True) + manifest = verify_source() + source_hash = digest(SOURCE_CODE) + templates = source_templates() + people = make_people(seed, cfg["people"]) + write_json(root / "people.json", people) + write_json(root / "edit-cases.json", edit_cases(people, seed)) + write_json(root / "questions.json", QUESTIONS) + rng = random.Random(seed + 2000000) + template_ids = np.empty((len(people), 5, 6), dtype=np.int16) + # Store separately tokenized full-name/pronoun sentences; no splitting at periods. + # This preserves abbreviations in company names and city names. + all_ids, lengths = [], [] + with (root / "biographies.jsonl").open("w") as out: + for p in people: + for variant in range(5): + ids = [rng.randrange(len(t)) for t in templates] + template_ids[p["id"], variant] = ids + sentences = render_sentences(p, templates, ids) + out.write( + json.dumps( + dict( + person_id=p["id"], + variant=variant, + template_ids=ids, + order=list(ATTRS), + source_sha256=source_hash, + text="".join(sentences), + ) + ) + + "\n" + ) + for a in range(6): + # Force this attribute first, and then second, to obtain both name forms. + full = render_sentences(p, templates, ids, [a])[0] + pro = render_sentences(p, templates, ids, [(a + 1) % 6, a])[1] + for text in (full, pro): + enc = tokenizer.encode(text).ids + all_ids.append(enc) + lengths.append(len(enc)) + max_len = max(lengths) + packed = np.zeros((len(all_ids), max_len), dtype=np.uint16) + for i, tokens in enumerate(all_ids): + packed[i, : len(tokens)] = tokens + np.save(root / "sentence-tokens.npy", packed.reshape(len(people), 5, 6, 2, max_len)) + np.save( + root / "sentence-lengths.npy", + np.array(lengths, dtype=np.int16).reshape(len(people), 5, 6, 2), + ) + np.save(root / "template-ids.npy", template_ids) + assert len({p["name"] for p in people}) == len(people) + for p in people: + assert people[p["partner"]]["split"] == p["split"] + assert date_key(p) != date_key(people[p["partner"]]) + counts = Counter(p["split"] for p in people) + for task in TASKS: + assert len(QUESTIONS[task]) == len(set(QUESTIONS[task])) == 6 + files = [ + "people.json", + "edit-cases.json", + "questions.json", + "biographies.jsonl", + "sentence-tokens.npy", + "sentence-lengths.npy", + "template-ids.npy", + ] + audit = dict( + seed=seed, + people=len(people), + splits=dict(counts), + source_revision=manifest["revision"], + source_sha256=digest(SOURCE_CODE), + template_counts=dict(zip(ATTRS, map(len, templates), strict=True)), + variants=5, + facts_per_person=6, + passes=540, + tasks_per_train_person=11, + train_rows=counts["train"] * 11, + qa_training_views=[0], + globally_held_out_views=list(range(1, 6)), + equal_date_comparisons=0, + cross_split_comparisons=0, + comparison_first_answer_fraction={ + s: np.mean( + [date_key(p) < date_key(people[p["partner"]]) for p in people if p["split"] == s] + ).item() + for s in counts + }, + city_collisions=sum(p["birthcity"] == p["workcity"] for p in people), + max_sentence_tokens=max_len, + files={f: digest(root / f) for f in files}, + ) + write_json(root / "audit.json", audit) + return audit + + +class BioStream: + """One deterministic pass presents every person exactly once, including the tail.""" + + def __init__(self, root, seed, condition): + self.tokens = np.load(Path(root) / "sentence-tokens.npy", mmap_mode="r") + self.lengths = np.load(Path(root) / "sentence-lengths.npy", mmap_mode="r") + self.seed, self.condition = seed, condition + self.count = self.tokens.shape[0] + + def pass_tokens(self, epoch): + rng = np.random.default_rng(np.random.SeedSequence([self.seed, epoch, 1427])) + people = rng.permutation(self.count) + stream = [50256] + order_hash = hashlib.sha256() + for pid in people: + variant = 0 if self.condition == "S" else (epoch + int(pid)) % 5 + order = rng.permutation(6) if self.condition == "MP" else np.arange(6) + order_hash.update(np.array([pid, variant, *order], dtype=np.int64).tobytes()) + for j, attr in enumerate(order): + form = int(j != 0) + size = self.lengths[pid, variant, attr, form] + stream.extend(self.tokens[pid, variant, attr, form, :size]) + stream.append(50256) + return np.asarray(stream, dtype=np.int64), order_hash.hexdigest() + + def exact_token_budget(self, passes): + # Permuting only changes which sentence uses the full name; sum its exact sizes. + return sum(len(self.pass_tokens(e)[0]) - 1 for e in range(passes)) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_diagnostics.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..dc0de9f1aeb4e6e8a48ea33b265811985ebea4d8 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_diagnostics.py @@ -0,0 +1,463 @@ +"""Frozen endpoint diagnostics for bioS; no training and no ground-truth auto inputs.""" + +from __future__ import annotations + +import calendar +import json +import os +import random +import re +import time +from collections import defaultdict +from pathlib import Path + +import torch +from tokenizers import Tokenizer + +from .bios_original_data import ATTRS, TASKS, answer, date, digest, load_json, question, write_json +from .bios_original_train import ( + amp, + encode_row, + generate, + load_model, + normalize, + sequence_scores, + setup, +) + +DEFAULT_ROOT = "docs/development-artifacts/bios-original-diagnostics-v1" +TASK_PAIR = ("parity", "comparison") + + +def select_people(people, world, count=24): + """Sample whole development partner pairs without model-dependent filtering.""" + if count % 2: + raise ValueError("The development count must consist of whole pairs") + pairs = [ + (p["id"], p["partner"]) for p in people if p["split"] == "dev" and p["id"] < p["partner"] + ] + pairs = random.Random(world + 930001).sample(pairs, count // 2) + return sorted(i for pair in pairs for i in pair) + + +def parse_date(text): + """Strict full-string date parser; malformed generations remain failures.""" + text = normalize(text) + names = {name.casefold(): i for i, name in enumerate(calendar.month_name) if i} + match = re.fullmatch(r"([a-z]+) ([1-9]|1\d|2[0-8]), (\d{4})", text) + if match is None or match[1] not in names: + return None + return (int(match[3]), names[match[1]], int(match[2])) + + +def operation_prompt(task, first, second=None): + """Exact rule-training prompt; only supplied strings enter this function.""" + if task == "parity": + parsed = parse_date(first) + month = calendar.month_name[parsed[1]] if parsed else first + return f"Question: Is {month} an even-numbered month?\nAnswer:" + if task == "comparison": + return f"Question: Which date is earlier, {first} or {second}?\nAnswer:" + raise ValueError(task) + + +def decode_operation(task, generated, first, second=None, names=None): + """Map a model-selected supplied date to its name without consulting truth.""" + if task == "parity": + return normalize(generated) + chosen = normalize(generated) + values = [normalize(first), normalize(second)] + if values[0] == values[1] or chosen not in values: + return None + return names[values.index(chosen)] + + +def symbolic_operation(task, first, second=None, names=None): + """A separately labelled host-computation ceiling, never a model result.""" + a = parse_date(first) + if a is None: + return None + if task == "parity": + return "yes" if a[1] % 2 == 0 else "no" + b = parse_date(second) + if b is None or a == b: + return None + return names[0 if a < b else 1] + + +def audit_batches(people, tasks, cot, batch_size): + """Select one original physical batch per split, independent of predictions.""" + eligible = [p for p in people if p["split"] in ("dev", "test")] + rows_per_person = len(tasks) * 6 * (2 if cot else 1) + starts = set() + for split in ("dev", "test"): + person_index = next(i for i, p in enumerate(eligible) if p["split"] == split) + starts.add((person_index * rows_per_person // batch_size) * batch_size) + return sorted(starts) + + +def read_selected_batches(path, starts, batch_size): + batches = {s: [] for s in starts} + with Path(path).open() as stream: + for i, line in enumerate(stream): + for s in starts: + if s <= i < s + batch_size: + batches[s].append(dict(load_json_line=json.loads(line), source_row=i)) + if i >= max(starts) + batch_size - 1: + break + if any(len(rows) != batch_size for rows in batches.values()): + raise ValueError("Incomplete historical physical batch") + return [dict(start=s, rows=rows) for s, rows in batches.items()] + + +def prepare(config_path, root=DEFAULT_ROOT, count=24): + root = Path(root) + if (root / "plan.json").exists(): + raise FileExistsError("Diagnostic inputs already frozen") + cfg = load_json(config_path) + source_files = [ + "src/llm_memory_editability/bios_original_diagnostics.py", + "scripts/run_bios_original_diagnostics.py", + "src/llm_memory_editability/bios_original_data.py", + "src/llm_memory_editability/bios_original_model.py", + "src/llm_memory_editability/bios_original_train.py", + ] + # Loading current implementations is valid only if original implementations match. + frozen = Path(cfg["result_root"]) / "execution-source" + for file in source_files[2:]: + if digest(file) != digest(frozen / file): + raise ValueError(f"Original source changed: {file}") + plan = dict( + version=1, + created_unix=time.time(), + config_path=str(config_path), + config_sha256=digest(config_path), + config=cfg, + count=count, + views=[0, 1], + diagnostic_batch_size=16, + audit_batch_size=cfg["evaluation"]["batch_size"], + max_new_tokens=cfg["evaluation"]["max_new_tokens"], + source_sha256={f: digest(f) for f in source_files}, + tokenizer_sha256=digest(Path(cfg["data_root"]) / "tokenizer/tokenizer.json"), + worlds={}, + endpoints=[], + ) + for world in cfg["world_seeds"]: + data_path = Path(cfg["data_root"]) / f"world-{world}/people.json" + people = load_json(data_path) + plan["worlds"][str(world)] = dict( + person_ids=select_people(people, world, count), + people_path=str(data_path), + sha256=digest(data_path), + ) + for init in cfg["initialization_seeds"]: + for condition in cfg["task"]["conditions"]: + stages = ["adapt", "task"] if condition in ("S", "M", "MP") else ["task"] + for stage in stages: + path = ( + Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" + ) + complete = load_json(path / "complete.json") + evaluation = load_json(path / "evaluation/evaluation-complete.json") + if complete["checkpoint_sha256"] != evaluation["checkpoint_sha256"]: + raise ValueError("Checkpoint/evaluation hash disagreement") + endpoint_id = f"world-{world}-{condition}-{stage}" + tasks = ATTRS if stage == "adapt" else TASKS + cot = stage == "task" and condition == "MP-CoT" + selected = read_selected_batches( + path / "evaluation/predictions.jsonl", + audit_batches(people, tasks, cot, plan["audit_batch_size"]), + plan["audit_batch_size"], + ) + sample = root / "audit-inputs" / f"{endpoint_id}.json" + write_json(sample, selected) + plan["endpoints"].append( + dict( + id=endpoint_id, + world=world, + init=init, + condition=condition, + stage=stage, + checkpoint=str(path / "final.pt"), + checkpoint_sha256=complete["checkpoint_sha256"], + audit_sample=str(sample), + audit_sample_sha256=digest(sample), + ) + ) + write_json(root / "plan.json", plan) + return plan + + +def verify_plan(plan): + for path, sha in plan["source_sha256"].items(): + if digest(path) != sha: + raise ValueError(f"Frozen diagnostic source changed: {path}") + for data in plan["worlds"].values(): + if digest(data["people_path"]) != data["sha256"]: + raise ValueError("People data changed") + + +def run_audit(model, tok, endpoint, plan, output, device): + sample = Path(endpoint["audit_sample"]) + if digest(sample) != endpoint["audit_sample_sha256"]: + raise ValueError("Audit inputs changed") + report = [] + for batch in load_json(sample): + rows = [r["load_json_line"] for r in batch["rows"]] + encoded = [encode_row(tok, r["prompt"], r["answer"]) for r in rows] + with torch.no_grad(), amp(device): + avg, full = sequence_scores(model, encoded, device) + generated, ended = generate( + model, tok, [r["prompt"] for r in rows], device, plan["max_new_tokens"] + ) + for original, text, eos, mean_lp, full_lp in zip( + batch["rows"], generated, ended, avg.tolist(), full.tolist(), strict=True + ): + old = original["load_json_line"] + extracted = text.rsplit("Answer:", 1)[-1].strip() if old["cot"] else text + report.append( + dict( + source_row=original["source_row"], + physical_batch_start=batch["start"], + original=old, + reloaded_generated=text, + reloaded_eos=eos, + generated_identical=text == old["generated"], + eos_identical=eos == old["eos"], + correctness_identical=(normalize(extracted) == normalize(old["answer"])) + == old["correct"], + mean_logp_difference=mean_lp - old["answer_mean_logp"], + full_logp_difference=full_lp - old["answer_full_logp"], + ) + ) + write_json(output / "audit-rows.json", report) + summary = dict( + rows=len(report), + generation_mismatches=sum(not r["generated_identical"] for r in report), + eos_mismatches=sum(not r["eos_identical"] for r in report), + correctness_mismatches=sum(not r["correctness_identical"] for r in report), + max_abs_full_logp_difference=max(abs(r["full_logp_difference"]) for r in report), + exact_original_batch=True, + precision="FP32 parameters, BF16 autocast, TF32 enabled", + ) + summary["status"] = ( + "passed" + if all( + summary[k] == 0 + for k in ("generation_mismatches", "eos_mismatches", "correctness_mismatches") + ) + and summary["max_abs_full_logp_difference"] <= 1e-4 + else "discrepancy" + ) + write_json(output / "audit-summary.json", summary) + return summary + + +def generate_rows(model, tok, rows, plan, device): + for start in range(0, len(rows), plan["diagnostic_batch_size"]): + batch = rows[start : start + plan["diagnostic_batch_size"]] + outputs, ended = generate( + model, tok, [r["prompt"] for r in batch], device, plan["max_new_tokens"] + ) + for row, text, eos in zip(batch, outputs, ended, strict=True): + row.update(generated=text, eos=eos) + print( + json.dumps( + dict(generation_done=min(start + len(batch), len(rows)), generation_total=len(rows)) + ), + flush=True, + ) + + +def run_diagnostics(model, tok, endpoint, plan, output, device): + world = plan["worlds"][str(endpoint["world"])] + people = load_json(world["people_path"]) + selected = [people[i] for i in world["person_ids"]] + extraction = [ + dict(person_id=p["id"], view=v, prompt=question(p, "date", v), target=date(p)) + for p in selected + for v in plan["views"] + ] + generate_rows(model, tok, extraction, plan, device) + lookup = {} + for row in extraction: + row.update( + parseable=parse_date(row["generated"]) is not None, + correct=normalize(row["generated"]) == normalize(row["target"]), + ) + lookup[row["person_id"], row["view"]] = row + write_json(output / "extractions.json", extraction) + rows = [] + for p in selected: + other = people[p["partner"]] + for task in TASK_PAIR: + for view in plan["views"]: + base = dict( + person_id=p["id"], + partner=other["id"], + view=view, + task=task, + target=answer(p, task, other), + ) + for cot in (False, True): + rows.append( + dict( + base, + mode="cot" if cot else "direct", + prompt=question(p, task, view, other, cot), + cot_trained=endpoint["condition"] == "MP-CoT", + ) + ) + for mode in ("oracle_rule", "autonomous_rule"): + a = date(p) if mode == "oracle_rule" else lookup[p["id"], view]["generated"] + b = ( + date(other) + if mode == "oracle_rule" + else lookup[other["id"], view]["generated"] + ) + parsed = parse_date(a) is not None and ( + task != "comparison" or parse_date(b) is not None + ) + valid = normalize(a) == normalize(date(p)) and ( + task != "comparison" or normalize(b) == normalize(date(other)) + ) + symbolic = symbolic_operation(task, a, b, (p["name"], other["name"])) + rows.append( + dict( + base, + mode=mode, + prompt=operation_prompt(task, a, b), + supplied_dates=[a, b] if task == "comparison" else [a], + inputs_parseable=parsed, + inputs_correct=valid, + symbolic_prediction=symbolic, + symbolic_correct=symbolic is not None + and normalize(symbolic) == normalize(base["target"]), + ) + ) + generate_rows(model, tok, rows, plan, device) + totals = defaultdict(lambda: defaultdict(int)) + for row in rows: + p, other = people[row["person_id"]], people[row["partner"]] + if row["mode"] in ("direct", "cot"): + pred = ( + row["generated"].rsplit("Answer:", 1)[-1].strip() + if row["mode"] == "cot" + else row["generated"] + ) + else: + dates = row["supplied_dates"] + pred = decode_operation( + row["task"], + row["generated"], + dates[0], + dates[1] if len(dates) == 2 else None, + (p["name"], other["name"]), + ) + row["prediction"] = pred + row["output_in_question_pair"] = ( + pred is not None and normalize(pred) in (normalize(p["name"]), normalize(other["name"])) + if row["task"] == "comparison" + else None + ) + if row["task"] == "comparison" and row["mode"] in ("oracle_rule", "autonomous_rule"): + row["output_is_supplied_date"] = normalize(row["generated"]) in { + normalize(value) for value in row["supplied_dates"] + } + row["correct"] = pred is not None and normalize(pred) == normalize(row["target"]) + row["correct_with_eos"] = row["correct"] and row["eos"] + key = f"{row['task']}/view-{row['view']}/{row['mode']}" + total = totals[key] + total["n"] += 1 + total["correct"] += row["correct"] + total["correct_with_eos"] += row["correct_with_eos"] + if row["task"] == "comparison": + total["output_in_question_pair"] += row["output_in_question_pair"] + if "output_is_supplied_date" in row: + total["output_is_supplied_date"] += row["output_is_supplied_date"] + if row["mode"] == "autonomous_rule": + for condition in ("inputs_parseable", "inputs_correct"): + total[condition + "_n"] += row[condition] + total[condition + "_correct"] += row[condition] and row["correct"] + total["symbolic_correct"] += row["symbolic_correct"] + with (output / "diagnostics.jsonl").open("w") as stream: + for row in rows: + stream.write(json.dumps(row) + "\n") + summary = dict( + rows=len(rows), + extraction_rows=len(extraction), + extraction_correct=sum(r["correct"] for r in extraction), + extraction_parseable=sum(r["parseable"] for r in extraction), + totals=dict(totals), + people=len(selected), + independent_partner_pairs=len(selected) // 2, + split="development", + no_training=True, + limitations=[ + "Oracle and autonomous rules use externally supplied text and a changed prompt.", + "Non-MP-CoT models did not train on the CoT instruction.", + "Host date-to-name mapping and symbolic ceilings are not model reasoning.", + "Twenty-four people are a fixed diagnostic subset, not population estimates.", + ], + ) + write_json(output / "diagnostic-summary.json", summary) + return summary + + +def run_endpoint(root, endpoint_id, device="cuda:0", memory_fraction=0.045): + root = Path(root) + plan = load_json(root / "plan.json") + verify_plan(plan) + endpoint = next(e for e in plan["endpoints"] if e["id"] == endpoint_id) + output = root / "endpoints" / endpoint_id + if (output / "complete.json").exists(): + return load_json(output / "complete.json") + output.mkdir(parents=True, exist_ok=True) + if digest(endpoint["checkpoint"]) != endpoint["checkpoint_sha256"]: + raise ValueError("Checkpoint changed") + cfg = plan["config"] + setup(endpoint["init"], device) + if str(device).startswith("cuda"): + torch.cuda.set_per_process_memory_fraction(memory_fraction, device) + torch.cuda.reset_peak_memory_stats(device) + tok_path = Path(cfg["data_root"]) / "tokenizer/tokenizer.json" + if digest(tok_path) != plan["tokenizer_sha256"]: + raise ValueError("Tokenizer changed") + tok = Tokenizer.from_file(str(tok_path)) + start = time.monotonic() + model = load_model(endpoint["checkpoint"], cfg, device, adapters=True).eval() + model.requires_grad_(False) + write_json( + output / "running.json", + dict( + endpoint=endpoint_id, + started_unix=time.time(), + pid=os.getpid(), + device=device, + cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), + memory_fraction=memory_fraction, + shared_gpu=True, + torch_version=torch.__version__, + ), + ) + audit = run_audit(model, tok, endpoint, plan, output, device) + diagnostics = ( + run_diagnostics(model, tok, endpoint, plan, output, device) + if endpoint["stage"] == "task" + else None + ) + result = dict( + endpoint=endpoint, + seconds=time.monotonic() - start, + audit=audit, + diagnostics=diagnostics, + shared_gpu=True, + memory_fraction=memory_fraction, + cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), + peak_allocated_bytes=torch.cuda.max_memory_allocated(device) + if str(device).startswith("cuda") + else None, + ) + write_json(output / "complete.json", result) + return result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_model.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_model.py new file mode 100644 index 0000000000000000000000000000000000000000..039ceaef72cf7fefa38bb094dbefbe9f7e88d651 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_model.py @@ -0,0 +1,130 @@ +"""GPT-2 blocks, quarter-head NeoX RoPE, tied vocabulary, explicit Q/V/embedding LoRA.""" + +from __future__ import annotations + +import math + +import torch +from torch import nn +from torch.nn import functional as F + + +class Attention(nn.Module): + def __init__(self, cfg): + super().__init__() + width = cfg["width"] + self.heads = cfg["heads"] + self.dim = width // self.heads + self.rotary_dim = int(self.dim * cfg["rotary_fraction"]) + assert self.rotary_dim % 2 == 0 and self.rotary_dim > 0 + self.qkv = nn.Linear(width, 3 * width) + self.out = nn.Linear(width, width) + freq = 1.0 / ( + cfg["rotary_base"] ** (torch.arange(0, self.rotary_dim, 2).float() / self.rotary_dim) + ) + angle = torch.outer(torch.arange(cfg["context"]).float(), freq) + angle = torch.cat((angle, angle), dim=-1)[None, None] + self.register_buffer("cos", angle.cos(), persistent=False) + self.register_buffer("sin", angle.sin(), persistent=False) + self.dropout = cfg["dropout"] + self.rank = 0 + + def add_lora(self, rank): + self.rank = rank + width = self.heads * self.dim + self.q_a = nn.Parameter(torch.randn(rank, width) * 0.02) + self.q_b = nn.Parameter(torch.zeros(width, rank)) + self.v_a = nn.Parameter(torch.randn(rank, width) * 0.02) + self.v_b = nn.Parameter(torch.zeros(width, rank)) + + def rotate(self, x): + z, tail = x[..., : self.rotary_dim], x[..., self.rotary_dim :] + half = self.rotary_dim // 2 + swapped = torch.cat((-z[..., half:], z[..., :half]), dim=-1) + size = x.shape[-2] + z = z * self.cos[:, :, :size].to(x.dtype) + swapped * self.sin[:, :, :size].to(x.dtype) + return torch.cat((z, tail), dim=-1) + + def forward(self, x): + b, t, width = x.shape + q, k, v = self.qkv(x).chunk(3, dim=-1) + if self.rank: + q = q + F.linear(F.linear(x, self.q_a), self.q_b) + v = v + F.linear(F.linear(x, self.v_a), self.v_b) + q, k, v = [z.view(b, t, self.heads, self.dim).transpose(1, 2) for z in (q, k, v)] + y = F.scaled_dot_product_attention( + self.rotate(q), + self.rotate(k), + v, + is_causal=True, + dropout_p=self.dropout if self.training else 0, + ) + return self.out(y.transpose(1, 2).contiguous().view(b, t, width)) + + +class Block(nn.Module): + def __init__(self, cfg): + super().__init__() + width = cfg["width"] + self.ln1, self.ln2 = nn.LayerNorm(width), nn.LayerNorm(width) + self.attn = Attention(cfg) + self.up, self.down = nn.Linear(width, 4 * width), nn.Linear(4 * width, width) + self.dropout = nn.Dropout(cfg["dropout"]) + + def forward(self, x): + x = x + self.dropout(self.attn(self.ln1(x))) + return x + self.dropout(self.down(F.gelu(self.up(self.ln2(x)), approximate="tanh"))) + + +class GPT(nn.Module): + def __init__(self, cfg): + super().__init__() + self.cfg = cfg + self.embedding = nn.Embedding(cfg["vocab_size"], cfg["width"]) + self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg["layers"])]) + self.norm = nn.LayerNorm(cfg["width"]) + self.dropout = nn.Dropout(cfg["dropout"]) + self.embedding_rank = 0 + self.apply(self._init) + for block in self.blocks: + nn.init.normal_(block.attn.out.weight, std=0.02 / math.sqrt(2 * cfg["layers"])) + nn.init.normal_(block.down.weight, std=0.02 / math.sqrt(2 * cfg["layers"])) + + @staticmethod + def _init(module): + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, std=0.02) + if isinstance(module, nn.Linear): + nn.init.zeros_(module.bias) + + def add_lora(self, qv_rank, embedding_rank): + self.requires_grad_(False) + for b in self.blocks: + b.attn.add_lora(qv_rank) + self.embedding_rank = embedding_rank + self.emb_a = nn.Parameter(torch.randn(self.cfg["vocab_size"], embedding_rank) * 0.02) + self.emb_b = nn.Parameter(torch.zeros(embedding_rank, self.cfg["width"])) + + def hidden(self, ids): + x = self.embedding(ids) + if self.embedding_rank: + x = x + F.embedding(ids, self.emb_a) @ self.emb_b + x = self.dropout(x) + for block in self.blocks: + x = block(x) + return self.norm(x) + + def logits(self, hidden): + # Preserve input/output tying also for the embedding update. + logits = F.linear(hidden, self.embedding.weight) + if self.embedding_rank: + logits = logits + F.linear(F.linear(hidden, self.emb_b), self.emb_a) + return logits + + def forward(self, ids, targets=None): + h = self.hidden(ids) + if targets is None: + return self.logits(h) + # Avoid materializing logits at padded/unsupervised positions. + valid = targets != -100 + return F.cross_entropy(self.logits(h[valid]).float(), targets[valid], reduction="mean") diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_report.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_report.py new file mode 100644 index 0000000000000000000000000000000000000000..8aace2494390c65045a2d379beb42695d3b84c8e --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_report.py @@ -0,0 +1,685 @@ +"""Read-only, CPU aggregation of the completed original bioS development run.""" + +from __future__ import annotations + +import csv +import hashlib +import json +import math +import re +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +from llm_memory_editability.bios_original_data import ( + ATTRS, + MONTHS, + TASKS, + answer, + question, +) + +DATE_PATTERN = re.compile( + "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}" +) +DIMENSIONS = ("world", "initialization", "condition", "stage", "split", "task", "view", "cot") +COUNTS = ( + "n", + "correct", + "eos", + "format_recognized", + "correct_eos", + "correct_unrecognized", + "wrong_recognized", + "wrong_unrecognized", + "terminal_answer_match", + "target_text_present", + "city_swap", + "comparison_outside_pair", + "sum_full_logp", + "sum_mean_logp", + "sum_answer_probability", +) + + +def normalize(text): + """Independently reproduce the historical frozen evaluator's normalization.""" + return " ".join(text.strip().rstrip(".").casefold().split()) + + +def extract(row): + text = row["generated"] + return text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text + + +def recognized(text, task, vocabulary): + value = normalize(text) + if task == "parity": + return value in ("yes", "no") + if task == "year": + return bool(re.fullmatch(r"\d{4}", value)) + if task == "date": + return bool(DATE_PATTERN.fullmatch(value)) + if task in ("company_city", "city_company"): + fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") + parts = value.split(";") + return len(parts) == 2 and all( + part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) + ) + return value in vocabulary["name" if task == "comparison" else task] + + +def review_flags(row, person, vocabulary, partner=None): + """Mechanical error labels only; these do not replace the frozen score.""" + text, target = extract(row), normalize(row["answer"]) + correct = normalize(text) == target + form = recognized(text, row["task"], vocabulary) + suffix = row["generated"].rsplit("Answer:", 1)[-1] + terminal = not correct and "Answer:" in row["generated"] and normalize(suffix) == target + # A literal occurrence is an inspection cue, not a semantic-correctness claim. + present = not correct and bool( + re.search(r"(? 1e-5: + raise ValueError(f"Invalid log probability: {path}:{line_number}") + cell[target] += value + cell["sum_answer_probability"] += math.exp(row["answer_full_logp"]) + for category in ( + "terminal_answer_match", + "target_text_present", + "city_swap", + "comparison_outside_pair", + "wrong_recognized", + "wrong_unrecognized", + "correct_unrecognized", + ): + sample_key = (row["task"], row["view"] == 0, row["cot"], category) + if flags[category] and sample_counts[sample_key] < 2: + sample_counts[sample_key] += 1 + examples.append( + dict( + **meta, + category=category, + source=str(path), + line=line_number, + **row, + review_status="deterministic inspection sample; not human-labelled", + ) + ) + expected_cells = len(cfg["evaluation"]["splits"]) * len(tasks) * 6 * len(modes) + if len(cells) != expected_cells or len(completion["totals"]) != expected_cells: + raise ValueError(f"Incomplete evaluation cell matrix: {path}") + counts = Counter(p["split"] for p in people) + for (split, task, view, cot), cell in cells.items(): + if cell["n"] != counts[split]: + raise ValueError(f"Incomplete population: {path}: {split}/{task}/{view}/{cot}") + old = completion["totals"][f"{split}/{task}/view-{view}/cot-{cot}"] + if any(cell[k] != old[k] for k in ("n", "correct", "format_recognized")): + raise ValueError(f"Historical totals mismatch: {path}") + if not math.isclose(cell["sum_full_logp"], old["sum_full_logp"], abs_tol=1e-8): + raise ValueError(f"Historical logp total mismatch: {path}") + checks["cells_population_and_historical_totals_verified"] += 1 + provenance = dict( + **meta, + path=str(path), + sha256=digest.hexdigest(), + bytes=path.stat().st_size, + checkpoint_sha256=completion["checkpoint_sha256"], + checks=dict(checks), + completion_sha256=hashlib.sha256(completion_path.read_bytes()).hexdigest(), + ) + conditional = conditional_rows(seen, people, meta, modes) if meta["stage"] == "task" else [] + return [finalized(v) for v in cells.values()], examples, provenance, conditional + + +def pretrain_rows(cfg): + curves, inventory = [], [] + for world in cfg["world_seeds"]: + for init in cfg["initialization_seeds"]: + for condition in cfg["pretrain"]["conditions"]: + root = Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/pretrain" + path = root / "metrics.jsonl" + metrics = [json.loads(line) for line in path.read_text().splitlines()] + expected = list(range(1, cfg["pretrain"]["passes"] + 1)) + if [r["passes"] for r in metrics] != expected: + raise ValueError(f"Incomplete pretraining curve: {path}") + for row in metrics: + curves.append( + dict(world=world, initialization=init, condition=condition, **row) + ) + inventory.append( + dict( + world=world, + initialization=init, + condition=condition, + path=str(path), + sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + passes=len(metrics), + final_nll=metrics[-1]["nll"], + nodes=[ + dict(passes=n, checkpoint_exists=(root / f"pass-{n:03d}.pt").exists()) + for n in cfg["pretrain"]["nodes"] + ], + ) + ) + return curves, inventory + + +def paired_differences(groups): + pairs = [("S", "M"), ("M", "MP"), ("MP", "MP-R"), ("MP-R", "MP-Random"), ("MP", "MP-CoT")] + lookup = {} + for row in groups: + key = tuple( + row[k] + for k in ("world", "initialization", "stage", "split", "task", "view_group", "cot") + ) + lookup.setdefault(key, {})[row["condition"]] = row + rows = [] + for key, conditions in lookup.items(): + for left, right in pairs: + if left not in conditions or right not in conditions: + continue + a, b = conditions[left], conditions[right] + if a["n"] != b["n"]: + raise ValueError("Unequal paired populations") + rows.append( + dict( + **dict( + zip( + ( + "world", + "initialization", + "stage", + "split", + "task", + "view_group", + "cot", + ), + key, + strict=True, + ) + ), + left=left, + right=right, + n_each=a["n"], + left_accuracy=a["correct_rate"], + right_accuracy=b["correct_rate"], + difference_pp=100 * (b["correct_rate"] - a["correct_rate"]), + ) + ) + return rows + + +def make_plots(output, curves, groups): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, axes = plt.subplots(1, 2, figsize=(11, 4)) + for world in sorted({r["world"] for r in curves}): + for c, color in zip(("S", "M", "MP"), ("#9b5f1b", "#4477aa", "#228833"), strict=True): + subset = [r for r in curves if r["world"] == world and r["condition"] == c] + axes[0].plot( + [r["passes"] for r in subset], + [r["nll"] for r in subset], + color=color, + alpha=0.8, + label=f"{c}, world {world}", + ) + axes[0].set(xlabel="Biography exposures per person", ylabel="Training NLL", yscale="log") + axes[0].legend(fontsize=7) + for offset, view, color in [(-0.17, "canonical", "#4477aa"), (0.17, "heldout", "#cc6677")]: + means = [] + for c in ("S", "M", "MP"): + data = [ + r["correct_rate"] + for r in groups + if r["stage"] == "adapt" + and r["split"] == "test" + and r["condition"] == c + and r["view_group"] == view + and r["family"] == "six_attributes" + ] + means.append(100 * sum(data) / len(data)) + axes[1].bar([i + offset for i in range(3)], means, width=0.32, label=view, color=color) + axes[1].set( + xticks=range(3), + xticklabels=("S", "M", "MP"), + ylabel="QA extraction accuracy (%)", + ylim=(0, 105), + ) + axes[1].legend() + fig.suptitle("Original bioS development: training fit and later QA extraction") + fig.tight_layout() + for suffix in ("png", "pdf"): + fig.savefig(output / f"bios-pretrain-and-extraction.{suffix}", dpi=160) + plt.close(fig) + + +def report_text(overall, groups, endpoints): + def mean(rows, field="correct_rate"): + # Exactly one initialization per world in this development configuration. + per_world = {} + for row in rows: + per_world.setdefault(row["world"], []).append(row[field]) + values = [sum(v) / len(v) for v in per_world.values()] + return 100 * sum(values) / len(values) if values else float("nan") + + def select(rows, **conditions): + return [r for r in rows if all(r[k] == v for k, v in conditions.items())] + + lines = [ + "# 原版 bioS 开发预测复盘", + "", + "本报告独立复算两开发世界的 570 万条既有预测、18 个评价端点与全部 3240 个预训练" + "日志节点。没有新增训练、GPU 前向或更改历史预测。原始评分与完成文件逐单元一致。", + "", + "表中百分比先在每个世界内汇总,再对两个世界等权;这是开发结果,无新增独立确认。" + "同一人物的五个留出问法,以及同一比较人物对的两个问序,属于重复测量。", + "", + "## 六属性 QA 提取", + "", + "| BIO 条件 | 规范问法 | 五个留出问法均值 |", + "| --- | ---: | ---: |", + ] + for condition in ("S", "M", "MP"): + values = [ + mean( + select( + overall, + stage="adapt", + split="test", + condition=condition, + family="six_attributes", + view_group=v, + cot=False, + ) + ) + for v in ("canonical", "heldout") + ] + lines.append(f"| {condition} | {values[0]:.2f}% | {values[1]:.2f}% |") + lines += [ + "", + "S/M/MP 使用相同人物与语义事实曝光;M 增加表述,MP 再重排句序。" + "QA 适配使用训练人物,测试人物只参加 BIO 预训练。这里测的是经共同 QA 适配后的提取," + "不能称为预训练终点未经适配的问答表现。工作城市已出现于传记,属于提取任务。", + "", + "## 任务适配后的规范问法", + "", + "| 模型 / 推理方式 | 日期 | 年份 | 月份奇偶 | 出生早晚比较 |", + "| --- | ---: | ---: | ---: | ---: |", + ] + for condition, cot in [ + ("MP", False), + ("MP-R", False), + ("MP-Random", False), + ("MP-CoT", False), + ("MP-CoT", True), + ]: + values = [ + mean( + select( + groups, + stage="task", + split="test", + condition=condition, + view_group="canonical", + cot=cot, + task=task, + ) + ) + for task in ("date", "year", "parity", "comparison") + ] + mode = "CoT" if cot else "直接" + lines.append(f"| {condition} / {mode} | " + " | ".join(f"{v:.2f}%" for v in values) + " |") + lines += [ + "", + "年份和奇偶需要从已知属性执行操作,不能与六属性提取的平均值混为一项。" + "MP-CoT 的两种推理方式使用同一适配端点,但解释提示、监督格式及输出计算不同。" + "MP-R 的收益须与匹配的 MP-Random 同时检查。", + "", + "## 错误与计分审阅", + "", + ] + for condition, cot in (("MP", False), ("MP-CoT", True)): + value = mean( + select( + groups, + stage="task", + split="test", + condition=condition, + view_group="canonical", + cot=cot, + task="comparison", + ), + "comparison_outside_pair_rate", + ) + lines.append( + f"- {condition} / {'CoT' if cot else '直接'} 的比较输出中," + f"{value:.2f}% 未精确返回问题中任一人的名字;这不能只解释为日期运算错误。" + ) + suffix = mean( + select( + groups, + stage="task", + split="test", + condition="MP-CoT", + view_group="heldout", + cot=False, + task="date", + ), + "terminal_answer_match_rate", + ) + lines += [ + f"- MP-CoT 直接作答的留出日期问法中,{suffix:.2f}% 的全量输出虽未通过冻结评分," + "最后一个 `Answer:` 后恰为目标日期。这是可复核的格式失分,保留为事后辅助统计;" + "没有改写主分数。", + "- `wrong_recognized` 只表示输出满足原格式规则但不等于标签;" + "`target_text_present` 只表示原输出出现目标文字,不认定语义正确。" + "城市互换与问题外人名由已知人物表确定。", + "- `error-review-samples.jsonl` 按任务、问法组、模式、错误标签保存最先两条," + "是确定性审阅样本,不是错误率的随机估计,也不是全量人工语义标注。", + "- CoT 的历史 `answer_full_logp` 是解释提示后直接接短答案的概率," + "不是所生成推理链或最终答案的概率,不用于判断 CoT 是否掌握知识。", + "- `conditional-task-scores.csv` 在同一人物、相同问法和输出模式下检查源属性是否答对;" + "比较题要求两个人的日期都答对。它是条件子集分析,覆盖率与全量分数同时保留," + "不等同于把模型自产属性重新输入后的两次调用实验。", + "", + "## 预训练曲线与剩余工作", + "", + "`pretrain-curves.csv` 与图保留六条各 540 次曝光的训练 NLL。不同数据条件的文本" + "可预测性不同,NLL 不能当作统一知识量刻度。已保存权重节点存在不等于已测出各节点的" + "知识/推理能力;当前没有这样的语义学习曲线。", + "", + "本 CPU 报告没有完成独立权重重载、oracle 属性输入或自主提取后运算;" + "100k 正式矩阵与日期编辑也未执行。它们的后续结果应写入独立产物。", + "", + "复现:`PYTHONPATH=src .venv/bin/python scripts/report_bios_original.py`。" + "原预测、配置、数据及报告源码哈希见 `audit.json`。", + "", + f"已核验端点:{len(endpoints)};完整单元表 `cells.csv`,按任务与问法组汇总" + " `task-view-groups.csv`,世界内配对差 `paired-world-differences.csv`。", + ] + return "\n".join(lines) + "\n" + + +def run_report(config_path, output): + cfg = json.loads(config_path.read_text()) + output.mkdir(parents=True, exist_ok=True) + cells, examples, endpoints, conditional = [], [], [], [] + for world in cfg["world_seeds"]: + people_path = Path(cfg["data_root"]) / f"world-{world}/people.json" + people = json.loads(people_path.read_text()) + if [p["id"] for p in people] != list(range(cfg["people"])): + raise ValueError("People index contract changed") + for init in cfg["initialization_seeds"]: + for stage, conditions in ( + ("adapt", cfg["pretrain"]["conditions"]), + ("task", cfg["task"]["conditions"]), + ): + for condition in conditions: + meta = dict(world=world, initialization=init, condition=condition, stage=stage) + root = ( + Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" + ) + a, b, c, d = read_endpoint(root, meta, cfg, people) + cells.extend(a) + examples.extend(b) + endpoints.append(c) + conditional.extend(d) + print( + json.dumps(dict(**meta, rows=sum(r["n"] for r in a), status="verified")), + flush=True, + ) + groups = rollup(cells, views=True) + overall = overall_rows(groups) + curves, inventory = pretrain_rows(cfg) + write_csv(output / "cells.csv", cells) + write_csv(output / "task-view-groups.csv", groups) + write_csv(output / "overall.csv", overall) + write_csv(output / "paired-world-differences.csv", paired_differences(groups)) + write_csv(output / "conditional-task-scores.csv", conditional) + write_csv(output / "pretrain-curves.csv", curves) + with (output / "error-review-samples.jsonl").open("w") as stream: + for example in examples: + stream.write(json.dumps(example, ensure_ascii=False) + "\n") + save_json( + output / "audit.json", + dict( + created_at_utc=datetime.now(timezone.utc).isoformat(), + scope="CPU predictions/logs audit; no checkpoint reload or GPU inference", + config=str(config_path), + config_sha256=hashlib.sha256(config_path.read_bytes()).hexdigest(), + raw_prediction_rows=sum(r["n"] for r in cells), + endpoint_count=len(endpoints), + cells=len(cells), + pretraining_runs=len(inventory), + pretrain_nodes=len(curves), + endpoints=endpoints, + pretrain=inventory, + failures=[], + sources=[ + dict(path=str(p), sha256=hashlib.sha256(p.read_bytes()).hexdigest()) + for p in ( + Path(__file__), + Path("scripts/report_bios_original.py"), + Path("src/llm_memory_editability/bios_original_data.py"), + Path("src/llm_memory_editability/bios_original_train.py"), + *[ + Path(cfg["data_root"]) / f"world-{w}/people.json" + for w in cfg["world_seeds"] + ], + ) + ], + missing_scientific_deliverables=[ + "Independent GPU checkpoint reload remains unverified by this CPU report", + "Oracle-input and extract-then-operate inference are absent from these inputs", + "Pretraining semantic trajectories absent; existing curve is training NLL only", + "Sampled output inspection is separate from exhaustive human semantic adjudication", + ], + ), + ) + save_json( + output / "summary.json", + dict( + development_worlds=cfg["world_seeds"], + independent_worlds=len(cfg["world_seeds"]), + test_overall=[r for r in overall if r["split"] == "test"], + probability_caveat=( + "CoT logp scores the short gold answer immediately after the explanation prompt; " + "it is not the probability of the generated CoT or its final answer." + ), + scoring=( + "Historical answer EM; EOS is reported independently. Views and paired " + "comparison orientations are repeated measurements, not independent worlds." + ), + ), + ) + make_plots(output, curves, overall) + (output / "report.md").write_text(report_text(overall, groups, endpoints)) + return overall diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_train.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_train.py new file mode 100644 index 0000000000000000000000000000000000000000..eea8f0449758025224fd3bb37444cc7e54e7ef7c --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_original_train.py @@ -0,0 +1,669 @@ +"""Restartable development execution for the original bioS experiment, plan 14.27.""" + +from __future__ import annotations + +import contextlib +import json +import math +import os +import random +import re +import time +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_original_data import ( + ATTRS, + MATERIAL, + MONTHS, + TASKS, + BioStream, + answer, + date, + digest, + load_json, + question, + reasoning, + write_json, +) +from .bios_original_model import GPT + + +def setup(seed, device): + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + torch.set_num_threads(4) + torch.manual_seed(seed) + random.seed(seed) + np.random.seed(seed) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.use_deterministic_algorithms(True) + if str(device).startswith("cuda"): + torch.cuda.set_device(device) + + +def amp(device): + return ( + torch.autocast("cuda", dtype=torch.bfloat16) + if str(device).startswith("cuda") + else contextlib.nullcontext() + ) + + +def append(path, record): + with Path(path).open("a") as out: + out.write(json.dumps(record) + "\n") + + +def atomic_save(path, obj): + path = Path(path) + tmp = path.with_suffix(".tmp") + torch.save(obj, tmp) + tmp.replace(path) + + +def pack_tokens(tokens, context=512): + """Adjacent chunks overlap by the context token only; every target is scored once.""" + n = len(tokens) - 1 + rows = math.ceil(n / context) + x = np.full((rows, context), 50256, dtype=np.int64) + y = np.full((rows, context), -100, dtype=np.int64) + x.flat[:n] = tokens[:-1] + y.flat[:n] = tokens[1:] + return torch.from_numpy(x), torch.from_numpy(y) + + +def optimizer_for(model, settings): + params = [p for p in model.parameters() if p.requires_grad] + groups = [ + dict(params=[p for p in params if p.ndim >= 2], weight_decay=settings["weight_decay"]), + dict(params=[p for p in params if p.ndim < 2], weight_decay=0.0), + ] + return torch.optim.AdamW( + groups, + lr=settings["learning_rate"], + betas=tuple(settings.get("adam_betas", [0.9, 0.999])), + eps=settings.get("adam_epsilon", 1e-6), + fused=next(model.parameters()).is_cuda, + ) + + +def parameter_count(model): + return sum(p.numel() for p in model.parameters()) + + +def pretrain(cfg, world, init, condition, device, stop_after_pass=None): + setup(init, device) + root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / "pretrain" + root.mkdir(parents=True, exist_ok=True) + settings = cfg["pretrain"] + data_root = Path(cfg["data_root"]) / f"world-{world}" + stream = BioStream(data_root, world, condition) + contract = dict( + config=cfg, + world=world, + init=init, + condition=condition, + data_audit_sha256=digest(data_root / "audit.json"), + ) + if (root / "contract.json").exists(): + if load_json(root / "contract.json") != contract: + raise ValueError("Run contract changed; use a new run directory") + else: + write_json(root / "contract.json", contract) + model = GPT(cfg["model"]).to(device) + opt = optimizer_for(model, settings) + start, step, seen, elapsed = 0, 0, 0, 0.0 + latest = root / "latest.pt" + 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"]) + start, step, seen, elapsed = [state[k] for k in ("passes", "step", "tokens", "elapsed")] + del state + elif (root / "metrics.jsonl").exists(): + raise ValueError("Metrics without a resumable checkpoint require investigation") + if (root / "metrics.jsonl").exists(): + kept = [ + line + for line in (root / "metrics.jsonl").read_text().splitlines() + if json.loads(line)["passes"] <= start + ] + (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) + if start == 0 and not (root / "pass-000.pt").exists(): + atomic_save(root / "pass-000.pt", dict(model=model.state_dict(), config=cfg["model"])) + if not latest.exists(): + atomic_save( + latest, + dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + passes=0, + step=0, + tokens=0, + elapsed=0.0, + ), + ) + count = parameter_count(model) + write_json( + root / "model.json", + dict( + parameters=count, + trainable=count, + device=str(device), + gpu=torch.cuda.get_device_name(device) if "cuda" in str(device) else "cpu", + torch=torch.__version__, + resume_pass=start, + ), + ) + model.train() + runner = torch.compile(model) if settings.get("compile") else model + wall = time.monotonic() + for epoch in range(start, min(settings["passes"], stop_after_pass or settings["passes"])): + pass_start = time.monotonic() + tokens, order_hash = stream.pass_tokens(epoch) + xs, ys = pack_tokens(tokens, cfg["model"]["context"]) + total_loss, valid_tokens = 0.0, 0 + batch = settings["batch_size"] + micro = settings["micro_batch_size"] + for i in range(0, len(xs), batch): + # Learning rate follows complete-person exposure; no outcome-based stopping. + progress = (epoch + i / len(xs)) / settings["passes"] + cosine = ( + settings["minimum_lr_ratio"] + + (1 - settings["minimum_lr_ratio"]) * (1 + math.cos(math.pi * progress)) / 2 + ) + lr = ( + settings["learning_rate"] + * cosine + * min(1, (step + 1) / max(1, settings["warmup_steps"])) + ) + for group in opt.param_groups: + group["lr"] = lr + opt.zero_grad(set_to_none=True) + end = min(i + batch, len(xs)) + denom = int((ys[i:end] != -100).sum()) + batch_loss = 0.0 + for j in range(i, end, micro): + x, y = ( + xs[j : min(j + micro, end)].to(device), + ys[j : min(j + micro, end)].to(device), + ) + n = int((y != -100).sum()) + with amp(device): + loss = runner(x, y) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite loss at pass {epoch}, step {step}") + (loss * (n / denom)).backward() + batch_loss += loss.detach().item() * n + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), settings["gradient_clip"]) + if not torch.isfinite(norm): + raise FloatingPointError(f"Nonfinite gradient at step {step}") + opt.step() + step += 1 + total_loss += batch_loss + valid_tokens += denom + if step % 10 == 0: + write_json( + root / "status.json", + dict( + state="running", + passes_completed=epoch, + pass_fraction=end / len(xs), + step=step, + learning_rate=lr, + last_batch_nll=batch_loss / denom, + tokens=seen + valid_tokens, + elapsed=elapsed + time.monotonic() - wall, + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + assert valid_tokens == len(tokens) - 1 + seen += valid_tokens + duration = time.monotonic() - pass_start + record = dict( + passes=epoch + 1, + people_presented=(epoch + 1) * stream.count, + tokens=seen, + pass_tokens=valid_tokens, + nll=total_loss / valid_tokens, + seconds=duration, + tokens_per_second=valid_tokens / duration, + step=step, + learning_rate=lr, + presentation_sha256=order_hash, + estimated_training_flops=6 * count * seen, + elapsed=elapsed + time.monotonic() - wall, + ) + append(root / "metrics.jsonl", record) + print(json.dumps(record), flush=True) + if epoch + 1 in settings["nodes"]: + atomic_save( + root / f"pass-{epoch + 1:03d}.pt", + dict(model=model.state_dict(), config=cfg["model"], metrics=record), + ) + if (epoch + 1) % 10 == 0 or epoch + 1 == stop_after_pass or epoch + 1 == settings["passes"]: + atomic_save( + latest, + dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + passes=epoch + 1, + step=step, + tokens=seen, + elapsed=elapsed + time.monotonic() - wall, + ), + ) + write_json( + root / "status.json", + dict( + state="complete" if epoch + 1 == settings["passes"] else "running", + passes_completed=epoch + 1, + **record, + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + return root / f"pass-{settings['passes']:03d}.pt" + + +def encode_row(tokenizer, prompt, target): + prefix = tokenizer.encode(prompt).ids + suffix = tokenizer.encode(" " + target).ids + [50256] + return dict(ids=prefix + suffix, answer_start=len(prefix)) + + +def supervised_batch(rows, device): + width = max(len(r["ids"]) for r in rows) - 1 + x = torch.full((len(rows), width), 50256, dtype=torch.long, device=device) + y = torch.full_like(x, -100) + for i, r in enumerate(rows): + ids = torch.tensor(r["ids"], device=device) + x[i, : len(ids) - 1] = ids[:-1] + y[i, r["answer_start"] - 1 : len(ids) - 1] = ids[r["answer_start"] :] + return x, y + + +def sequence_scores(model, rows, device): + x, y = supervised_batch(rows, device) + h = model.hidden(x) + b, t = torch.where(y != -100) + losses = F.cross_entropy(model.logits(h[b, t]).float(), y[b, t], reduction="none") + sums = torch.zeros(len(rows), device=device).scatter_add_(0, b, losses) + sizes = torch.bincount(b, minlength=len(rows)) + return -sums / sizes, -sums + + +def task_rows(people, tokenizer, tasks, condition, epoch, seed): + rng = random.Random(seed) + # Use the published label vocabulary, independent of held-out person attributes. + cities = sorted( + set((MATERIAL / "fields/city.txt").read_text().splitlines()) + | { + line.split(";", 1)[1].strip() + for line in (MATERIAL / "fields/company.txt").read_text().splitlines() + } + ) + bins = defaultdict(list) + for city in cities: + bins[len(tokenizer.encode(" " + city).ids)].append(city) + rows = [] + for p in people: + if p["split"] != "train": + continue + other = people[p["partner"]] + for j, task in enumerate(tasks): + cot = condition == "MP-CoT" and (p["id"] + j + epoch) % 2 == 0 + prompt = question(p, task, other=other, cot=cot) + target = reasoning(p, task, other) if cot else answer(p, task, other) + row = encode_row(tokenizer, prompt, target) + row.update(person_id=p["id"], task=task, cot=cot) + if task in ("birthcity", "workcity") and p["birthcity"] != p["workcity"]: + competing = p["workcity"] if task == "birthcity" else p["birthcity"] + candidates = [ + c + for c in bins[len(tokenizer.encode(" " + competing).ids)] + if c not in (p["birthcity"], p["workcity"]) + ] + if not candidates: + raise ValueError( + "No length-matched random city; cannot silently relax matching" + ) + negative = rng.choice(candidates) if condition == "MP-Random" else competing + row["negative"] = encode_row(tokenizer, prompt, negative) + rows.append(row) + return rows + + +def rule_rows(tokenizer): + rows = [] + for m, name in enumerate(MONTHS, 1): + rows.append( + encode_row( + tokenizer, + f"Question: Is {name} an even-numbered month?\nAnswer:", + "yes" if m % 2 == 0 else "no", + ) + ) + rng = random.Random(14270000) + for i in range(24): + a, b = [ + dict( + year=rng.randrange(1900, 2100), month=rng.randrange(1, 13), day=rng.randrange(1, 29) + ) + for _ in range(2) + ] + if i % 2: + a, b = ( + max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + ) + else: + a, b = ( + min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + ) + rows.append( + encode_row( + tokenizer, + f"Question: Which date is earlier, {date(a)} or {date(b)}?\nAnswer:", + date(b if i % 2 else a), + ) + ) + return rows + + +def load_model(path, cfg, device, adapters=False): + model = GPT(cfg["model"]) + if adapters: + model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) + state = torch.load(path, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + return model.to(device) + + +def finetune(cfg, world, init, condition, stage, parent, device, tokenizer): + setup(init + 1, device) + root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / stage + root.mkdir(parents=True, exist_ok=True) + people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") + contract = dict( + config=cfg, + world=world, + init=init, + condition=condition, + stage=stage, + parent=str(parent), + parent_sha256=digest(parent), + ) + if (root / "contract.json").exists() and load_json(root / "contract.json") != contract: + raise ValueError("Finetuning contract changed") + write_json(root / "contract.json", contract) + if (root / "complete.json").exists(): + return root / "final.pt" + model = load_model(parent, cfg, device, adapters=stage == "task") + if stage == "adapt": + model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) + model.to(device) + opt = optimizer_for(model, cfg["adapt"]) + start, step = 0, 0 + if (root / "latest.pt").exists(): + ck = torch.load(root / "latest.pt", map_location=device, weights_only=False) + model.load_state_dict(ck["model"]) + opt.load_state_dict(ck["optimizer"]) + start, step = ck["epoch"], ck["step"] + del ck + if (root / "metrics.jsonl").exists(): + kept = [ + line + for line in (root / "metrics.jsonl").read_text().splitlines() + if json.loads(line)["epoch"] <= start + ] + (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) + write_json( + root / "parameters.json", + dict( + total=parameter_count(model), + trainable=sum(p.numel() for p in model.parameters() if p.requires_grad), + trainable_names=[n for n, p in model.named_parameters() if p.requires_grad], + ), + ) + epochs = cfg[stage]["epochs"] + model.train() + for epoch in range(start, epochs): + rows = task_rows( + people, + tokenizer, + ATTRS if stage == "adapt" else TASKS, + condition if stage == "task" else "MP", + epoch, + world + 1427, + ) + if stage == "task": + rows += rule_rows(tokenizer) * cfg["task"]["rule_repetitions_per_epoch"] + random.Random(world + epoch + 20000000).shuffle(rows) + batch, micro = cfg["adapt"]["batch_size"], cfg["adapt"]["micro_batch_size"] + ce_sum, ranking_sum, candidates, target_tokens = 0.0, 0.0, 0, 0 + wall = time.monotonic() + for i in range(0, len(rows), batch): + group = rows[i : i + batch] + lr = cfg["adapt"]["learning_rate"] * ( + 0.1 + 0.9 * (1 + math.cos(math.pi * (epoch + i / len(rows)) / epochs)) / 2 + ) + for pg in opt.param_groups: + pg["lr"] = lr + opt.zero_grad(set_to_none=True) + for j in range(0, len(group), micro): + part = group[j : j + micro] + with amp(device): + scores, _ = sequence_scores(model, part, device) + ce = -scores.mean() + neg_pairs = [(k, r["negative"]) for k, r in enumerate(part) if "negative" in r] + rank = scores.sum() * 0 + if stage == "task" and neg_pairs: + neg, _ = sequence_scores(model, [r for _, r in neg_pairs], device) + pos = scores[[k for k, _ in neg_pairs]] + # Normalize by all positive rows, including zero collision/non-city terms. + rank = F.softplus(cfg["task"]["margin"] - (pos - neg)).sum() / len(part) + candidates += len(neg_pairs) + coefficient = ( + cfg["task"]["ranking_coefficient"] + if condition in ("MP-R", "MP-Random") and stage == "task" + else 0.0 + ) + loss = ce + coefficient * rank + if not torch.isfinite(loss): + raise FloatingPointError("Nonfinite finetuning loss") + (loss * len(part) / len(group)).backward() + ce_sum += ce.item() * len(part) + ranking_sum += rank.item() * len(part) + target_tokens += sum(len(r["ids"]) - r["answer_start"] for r in part) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(norm): + raise FloatingPointError("Nonfinite finetuning gradient") + opt.step() + step += 1 + if step % 25 == 0: + write_json( + root / "status.json", + dict( + state="running", + epoch=epoch, + fraction=min(i + batch, len(rows)) / len(rows), + step=step, + last_ce=ce.item(), + pid=os.getpid(), + updated_unix=time.time(), + ), + ) + rec = dict( + epoch=epoch + 1, + rows=len(rows), + ce=ce_sum / len(rows), + rank=ranking_sum / len(rows), + scored_negative_candidates=candidates, + target_tokens=target_tokens, + seconds=time.monotonic() - wall, + ) + append(root / "metrics.jsonl", rec) + print(json.dumps(rec), flush=True) + atomic_save( + root / "latest.pt", + dict(model=model.state_dict(), optimizer=opt.state_dict(), epoch=epoch + 1, step=step), + ) + atomic_save(root / "final.pt", dict(model=model.state_dict(), config=cfg["model"])) + write_json( + root / "complete.json", + dict(epochs=epochs, step=step, checkpoint_sha256=digest(root / "final.pt")), + ) + return root / "final.pt" + + +@torch.no_grad() +def generate(model, tokenizer, prompts, device, max_tokens): + # Right padding; each row's final real position supplies its own next token. + sequences = [tokenizer.encode(p).ids for p in prompts] + outputs, finished = [[] for _ in prompts], [False] * len(prompts) + for _ in range(max_tokens): + width = max(map(len, sequences)) + if width > model.cfg["context"]: + break + ids = torch.full((len(prompts), width), 50256, dtype=torch.long, device=device) + for i, seq in enumerate(sequences): + ids[i, : len(seq)] = torch.tensor(seq, device=device) + with amp(device): + h = model.hidden(ids) + last = h[ + torch.arange(len(prompts), device=device), + torch.tensor([len(s) - 1 for s in sequences], device=device), + ] + pred = model.logits(last).argmax(-1).tolist() + for i, token in enumerate(pred): + if not finished[i]: + outputs[i].append(token) + sequences[i].append(token) + finished[i] = token == 50256 + if all(finished): + break + return [tokenizer.decode(ids, skip_special_tokens=True).strip() for ids in outputs], finished + + +def normalize(text): + return " ".join(text.strip().rstrip(".").casefold().split()) + + +def recognized_format(text, task, vocabulary): + value = normalize(text) + if task == "parity": + return value in ("yes", "no") + if task == "year": + return bool(re.fullmatch(r"\d{4}", value)) + if task == "date": + return bool( + re.fullmatch( + "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}", + value, + ) + ) + if task in ("company_city", "city_company"): + parts = value.split(";") + fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") + return len(parts) == 2 and all( + part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) + ) + return value in vocabulary["name" if task == "comparison" else task] + + +@torch.no_grad() +def evaluate(cfg, world, checkpoint, output, device, tokenizer, tasks=TASKS, cot=False): + output = Path(output) + if (output / "evaluation-complete.json").exists(): + if load_json(output / "evaluation-complete.json")["checkpoint_sha256"] != digest( + checkpoint + ): + raise ValueError("Evaluated checkpoint changed") + return + output.mkdir(parents=True, exist_ok=True) + people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") + vocabulary = {field: {normalize(p[field]) for p in people} for field in ("name", *ATTRS[1:])} + model = load_model(checkpoint, cfg, device, adapters=True).eval() + totals = defaultdict(lambda: defaultdict(float)) + batch = [] + with (output / "predictions.jsonl").open("w") as out: + + def flush(): + if not batch: + return + enc = [encode_row(tokenizer, r["prompt"], r["answer"]) for r in batch] + with amp(device): + avg, full = sequence_scores(model, enc, device) + generated, ended = generate( + model, + tokenizer, + [r["prompt"] for r in batch], + device, + cfg["evaluation"]["max_new_tokens"], + ) + for row, text, stop, av, lp in zip( + batch, generated, ended, avg.tolist(), full.tolist(), strict=True + ): + extracted = text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text + correct = normalize(extracted) == normalize(row["answer"]) + # Syntactic recognition is distinct from correctness; retain raw output. + recognized = recognized_format(extracted, row["task"], vocabulary) + row.update( + generated=text, + eos=stop, + correct=correct, + format_recognized=recognized, + answer_mean_logp=av, + answer_full_logp=lp, + ) + out.write(json.dumps(row) + "\n") + key = f"{row['split']}/{row['task']}/view-{row['view']}/cot-{row['cot']}" + t = totals[key] + t["n"] += 1 + t["correct"] += correct + t["format_recognized"] += recognized + t["sum_full_logp"] += lp + batch.clear() + write_json( + output / "evaluation-status.json", + dict( + rows=sum(t["n"] for t in totals.values()), + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + + for p in people: + if p["split"] not in cfg["evaluation"]["splits"]: + continue + other = people[p["partner"]] + for task in tasks: + for view in cfg["evaluation"]["views"]: + for use_cot in [False, True] if cot else [False]: + batch.append( + dict( + person_id=p["id"], + split=p["split"], + task=task, + view=view, + cot=use_cot, + partner=other["id"] if task == "comparison" else None, + prompt=question(p, task, view, other, use_cot), + answer=answer(p, task, other), + ) + ) + if len(batch) == cfg["evaluation"]["batch_size"]: + flush() + flush() + write_json( + output / "evaluation-complete.json", + dict(checkpoint_sha256=digest(checkpoint), totals=dict(totals)), + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_path_diagnostics.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_path_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..219336bcde27c897b81d6c253255dca79eb11d1c --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_path_diagnostics.py @@ -0,0 +1,727 @@ +"""Read-only answer-source diagnostics for the frozen two-chain experiments. + +Matching an answer to a candidate is a behavioral description, not evidence that +the model used that internal path. Multiple matching roles are never tie-broken. +""" + +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, write_json + +LEARNING_ROLES = ("default", "actual", "other_default", "other_actual") +EDIT_ROLES = ( + "new_default", + "new_actual", + "old_default", + "old_actual", + "other_default", + "other_actual", +) +# Codes are shared across files. Role names differ between learning and editing. +NOT_APPLICABLE, TERMINATION_ERROR, OTHER, INDISTINGUISHABLE = -1, 0, 1, 2 +ROLE_CODE_START = 3 + + +def file_sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def classify_answers(prediction, ended, candidates): + """Return exclusive categories plus *all* matched role bits, including overlaps. + + An unfinished generation is a termination error even if its value matches. + Correctness is deliberately separate: a correct answer can have ambiguous roles. + """ + prediction, ended, candidates = map(np.asarray, (prediction, ended, candidates)) + if ( + candidates.ndim != 2 + or prediction.shape != ended.shape + or candidates.shape[0] != len(prediction) + ): + raise ValueError("Incompatible prediction/candidate shapes") + if not 1 <= candidates.shape[1] <= 8: + raise ValueError("Candidate role bitset requires one to eight roles") + matched = prediction[:, None] == candidates + n_matches = matched.sum(axis=1) + bits = (matched.astype(np.uint8) * (1 << np.arange(candidates.shape[1]))).sum(axis=1) + category = np.full(len(prediction), OTHER, dtype=np.int8) + unique = n_matches == 1 + category[unique] = ROLE_CODE_START + matched[unique].argmax(axis=1) + category[n_matches > 1] = INDISTINGUISHABLE + category[~ended.astype(bool)] = TERMINATION_ERROR + return category, bits.astype(np.uint8) + + +def candidate_answers(world, chain, target=None): + """Candidate values for all people, with no dependence on model predictions.""" + other = 1 - chain + old_default = world.answers[world.root_ids[chain, world.memberships[chain]]] + old_actual = world.answers[world.actual_ids[chain]] + current = world.answers if target is None else target + other_default = current[world.root_ids[other, world.memberships[other]]] + other_actual = current[world.actual_ids[other]] + if target is None: + roles = LEARNING_ROLES + values = (old_default, old_actual, other_default, other_actual) + else: + roles = EDIT_ROLES + values = ( + target[world.root_ids[chain, world.memberships[chain]]], + target[world.actual_ids[chain]], + old_default, + old_actual, + other_default, + other_actual, + ) + return roles, np.column_stack(values) + + +def score_saved_arrays(arrays, answers): + prediction, ended = arrays["prediction"], arrays["ended"] + if prediction.shape != answers.shape or ended.shape != answers.shape: + raise ValueError("Saved prediction length differs from truth") + if not np.isin(ended, [False, True]).all(): + raise ValueError("Invalid termination flags") + correct = (prediction == answers) & ended.astype(bool) + if not np.array_equal(correct, arrays["correct"]): + raise ValueError("Saved correctness differs from value-plus-EOS scoring") + return correct + + +def annotate_predictions(world, arrays, target=None): + """Full-query arrays plus candidate matrices aligned with derived_query_ids.""" + answers = world.answers if target is None else target + correct = score_saved_arrays(arrays, answers) + category = np.full(len(answers), NOT_APPLICABLE, dtype=np.int8) + bits = np.zeros(len(answers), dtype=np.uint8) + candidates = [] + for chain in range(2): + roles, values = candidate_answers(world, chain, target) + ids = world.derived_ids[chain] + category[ids], bits[ids] = classify_answers( + arrays["prediction"][ids], arrays["ended"][ids], values + ) + candidates.append(values) + return { + "query_id": np.arange(len(answers), dtype=np.int32), + "prediction": np.asarray(arrays["prediction"], dtype=np.int32), + "ended": np.asarray(arrays["ended"], dtype=bool), + "correct": correct, + "class_code": category, + "matched_role_bits": bits, + "derived_query_ids": world.derived_ids.astype(np.int32), + "candidate_tokens": np.stack(candidates).astype(np.int32), + "candidate_roles": np.array(roles), + } + + +def learning_subsets(world): + """Overlapping diagnostic groups; every row retains its own denominator.""" + yield "all_queries", np.arange(len(world.answers)) + yield "base", np.arange(world.n_base) + yield "independent_attributes", np.flatnonzero(np.isin(world.relation, [3, 4, 5, 6])) + for chain, name in enumerate(CHAINS): + for relation, ids in ( + ("membership", world.membership_ids[chain]), + ("default", world.root_ids[chain]), + ("actual", world.actual_ids[chain]), + ): + yield f"{name}/base/{relation}", ids + for split, ids in ( + ("all", world.derived_ids[chain]), + ("trained", world.train_ids[chain]), + ("heldout", world.heldout_ids[chain]), + ): + yield f"{name}/qa/{split}/all", ids + for label, mask in ( + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + yield ( + f"{name}/qa/{split}/{label}", + np.intersect1d(ids, world.derived_ids[chain, mask]), + ) + + +def editing_subsets(world, pair, chain, target): + yield "E/all", pair["E"] + yield "E/default", np.intersect1d(pair["E"], world.root_ids[chain]) + yield "E/actual", np.intersect1d(pair["E"], world.actual_ids[chain]) + # Membership in the 45-person manipulated cohort differs from factual conflict: + # six old exceptions can also conflict; coherent edits have no *new* conflicts. + actual_conflict = target[world.derived_ids[chain]] != target[world.actual_ids[chain]] + for split, ids in ( + ("all", pair["D"]), + ("trained", np.intersect1d(pair["D"], world.train_ids[chain])), + ("heldout", np.intersect1d(pair["D"], world.heldout_ids[chain])), + ): + yield f"D/{split}/all", ids + for label, group in ( + ("manipulated_conflict_cohort", pair["conflict_D"]), + ("factual_conflict", world.derived_ids[chain, actual_conflict]), + ("no_factual_conflict", world.derived_ids[chain, ~actual_conflict]), + ("old_exception", world.derived_ids[chain, world.exceptions[chain]]), + ("ordinary", world.derived_ids[chain, ~world.exceptions[chain]]), + ): + yield f"D/{split}/{label}", np.intersect1d(ids, group) + for pool_name, pool in ( + ("full", np.flatnonzero(pair["strata"] >= 0)), + ("editor_heldout", pair["heldout"]), + ): + yield f"U/{pool_name}/all", pool + for stratum in range(4): + yield ( + f"U/{pool_name}/stratum_{stratum}", + np.intersect1d(pool, np.flatnonzero(pair["strata"] == stratum)), + ) + + +def summary_rows(world, annotations, subsets, identity, old_correct=None): + """Counts are sufficient to reaggregate without hiding empty or ambiguous cells.""" + classes, bits = annotations["class_code"], annotations["matched_role_bits"] + for label, ids in subsets: + ids = np.asarray(ids) + correct = annotations["correct"][ids] + row = { + **identity, + "subset": label, + "n": len(ids), + "correct": int(correct.sum()), + "accuracy": float(correct.mean()) if len(ids) else None, + "termination_error": int((~annotations["ended"][ids]).sum()), + "role_not_applicable": int((classes[ids] == NOT_APPLICABLE).sum()), + "other_answer": int((classes[ids] == OTHER).sum()), + "indistinguishable": int((classes[ids] == INDISTINGUISHABLE).sum()), + "indistinguishable_wrong": int(((classes[ids] == INDISTINGUISHABLE) & ~correct).sum()), + } + # Stable CSV schema, even though learning uses only four roles. + for role in dict.fromkeys((*LEARNING_ROLES, *EDIT_ROLES)): + role_names = list(annotations["candidate_roles"]) + if role in role_names: + index = role_names.index(role) + row[f"unique_{role}"] = int((classes[ids] == ROLE_CODE_START + index).sum()) + row[f"matches_{role}"] = int( + (((bits[ids] & (1 << index)) != 0) & annotations["ended"][ids]).sum() + ) + else: + row[f"unique_{role}"] = row[f"matches_{role}"] = 0 + if old_correct is not None: + known = old_correct[ids] + row["old_known"] = int(known.sum()) + row["old_known_coverage"] = float(known.mean()) if len(ids) else None + row["old_known_now_wrong"] = int((known & ~correct).sum()) + row["damage_rate"] = ( + (float((known & ~correct).sum() / known.sum()) if known.any() else None) + if label.startswith("U/") + else None + ) + else: + row.update( + old_known=None, old_known_coverage=None, old_known_now_wrong=None, damage_rate=None + ) + yield row + + +def _write_csv(path, rows): + with Path(path).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def _safe_output(output, source_roots): + output = Path(output).resolve() + if any(output == root or root in output.parents for root in source_roots): + raise ValueError("Diagnostics must not be written into source experiment directories") + output.mkdir(parents=True, exist_ok=True) + return output + + +def analyze_saved(repository, output, manifest_path="configs/bios-cross-scale-development-v1.json"): + """Re-score the complete matrix using CPU arrays; never invoke old summary writers.""" + repository = Path(repository).resolve() + manifest_path = repository / manifest_path + manifest = json.loads(manifest_path.read_text()) + source_roots = [(repository / size["output"]).resolve() for size in manifest["sizes"]] + output = _safe_output(output, source_roots) + ledger = {} + + def record(path): + path = Path(path).resolve() + key = str(path.relative_to(repository)) if repository in path.parents else str(path) + digest = file_sha256(path) + if key in ledger and ledger[key] != digest: + raise ValueError(f"Source changed during analysis: {path}") + ledger[key] = digest + + record(manifest_path) + worlds, pairs = {}, {} + learning_rows, editing_rows, error_rows = [], [], [] + counts = { + "models": 0, + "learning_checkpoints": 0, + "edit_cases": 0, + "edit_checkpoints": 0, + "scored_query_predictions": 0, + "classified_derived_predictions": 0, + } + for size, root in zip(manifest["sizes"], source_roots, strict=True): + contract_path = root / "launch-contract.json" + record(contract_path) + contract = json.loads(contract_path.read_text()) + study = contract["study"] + expected_runs = { + (w, seed, condition) + for w in study["worlds"] + for seed in study["seeds"] + for condition in CONDITIONS + } + seen_runs = set() + for config_path in sorted(root.glob("world-*/config.json")): + record(config_path) + config = json.loads(config_path.read_text()) + if config["sources"] != contract["sources"] or config["study"] != study: + raise ValueError(f"Run contract mismatch: {config_path}") + for name, digest in config["sources"].items(): + path = repository / "src/llm_memory_editability" / name + if file_sha256(path) != digest: + raise ValueError(f"Frozen source changed: {name}") + record(path) + run = config_path.parent + key = (config["world"], config["seed"], config["condition"]) + if key in seen_runs: + raise ValueError("Duplicate model") + seen_runs.add(key) + if not (run / "complete.json").exists(): + raise ValueError(f"Incomplete run: {run}") + record(run / "complete.json") + world_seed = config["world"] + if world_seed not in worlds: + worlds[world_seed] = make_cross_world( + world_seed, repository / "data/bios-organization-v1" + ) + world = worlds[world_seed] + if config["truth_sha256"] != array_hash(world.answers) or config[ + "prompts_sha256" + ] != array_hash(world.prompts): + raise ValueError("Generated data mismatch") + common = { + "width": size["width"], + "parameters": config["parameters"], + "world": world_seed, + "seed": config["seed"], + "condition": config["condition"], + } + out_run = output / "queries" / f"width-{size['width']}" / run.name + out_run.mkdir(parents=True, exist_ok=True) + baseline = None + for step in study["checkpoints"]: + prediction_path = run / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {name: loaded[name] for name in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays) + np.savez_compressed(out_run / f"learning-{step}.npz", **annotated) + identity = { + **common, + "phase": "learning", + "chain": "", + "kind": "", + "scope": "", + "step": step, + } + learning_rows.extend( + summary_rows(world, annotated, learning_subsets(world), identity) + ) + counts["learning_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + if step == study["steps"]: + baseline = arrays["correct"] + if baseline is None: + raise ValueError("Missing learning endpoint") + for chain, name in enumerate(CHAINS): + pair_key = (world_seed, chain) + if pair_key not in pairs: + pairs[pair_key] = edit_pair(world, chain) + pair = pairs[pair_key] + for kind in ("coherent", "exception"): + target = pair[kind] + for scope in ("mlp", "all"): + case = f"{name}-{kind}-{scope}" + dest = run / "edits" / case + record(dest / "complete.json") + record(dest / "sets.npz") + with np.load(dest / "sets.npz", allow_pickle=False) as loaded: + for field, expected in pair.items(): + if not np.array_equal(loaded[field], expected): + raise ValueError(f"Edit set mismatch: {dest}/{field}") + if not np.array_equal(loaded["old_correct"], baseline): + raise ValueError(f"Edit baseline mismatch: {dest}") + for step in study["edit_checkpoints"]: + prediction_path = dest / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {k: loaded[k] for k in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays, target) + np.savez_compressed(out_run / f"{case}-{step}.npz", **annotated) + identity = { + **common, + "phase": "editing", + "chain": name, + "kind": kind, + "scope": scope, + "step": step, + } + editing_rows.extend( + summary_rows( + world, + annotated, + editing_subsets(world, pair, chain, target), + identity, + baseline, + ) + ) + # Readable per-D query ledger, with every ambiguity explicitly retained. + roles, values = candidate_answers(world, chain, target) + for query in pair["D"]: + person = world.person[query] + matches = [ + role + for i, role in enumerate(roles) + if annotated["matched_role_bits"][query] & (1 << i) + ] + code = int(annotated["class_code"][query]) + category = { + TERMINATION_ERROR: "termination_error", + OTHER: "other", + INDISTINGUISHABLE: "indistinguishable", + } + error_rows.append( + { + **identity, + "query": int(query), + "person": int(person), + "heldout": bool(query in world.heldout_ids[chain]), + "old_exception": bool(world.exceptions[chain, person]), + "manipulated_conflict_cohort": bool( + query in pair["conflict_D"] + ), + "factual_conflict": bool( + values[person, 0] != values[person, 1] + ), + "prediction": int(arrays["prediction"][query]), + "ended": bool(arrays["ended"][query]), + "correct": bool(arrays["correct"][query]), + "class": category.get( + code, + roles[code - ROLE_CODE_START] + if code >= ROLE_CODE_START + else "", + ), + "matched_roles": "|".join(matches), + **{ + role: int(values[person, i]) + for i, role in enumerate(roles) + }, + } + ) + counts["edit_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + counts["edit_cases"] += 1 + counts["models"] += 1 + print(json.dumps({"event": "p0_model_scored", **common, **counts}), flush=True) + if seen_runs != expected_runs: + raise ValueError(f"Incomplete or unexpected model grid: width {size['width']}") + if ( + counts["models"] != manifest["learning_runs"] + or counts["edit_cases"] != manifest["edit_cases"] + ): + raise ValueError("Incomplete matrix") + _write_csv(output / "learning-strata.csv", learning_rows) + _write_csv(output / "editing-strata.csv", editing_rows) + _write_csv(output / "propagation-queries.csv", error_rows) + # Verify that reading/analysis did not mutate any source and that no parallel + # process changed this historical input batch while it was being analyzed. + for name, digest in ledger.items(): + if file_sha256(repository / name) != digest: + raise ValueError(f"Source changed during analysis: {name}") + write_json(output / "sources.json", ledger) + write_json( + output / "schema.json", + { + "class_codes": { + "not_applicable_to_base_query": -1, + "termination_error": 0, + "other": 1, + "indistinguishable": 2, + "unique_role_start": 3, + }, + "learning_roles": LEARNING_ROLES, + "editing_roles": EDIT_ROLES, + "matched_role_bits": "bit i indicates value matches role i; EOS checked separately", + "candidate_tokens_shape": "chain, person, role; " + "maps to derived_query_ids[chain, person]", + "interpretation": "Candidate answer agreement is not causal evidence for a path. " + "Overlapping roles are never assigned a preferred interpretation.", + "subset_rows_overlap": True, + "manipulated_conflict_cohort": "Original 45 people, also tagged in coherent controls; " + "factual_conflict is measured from actual target answers.", + }, + ) + code_hashes = { + str(path.relative_to(repository)): file_sha256(path) + for path in (Path(__file__).resolve(), repository / "scripts/analyze_bios_paths.py") + } + audit = { + "complete": True, + **counts, + "source_files": len(ledger), + "sources_sha256": file_sha256(output / "sources.json"), + "analysis_sources": code_hashes, + "errors": [], + "source_data_modified": False, + "source_hashes_rechecked_after_analysis": True, + } + write_json(output / "audit.json", audit) + _report(output, audit, learning_rows, editing_rows) + return audit + + +def _report(output, audit, learning_rows, editing_rows): + lines = [ + "# P0:已有预测的行为诊断", + "", + f"完成{audit['models']}个模型、{audit['edit_cases']}个编辑;" + f"重计分{audit['learning_checkpoints']}个学习和{audit['edit_checkpoints']}个编辑检查点。", + "", + "候选答案相同的角色记为不可区分;答案重合不能证明内部路径。" + "终止失败独立于答案值记录。下表为案例等权均值,非独立查询推断。", + "", + "| 宽度 | 编辑 | 案例 | 冲突留出D | 新实际城市匹配 | 不可区分 | 终止失败 |", + "|---:|---|---:|---:|---:|---:|---:|", + ] + grouped = defaultdict(list) + for row in editing_rows: + if ( + row["kind"] == "exception" + and row["step"] == 512 + and row["subset"] == "D/heldout/manipulated_conflict_cohort" + ): + grouped[row["width"], row["scope"]].append(row) + for (width, scope), rows in sorted(grouped.items()): + rates = [ + np.mean([r[key] / r["n"] for r in rows]) + for key in ("correct", "matches_new_actual", "indistinguishable", "termination_error") + ] + lines.append( + f"| {width} | {scope} | {len(rows)} | " + + " | ".join(f"{100 * rate:.2f}%" for rate in rates) + + " |" + ) + lines += [ + "", + "新实际城市匹配是允许与旧实际/另一条链答案重合的描述性比例;" + "唯一匹配和全部角色位图均另存,不能据此宣称捷径已证实。", + "", + "学习分层见 learning-strata.csv;编辑分层见 editing-strata.csv;" + "每条传播查询见 propagation-queries.csv;全部逐查询数组见 queries/。", + "自主两步前向诊断尚须单独执行并记录模型权重来源。", + "", + ] + (output / "report.md").write_text("\n".join(lines)) + + +def free_generate_values(model, prompts, lengths, device, batch_size=512): + """Exactly the frozen value-plus-EOS generation convention, without targets.""" + import torch + + from .bios_train import precision + + predictions, ended = [], [] + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[begin : begin + batch_size], device=device) + n = torch.as_tensor(lengths[begin : begin + batch_size], device=device) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)} + + +def autonomous_two_step(model, world, chain, device, batch_size=512, answers=None): + """Generate bridge identity, then query that predicted identity, never the true one. + + Truth is accessed only for scoring after both model calls. A wrong but valid + bridge may coincidentally lead to a correct city; keep that outcome and the + first-hop correctness separately. Invalid/unterminated bridges fail outright. + """ + membership_ids = world.membership_ids[chain] + first = free_generate_values( + model, world.prompts[membership_ids], world.lengths[membership_ids], device, batch_size + ) + allowed_subjects = world.prompts[world.root_ids[chain], 1] + valid = first["ended"] & np.isin(first["prediction"], allowed_subjects) + second_prediction = np.full(len(membership_ids), -1, dtype=np.int64) + second_ended = np.zeros(len(membership_ids), dtype=bool) + if valid.any(): + # Root queries have the same grammar and relation token. Do not choose a + # template using true membership; replace the subject using generated data. + root_template = world.prompts[world.root_ids[chain, 0]] + prompts = np.broadcast_to(root_template, (int(valid.sum()), 5)).copy() + prompts[:, 1] = first["prediction"][valid] + lengths = np.full(len(prompts), world.lengths[world.root_ids[chain, 0]], dtype=np.int64) + second = free_generate_values(model, prompts, lengths, device, batch_size) + second_prediction[valid], second_ended[valid] = second["prediction"], second["ended"] + target = world.answers if answers is None else answers + return { + "query_id": world.derived_ids[chain], + "bridge_prediction": first["prediction"], + "bridge_ended": first["ended"], + "bridge_valid": valid, + "bridge_correct": (first["prediction"] == target[membership_ids]) & first["ended"], + "prediction": second_prediction, + "ended": second_ended, + "correct": valid & second_ended & (second_prediction == target[world.derived_ids[chain]]), + } + + +def diagnose_two_step_run( + run, output, device="cuda", learning_steps=(15360,), include_edits=False, batch_size=512 +): + """Independent, resumable forward-only jobs; no optimizer or training mutations.""" + import torch + + from .bios_model import CausalLM, ModelConfig + + run, output = Path(run).resolve(), Path(output).resolve() + repository = Path(__file__).resolve().parents[2] + output = _safe_output(output, [run]) + config = json.loads((run / "config.json").read_text()) + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if array_hash(world.answers) != config["truth_sha256"]: + raise ValueError("Two-step world differs from trained world") + device = torch.device(device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + jobs = [ + ( + f"learning-{step}", + run / f"model-{step}.pt", + world.answers, + run / f"predictions-{step}.npz", + ) + for step in learning_steps + ] + if include_edits: + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + for kind in ("coherent", "exception"): + for scope in ("mlp", "all"): + dest = run / "edits" / f"{name}-{kind}-{scope}" + jobs.append( + ( + dest.name, + dest / "model-final.pt", + pair[kind], + dest / f"predictions-{config['study']['edit_steps']}.npz", + ) + ) + for label, checkpoint, answers, direct_path in jobs: + dest = output / label + dest.mkdir(parents=True, exist_ok=True) + identity = { + "run": str(run), + "checkpoint": str(checkpoint), + "checkpoint_sha256": file_sha256(checkpoint), + "direct_predictions_sha256": file_sha256(direct_path), + "config_sha256": file_sha256(run / "config.json"), + "diagnostic_source_sha256": file_sha256(__file__), + "answer_sha256": array_hash(answers), + "batch_size": batch_size, + "device_type": device.type, + "torch": torch.__version__, + "precision": "BF16 autocast; FP32 weights" if device.type == "cuda" else "FP32", + } + complete_path = dest / "complete.json" + if complete_path.exists(): + saved = json.loads(complete_path.read_text()) + if saved["identity"] != identity: + raise ValueError(f"Changed diagnostic identity: {dest}") + continue + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + with np.load(direct_path) as data: + direct = {k: data[k] for k in ("prediction", "ended", "correct")} + score_saved_arrays(direct, answers) + rows = [] + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device, batch_size, answers) + ids = world.derived_ids[chain] + arrays.update({f"direct_{k}": v[ids] for k, v in direct.items()}) + np.savez_compressed(dest / f"{name}.npz", **arrays) + for split, mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("trained", np.isin(ids, world.train_ids[chain])), + ("heldout", np.isin(ids, world.heldout_ids[chain])), + ): + for population, population_mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + selected = mask & population_mask + n = int(selected.sum()) + rows.append( + { + "chain": name, + "split": split, + "population": population, + "n": n, + **{ + key: int(arrays[key][selected].sum()) + for key in ( + "correct", + "direct_correct", + "bridge_valid", + "bridge_correct", + ) + }, + } + ) + _write_csv(dest / "summary.csv", rows) + write_json( + complete_path, + { + "identity": identity, + "complete": True, + "queries": int(world.derived_ids.size), + "oracle_bridging": False, + }, + ) + del model, saved + if device.type == "cuda": + torch.cuda.empty_cache() + print( + json.dumps({"event": "two_step_complete", "run": str(run), "case": label}), flush=True + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_path_minimal.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_path_minimal.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2ed53451de1a88abe78ee5e58cb49745597c2b --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_path_minimal.py @@ -0,0 +1,379 @@ +"""Two-layer follow-up: common-error removal versus competing new answers.""" + +import argparse +import fcntl +import itertools +import json +import os +import subprocess +import sys +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig +from .bios_path_transfer import ROOT, inner, norm, path_mode, sha, stamp, tensor_sha + +CONFIG = ROOT / "configs/bios-path-minimal-v1.json" + + +def toy_data(config, device): + people = config["people"] + person = torch.arange(people, device=device).repeat_interleave(3) + relation = torch.arange(3, device=device).repeat(people) + value_start = 3 + people + 3 + tokens = torch.stack( + (torch.ones_like(person), 3 + person, 3 + people + relation, torch.full_like(person, 2)), -1 + ) + labels = value_start + (person + (relation == 2)) % 3 + return tokens, labels, value_start + + +def probe_data(config, person, kind, device): + tokens, old, values = toy_data(config, device) + ids = torch.arange(person * 3, person * 3 + 3, device=device) + a, b, c = values + (person + 1) % 3, values + (person + 2) % 3, values + person % 3 + labels = old[ids].clone() + labels[0], labels[1] = a if kind == "coherent" else b, a + return tokens[ids], labels, (a, b, c) + + +def gradients(model, tokens, labels, arm): + projection = model.blocks[0].mlp.down + captured = {} + + def hook(module, inputs, output): + captured["z"], captured["h"] = inputs[0], output + + handle = projection.register_forward_hook(hook) + try: + with path_mode(model, 0, arm): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits.double(), labels, reduction="none") + actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) + z, delta = captured["z"].detach(), delta.detach() + g = torch.einsum("btd,btk->btdk", delta, z).sum(1) + if norm(g.sum(0) - actual) / max(norm(actual), 1e-30) > 5e-5: + raise ValueError("Minimal-model gradient reconstruction failed") + return {"logits": logits.detach(), "loss": loss.detach(), "g": g, "z": z, "delta": delta} + finally: + handle.remove() + + +@torch.no_grad() +def evaluate(model, tokens, labels, values): + logits = model(tokens)[:, -1].double() + p = logits.softmax(-1) + a, b, c = values + return { + "loss": F.cross_entropy(logits, labels, reduction="none").cpu().tolist(), + "prediction": logits.argmax(-1).cpu().tolist(), + "probabilities_abc": p[:, [a, b, c]].cpu().tolist(), + "source_target_probability": p[0, labels[0]].item(), + "derived_margin_ab": (logits[1, a] - logits[1, b]).item(), + "isotropic_same_probability_reference": (p[1].square().sum() - p[1, a] - p[1, b]).item(), + } + + +def freeze(config): + directory = ROOT / config["artifacts"] + directory.mkdir(parents=True, exist_ok=True) + path = directory / "preregistration-lock.json" + if path.exists(): + raise FileExistsError("Cannot replace minimal-model prospective lock") + section = ( + "### 18.7 " + (ROOT / "docs/experimental-protocol.md").read_text().split("### 18.7 ", 1)[1] + ) + (directory / "preregistration.md").write_text(section) + files = [ + CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_path_minimal.py", + ROOT / "scripts/analyze_bios_path_margin.py", + ROOT / "tests/test_bios_path_minimal.py", + ROOT / "src/llm_memory_editability/bios_path_transfer.py", + ROOT / "src/llm_memory_editability/bios_model.py", + ROOT / "docs/development-artifacts/path-transfer-v1/audit.json", + ] + sources = {} + for file in files: + relative = file.relative_to(ROOT) + sources[str(relative)] = sha(file) + destination = directory / "frozen-files" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(file.read_bytes()) + write_json( + path, + { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(directory / "preregistration.md"), + "torch": torch.__version__, + }, + ) + return {"lock": str(path), "sha256": sha(path)} + + +def verify(config): + directory = ROOT / config["artifacts"] + path = directory / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Minimal config/runtime changed") + for name, digest in lock["sources"].items(): + if sha(ROOT / name) != digest: + raise ValueError("Minimal frozen source changed: " + name) + if sha(directory / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Minimal protocol changed") + return sha(path) + + +def learn(config, seed, device, out): + torch.manual_seed(seed) + tokens, labels, values = toy_data(config, device) + model = CausalLM(ModelConfig(values + 3, config["width"], 2, config["heads"], context=8)).to( + device + ) + if (out / "parent.pt").exists(): + saved = torch.load(out / "parent.pt", map_location=device, weights_only=False) + model.load_state_dict(saved["model"]) + return model + optimizer = torch.optim.AdamW( + model.parameters(), lr=config["train_lr"], weight_decay=config["train_weight_decay"] + ) + trajectory = [] + for step in range(config["train_steps"] + 1): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits, labels) + if step in (0, 128, 512, config["train_steps"]): + trajectory.append( + { + "step": step, + "loss": loss.item(), + "accuracy": logits.argmax(-1).eq(labels).float().mean().item(), + } + ) + if step == config["train_steps"]: + break + optimizer.zero_grad(set_to_none=True) + loss.backward() + optimizer.step() + torch.save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": config["train_steps"], + }, + out / "parent.pt", + ) + write_json(out / "learning.json", trajectory) + return model + + +def trajectory(model, parent, config, person, kind, arm, device, directory): + model.load_state_dict(parent) + model.eval() + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name == config["target_parameter"]) + tokens, labels, values = probe_data(config, person, kind, device) + w = model.blocks[0].mlp.down.weight + timeline, steps, factors = [], [], [] + for step in range(config["edit_steps"] + 1): + measure = step % config["measure_every"] == 0 or step == config["edit_steps"] + full = gradients( + model, tokens if measure else tokens[:1], labels if measure else labels[:1], "full" + ) + source = full if arm == "full" else gradients(model, tokens[:1], labels[:1], arm) + if not torch.equal(full["logits"][:1], source["logits"][:1]): + # Different batch sizes allow only normal FP32 GEMM rounding. + if (full["logits"][:1] - source["logits"][:1]).abs().max().item() > 3e-5: + raise ValueError("Minimal forward mismatch") + raw, original = source["g"][0], full["g"][0] + direction = raw * (norm(original) / norm(raw)) if norm(raw) else raw + if measure: + row = { + "step": step, + **evaluate(model, tokens, labels, values), + "source_gradient_norm": norm(original), + "intervened_gradient_norm": norm(raw), + "kernel_source": inner(full["g"][0], direction), + "kernel_derived": inner(full["g"][1], direction), + "kernel_retention": inner(full["g"][2], direction), + "kernel_derived_full": inner(full["g"][1], original), + } + timeline.append(row) + factors.append( + { + key: value.detach().cpu().numpy() + for key, value in { + "z": full["z"], + "delta": full["delta"], + "source_z": source["z"][:1], + "source_delta": source["delta"][:1], + }.items() + } + ) + if step == config["edit_steps"]: + break + before_weight = w.detach().clone() if measure else None + with torch.no_grad(): + w.add_(direction, alpha=-config["edit_lr"]) + if measure: + after = evaluate(model, tokens, labels, values) + actual_delta = w.detach() - before_weight + row["one_step_observed_derived"] = after["loss"][1] - row["loss"][1] + row["one_step_predicted_derived"] = inner(full["g"][1], actual_delta) + row["one_step_margin_change"] = after["derived_margin_ab"] - row["derived_margin_ab"] + steps.append( + { + "step": step, + "source_loss": full["loss"][0].item(), + "direction_norm": norm(direction), + "source_gradient_norm": norm(original), + } + ) + for name, value in model.state_dict().items(): + if name != config["target_parameter"] and not torch.equal(value, parent[name]): + raise ValueError("Minimal frozen parameter changed") + directory.mkdir(parents=True, exist_ok=True) + write_json( + directory / "trajectory.json", + { + "person": person, + "kind": kind, + "arm": arm, + "values_abc": values, + "labels": labels.cpu().tolist(), + "timeline": timeline, + "steps": steps, + }, + ) + np.savez_compressed( + directory / "factors.npz", + **{key: np.stack([factor[key] for factor in factors]) for key in factors[0]}, + ) + torch.save(w.detach().cpu(), directory / "edited-weight.pt") + write_json( + directory / "complete.json", + { + "finished_at": stamp(), + "steps": len(steps), + "weight_sha256": tensor_sha(w), + "frozen_parameters_unchanged": True, + "files": { + name: sha(directory / name) + for name in ("trajectory.json", "factors.npz", "edited-weight.pt") + }, + }, + ) + + +def run(config, seed, device): + lock_hash = verify(config) + if seed not in config["seeds"]: + raise ValueError("Unknown seed") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + out = ROOT / config["output"] / f"seed-{seed}" + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + write_json( + out / "runtime.json", + { + "started_at": stamp(), + "lock_sha256": lock_hash, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + ) + model = learn(config, seed, device, out) + parent = {k: v.detach().clone() for k, v in model.state_dict().items()} + for person, kind, arm in itertools.product( + config["people_to_edit"], config["kinds"], config["arms"] + ): + directory = out / f"person-{person}-{kind}-{arm}" + if not (directory / "complete.json").exists(): + trajectory(model, parent, config, person, kind, arm, device, directory) + print( + json.dumps( + { + "event": "trajectory", + "seed": seed, + "person": person, + "kind": kind, + "arm": arm, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "finished_at": stamp(), + "lock_sha256": lock_hash, + "files": { + str(path.relative_to(out)): sha(path) + for path in out.rglob("*") + if path.is_file() and path != out / "complete.json" and path.name != ".lock" + }, + }, + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("freeze", "worker", "dispatch")) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--gpus", nargs="+", type=int, default=[5, 8]) + args = parser.parse_args() + config = json.loads(CONFIG.read_text()) + if args.command == "freeze": + print(json.dumps(freeze(config))) + elif args.command == "worker": + run(config, args.seed, torch.device(args.device)) + else: + verify(config) + output = ROOT / config["output"] + output.mkdir(parents=True, exist_ok=True) + workers = [] + for index, seed in enumerate(config["seeds"]): + log = (output / f"seed-{seed}.log").open("a") + env = { + **os.environ, + "CUDA_VISIBLE_DEVICES": str(args.gpus[index % len(args.gpus)]), + "PYTHONPATH": str(ROOT / "src"), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + proc = subprocess.Popen( + [ + sys.executable, + str(ROOT / "scripts/run_bios_path_minimal.py"), + "worker", + "--seed", + str(seed), + ], + env=env, + cwd=ROOT, + stdout=log, + stderr=subprocess.STDOUT, + ) + workers.append((proc, log)) + codes = [] + for proc, log in workers: + codes.append(proc.wait()) + log.close() + write_json(output / "dispatch.json", {"finished_at": stamp(), "returncodes": codes}) + if any(codes): + raise RuntimeError("Minimal worker failed; see retained logs") + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_path_transfer.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_path_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..0c54e9cfda468b9a153577dd716a037dde1577f1 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_path_transfer.py @@ -0,0 +1,653 @@ +"""Prospective v2.13: forward-preserving path interventions and local transfer. + +Only a single MLP output weight is differentiated/updated in production. +Downstream parameters are frozen; the custom attention paths alter its input VJP. +""" + +import argparse +import fcntl +import hashlib +import itertools +import json +import os +import platform +import subprocess +import sys +import time +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path +from types import MethodType + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import edit_pair, make_cross_world +from .bios_cross_train import tensor_queries +from .bios_data import EOS, array_hash, write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = ROOT / "configs/bios-path-transfer-v1.json" +ARMS = ("full", "no_cross", "no_mlp", "fixed_qk") + + +def stamp(): + return datetime.now(timezone.utc).isoformat() + + +def sha(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def tensor_sha(value): + return hashlib.sha256(value.detach().cpu().contiguous().numpy().tobytes()).hexdigest() + + +def inner(a, b): + return (a.double() * b.double()).sum().item() + + +def norm(a): + return a.double().norm().item() + + +def relative(a, b): + return norm(a - b) / max(norm(b), 1e-30) + + +def cosine(a, b): + return inner(a, b) / max(norm(a) * norm(b), 1e-30) + + +def attention_surrogate(module, x, mode): + """Correct input Jacobian for frozen QK, or only the diagonal position blocks. + + no_cross makes T copies of the input: copy s only differentiates x_s, + then computes output s with the full original causal context. Thus Q_s, + K_s and V_s derivatives survive; all x_t -> output_s, t != s vanish. + """ + batch, length, width = x.shape + heads, dim = module.heads, width // module.heads + if mode == "no_cross": + expanded = x[:, None].expand(batch, length, length, width) + diagonal = torch.eye(length, device=x.device, dtype=x.dtype)[None, :, :, None] + routed = expanded.detach() + diagonal * (expanded - expanded.detach()) + q, k, v = module.qkv(routed).reshape(batch, length, length, 3, heads, dim).unbind(3) + index = torch.arange(length, device=x.device) + q = q[:, index, index] # B, query, H, D + scores = torch.einsum("bshd,bsthd->bhst", q, k) / dim**0.5 + mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() + a = scores.masked_fill(~mask, -torch.inf).softmax(-1) + output = torch.einsum("bhst,bsthd->bshd", a, v).reshape(batch, length, width) + else: + q, k, v = module.qkv(x).reshape(batch, length, 3, heads, dim).unbind(2) + scores = torch.einsum("bshd,bthd->bhst", q, k) / dim**0.5 + mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() + a = scores.masked_fill(~mask, -torch.inf).softmax(-1) + if mode == "fixed_qk": + a = a.detach() + elif mode != "manual_full": + raise ValueError(mode) + output = torch.einsum("bhst,bthd->bshd", a, v).reshape(batch, length, width) + return module.proj(output) + + +@contextmanager +def path_mode(model, layer, arm): + if arm not in (*ARMS, "manual_full"): + raise ValueError(arm) + saved = [] + try: + for block in model.blocks[layer + 1 :]: + if arm == "no_mlp": + module = block.mlp + original = module.forward + + def stopped(self, x, original=original): + with torch.no_grad(): + return original(x) + + module.forward = MethodType(stopped, module) + saved.append((module, original)) + elif arm != "full": + module = block.attention + original = module.forward + + def altered(self, x, original=original, arm=arm): + with torch.no_grad(): + reference = original(x) + surrogate = attention_surrogate(self, x, arm) + return reference + (surrogate - surrogate.detach()) + + module.forward = MethodType(altered, module) + saved.append((module, original)) + yield + finally: + for module, original in saved: + module.forward = original + + +def cases(world): + result = [] + for chain in range(2): + pair = edit_pair(world, chain) + for group in pair["groups"]: + members = np.flatnonzero(world.memberships[chain] == group) + eligible = members[ + np.isin(world.derived_ids[chain, members], world.heldout_ids) + & np.isin(world.derived_ids[chain, members], pair["conflict_D"]) + ] + if not len(eligible): + raise ValueError("No prespecified heldout conflict person") + person = int(eligible[0]) + others = members[ + (members != person) + & ~world.exceptions[chain, members] + & np.isin(world.derived_ids[chain, members], world.heldout_ids) + ] + if not len(others): + raise ValueError("No prespecified second heldout person") + other = int(others[0]) + distant = int(np.flatnonzero(~np.isin(world.memberships[chain], pair["groups"]))[0]) + root = int(world.root_ids[chain, group]) + actual = int(world.actual_ids[chain, person]) + default = int(pair["coherent"][root]) + alternative = int(pair["exception"][actual]) + if default == alternative: + raise ValueError("Selected person is not a new conflict") + for kind in ("root", "coherent", "conflict"): + source = root if kind == "root" else actual + target = alternative if kind == "conflict" else default + associated = actual if kind == "root" else root + ids = [ + source, + int(world.derived_ids[chain, person]), + int(world.derived_ids[chain, other]), + associated, + int(world.actual_ids[1 - chain, person]), + int(world.actual_ids[chain, distant]), + ] + targets = [target, default, default, default, *world.answers[ids[-2:]].tolist()] + result.append( + { + "name": f"chain-{chain}-group-{int(group)}-{kind}", + "chain": chain, + "group": int(group), + "kind": kind, + "person": person, + "other_person": other, + "ids": ids, + "targets": targets, + "old_targets": world.answers[ids].tolist(), + "roles": [ + "source", + "derived_same", + "derived_other", + "associated", + "retention_local", + "retention_distant", + ], + } + ) + return result + + +def example_data(world, case, device): + # Use the original interface, including teacher-forced answer for EOS loss. + targets = world.answers.copy() + targets[case["ids"]] = case["targets"] + all_data = tensor_queries(world, device, targets) + ids = torch.tensor(case["ids"], device=device) + return {key: value[ids] for key, value in all_data.items()} + + +def subset(data, ids): + return {key: value[ids] for key, value in data.items()} + + +def losses(logits, labels): + return ( + F.cross_entropy( + logits.double().reshape(-1, logits.shape[-1]), labels.reshape(-1), reduction="none" + ) + .reshape(-1, 2) + .mean(-1) + ) + + +def measure(model, data, layer, arm): + projection = model.blocks[layer].mlp.down + captured = {} + + def hook(module, inputs, output): + captured["z"], captured["h"] = inputs[0], output + + handle = projection.register_forward_hook(hook) + try: + with path_mode(model, layer, arm): + logits = model(data["tokens"], data["positions"]) + loss = losses(logits, data["labels"]) + actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) + z = captured["z"].detach() + delta = delta.detach() + per_position = torch.einsum("btd,btk->btdk", delta, z) + mask = torch.zeros(z.shape[:2], device=z.device, dtype=torch.bool) + mask.scatter_(1, data["positions"], True) + g = per_position.sum(1) + supervised = (per_position * mask[:, :, None, None]).sum(1) + unsupervised = (per_position * ~mask[:, :, None, None]).sum(1) + return { + "z": z, + "delta": delta, + "g": g, + "supervised": supervised, + "unsupervised": unsupervised, + "mask": mask, + "loss": loss.detach(), + "logits": logits.detach(), + "reconstruction_error": relative(g.sum(0), actual), + "decomposition_error": relative(supervised + unsupervised, g), + } + finally: + handle.remove() + + +@torch.no_grad() +def assess(model, data): + logits = model(data["tokens"], data["positions"]) + loss = losses(logits, data["labels"]) + first = model(data["prompts"], (data["lengths"] - 1)[:, None])[:, 0].argmax(-1) + continuation = data["tokens"].clone() + rows = torch.arange(len(first), device=first.device) + continuation[rows, data["lengths"]] = first + ended = model(continuation, data["lengths"][:, None])[:, 0].argmax(-1).eq(EOS) + return loss, first, ended + + +def frozen_files(config): + paths = [ + CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_path_transfer.py", + ROOT / "tests/test_bios_path_transfer.py", + ] + for name in ("bios_model.py", "bios_cross.py", "bios_cross_train.py", "bios_data.py"): + paths.append(ROOT / "src/llm_memory_editability" / name) + for world in config["worlds"]: + directory = ROOT / config["source_world_root"] / f"world-{world}" + paths += [ + directory / "world.npz", + directory / "metadata.json", + directory / "evaluation.npz", + ] + for world, seed in itertools.product(config["worlds"], config["seeds"]): + directory = ROOT / config["parent_root"] / f"world-{world}-seed-{seed}-neither" + paths += [directory / "config.json", directory / "learning-complete.json"] + paths += [directory / f"model-{step}.pt" for step in config["states"]] + return paths + + +def freeze(config): + directory = ROOT / config["artifacts"] + directory.mkdir(parents=True, exist_ok=True) + lock_path = directory / "preregistration-lock.json" + if lock_path.exists(): + raise FileExistsError("Cannot replace a prospective lock") + protocol = ( + "## 18. " + (ROOT / "docs/experimental-protocol.md").read_text().split("## 18. ", 1)[1] + ) + (directory / "preregistration.md").write_text(protocol) + manifests = {} + for world in config["worlds"]: + generated = make_cross_world(world, ROOT / config["source_world_root"]) + selected = cases(generated) + if len(selected) != config["cases_per_state"]: + raise ValueError("Case count mismatch") + manifests[str(world)] = { + "truth_sha256": array_hash(generated.answers), + "prompts_sha256": array_hash(generated.prompts), + "cases": selected, + } + write_json(directory / "cases.json", manifests) + sources = {} + for path in frozen_files(config): + relative_path = path.relative_to(ROOT) + sources[str(relative_path)] = sha(path) + if relative_path.parts[0] in ("src", "scripts", "tests", "configs"): + destination = directory / "frozen-files" / relative_path + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(path.read_bytes()) + lock = { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(directory / "preregistration.md"), + "cases_sha256": sha(directory / "cases.json"), + "torch": torch.__version__, + "numpy": np.__version__, + "python": platform.python_version(), + } + write_json(lock_path, lock) + return {"path": str(lock_path), "sha256": sha(lock_path)} + + +def verify_lock(config): + directory = ROOT / config["artifacts"] + path = directory / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Frozen config/runtime mismatch") + for name, digest in lock["sources"].items(): + if sha(ROOT / name) != digest: + raise ValueError("Frozen input changed: " + name) + for name, key in (("preregistration.md", "protocol_sha256"), ("cases.json", "cases_sha256")): + if sha(directory / name) != lock[key]: + raise ValueError("Prospective manifest changed") + return sha(path) + + +def save_factors(path, baseline, sources, data): + arrays = { + "positions": data["positions"].cpu().numpy(), + "labels": data["labels"].cpu().numpy(), + "tokens": data["tokens"].cpu().numpy(), + } + for prefix, result in [("evaluation", baseline), *sources.items()]: + for key in ("z", "delta", "loss"): + arrays[prefix + "_" + key] = result[key].cpu().numpy() + np.savez_compressed(path, **arrays) + + +def run_case(model, world, case, config, destination): + layer = config["target_layer"] + w = model.blocks[layer].mlp.down.weight + parent = w.detach().clone() + frozen_before = { + name: tensor_sha(value) + for name, value in model.state_dict().items() + if name != config["target_parameter"] + } + data = example_data(world, case, w.device) + baseline = measure(model, data, layer, "full") + before, old_prediction, old_ended = assess(model, data) + sources, diagnostics, updates = {}, [], [] + with torch.no_grad(): + if not torch.equal(before, baseline["loss"]): + raise ValueError("Evaluation/gradient forward mismatch") + for arm in config["arms"]: + source = measure(model, subset(data, slice(0, 1)), layer, arm) + sources[arm] = source + error = (source["logits"] - sources["full"]["logits"]).abs().max().item() + if error > config["forward_tolerance"]: + raise ValueError(f"Forward preservation failed: {error}") + if ( + max(source["reconstruction_error"], baseline["reconstruction_error"]) + > config["gradient_tolerance"] + ): + raise ValueError("Outer-product reconstruction failed") + direction = source["g"][0] + gfull = sources["full"]["g"][0] + if arm == "no_cross" and norm(source["unsupervised"]) > 1e-9: + raise ValueError("Cross-position cut did not eliminate unsupervised-position gradient") + for j, role in enumerate(case["roles"]): + row = { + "arm": arm, + "role": role, + "probe": j, + "forward_error": error, + "reconstruction_error": source["reconstruction_error"], + "gradient_norm": norm(direction), + "gradient_cosine_full": cosine(direction, gfull), + "supervised_norm": norm(source["supervised"]), + "unsupervised_norm": norm(source["unsupervised"]), + "kernel": inner(baseline["g"][j], direction), + "source_loss": source["loss"].item(), + "probe_loss": before[j].item(), + } + for left, right in itertools.product(("supervised", "unsupervised"), repeat=2): + row[f"kernel_{left}_{right}"] = inner(baseline[left][j], source[right][0]) + diagnostics.append(row) + for scale, fraction in itertools.product(config["scales"], config["step_fractions"]): + denominator = norm(gfull if scale == "shared_lr" else direction) + eta = fraction * norm(parent) / denominator if denominator else 0.0 + with torch.no_grad(): + w.copy_(parent - eta * direction) + displacement = w.detach() - parent + weight_hash = tensor_sha(w) + after, predicted_token, ended = assess(model, data) + predicted = (baseline["g"].double() * displacement.double()).sum((-1, -2)) + for j, role in enumerate(case["roles"]): + updates.append( + { + "arm": arm, + "scale": scale, + "fraction": fraction, + "eta": eta, + "update_norm": norm(displacement), + "weight_sha256": weight_hash, + "role": role, + "probe": j, + "id": case["ids"][j], + "target": case["targets"][j], + "old_target": case["old_targets"][j], + "before": before[j].item(), + "after": after[j].item(), + "observed_change": (after[j] - before[j]).item(), + "predicted_change": predicted[j].item(), + "ideal_predicted_change": -eta * inner(baseline["g"][j], direction), + "baseline_prediction": int(old_prediction[j]), + "baseline_ended": bool(old_ended[j]), + "prediction": int(predicted_token[j]), + "ended": bool(ended[j]), + } + ) + with torch.no_grad(): + w.copy_(parent) + if not torch.equal(w, parent): + raise ValueError("Parent weight was not restored") + frozen_after = { + name: tensor_sha(value) + for name, value in model.state_dict().items() + if name != config["target_parameter"] + } + if frozen_before != frozen_after: + raise ValueError("A frozen parameter changed") + destination.mkdir(parents=True, exist_ok=True) + save_factors(destination / "factors.npz", baseline, sources, data) + write_json( + destination / "measurements.json", + {"case": case, "diagnostics": diagnostics, "updates": updates}, + ) + write_json( + destination / "receipt.json", + { + "finished_at": stamp(), + "files": { + name: sha(destination / name) for name in ("factors.npz", "measurements.json") + }, + "baseline_reconstruction_error": baseline["reconstruction_error"], + "frozen_parameters_unchanged": True, + "parent_restored": True, + }, + ) + + +def verify_receipt(directory): + receipt = json.loads((directory / "receipt.json").read_text()) + for name, digest in receipt["files"].items(): + if sha(directory / name) != digest: + raise ValueError("Receipt mismatch: " + str(directory / name)) + + +def run(config, world_id, seed, device): + lock_hash = verify_lock(config) + if world_id not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("Worker outside the frozen matrix") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + world = make_cross_world(world_id, ROOT / config["source_world_root"]) + name = f"world-{world_id}-seed-{seed}-neither" + source = ROOT / config["parent_root"] / name + out = ROOT / config["output"] / name + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as stream: + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + started = time.monotonic() + write_json( + out / "runtime.json", + { + "started_at": stamp(), + "lock_sha256": lock_hash, + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if "cuda" in str(device) else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "torch": torch.__version__, + }, + ) + for step in config["states"]: + checkpoint = torch.load( + source / f"model-{step}.pt", map_location="cpu", weights_only=False + ) + if checkpoint["step"] != step: + raise ValueError("Parent step mismatch") + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + model.eval() + for pname, parameter in model.named_parameters(): + parameter.requires_grad_(pname == config["target_parameter"]) + selected = cases(world) + state_out = out / f"step-{step}" + state_out.mkdir(exist_ok=True) + # Original-forward repeated gradient, not a new scientific sample. + sham_data = subset(example_data(world, selected[0], device), slice(0, 1)) + first = measure(model, sham_data, config["target_layer"], "full") + second = measure(model, sham_data, config["target_layer"], "full") + sham_error = relative(first["g"], second["g"]) + if sham_error > config["gradient_tolerance"]: + raise ValueError("Sham gradient failed") + write_json(state_out / "sham.json", {"relative_gradient_error": sham_error}) + for case in selected: + destination = state_out / case["name"] + if (destination / "receipt.json").exists(): + verify_receipt(destination) + else: + run_case(model, world, case, config, destination) + print( + json.dumps( + { + "event": "case", + "world": world_id, + "seed": seed, + "step": step, + "case": case["name"], + } + ), + flush=True, + ) + del model, checkpoint + files = { + str(path.relative_to(out)): sha(path) + for path in out.rglob("*") + if path.is_file() and path.name not in (".lock", "complete.json") + } + write_json( + out / "complete.json", + { + "finished_at": stamp(), + "seconds": time.monotonic() - started, + "lock_sha256": lock_hash, + "cases": len(config["states"]) * len(selected), + "files": files, + }, + ) + + +def dispatch(config, gpus): + verify_lock(config) + output = ROOT / config["output"] + output.mkdir(parents=True, exist_ok=True) + jobs = list(itertools.product(config["worlds"], config["seeds"])) + active, finished = [], [] + with (output / ".dispatch.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + while jobs or active: + for gpu in gpus: + if jobs and not any(item["gpu"] == gpu for item in active): + world, seed = jobs.pop(0) + path = output / f"world-{world}-seed-{seed}-neither" + if (path / "complete.json").exists(): + finished.append({"world": world, "seed": seed, "reused": True}) + continue + log = (output / f"world-{world}-seed-{seed}.log").open("a") + env = { + **os.environ, + "CUDA_VISIBLE_DEVICES": str(gpu), + "PYTHONPATH": str(ROOT / "src"), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + command = [ + sys.executable, + str(ROOT / "scripts/run_bios_path_transfer.py"), + "worker", + "--world", + str(world), + "--seed", + str(seed), + "--device", + "cuda:0", + ] + proc = subprocess.Popen( + command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT + ) + active.append( + {"gpu": gpu, "world": world, "seed": seed, "process": proc, "log": log} + ) + for item in active[:]: + code = item["process"].poll() + if code is not None: + item["log"].close() + record = {k: item[k] for k in ("gpu", "world", "seed")} + finished.append({**record, "returncode": code}) + active.remove(item) + write_json( + output / "dispatch.json", + { + "updated_at": stamp(), + "pending": jobs, + "running": [{k: x[k] for k in ("gpu", "world", "seed")} for x in active], + "finished": finished, + }, + ) + if active: + time.sleep(2) + if any(item.get("returncode", 0) for item in finished): + raise RuntimeError("One or more workers failed; inspect preserved logs") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("freeze", "worker", "dispatch")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--gpus", type=int, nargs="+", default=[5, 8]) + args = parser.parse_args() + config = json.loads(CONFIG.read_text()) + if args.command == "freeze": + print(json.dumps(freeze(config))) + elif args.command == "worker": + run(config, args.world, args.seed, torch.device(args.device)) + else: + dispatch(config, args.gpus) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_readout_control.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_readout_control.py new file mode 100644 index 0000000000000000000000000000000000000000..877089e7e83d985cfb9e4b5e65920b2db8312d4d --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_readout_control.py @@ -0,0 +1,373 @@ +"""H5: original E93 exception edits of all weights except tied token/readout weights.""" + +import argparse +import fcntl +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_metrics, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +SCOPE = "all-freeze-embedding" +STUDY = { + "protocol": "v2.8-h5-readout-control-E93", + "widths": [256, 768], + "parent_step": 15360, + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kind": "exception", + "scope": SCOPE, + "frozen": "token.weight, shared by input embedding and output F.linear readout", + "trainable": "all other parameters, including absolute position embedding", + "lr": 3e-5, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 48, + "E": 93, + "D": 96, + "R": 4096, + "reference_scopes": ["mlp", "all"], + "selection": "all fixed512 endpoints; no best step", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("H5 configuration differs from the fixed contract") + + +def control_sources(): + return { + **source_hashes(), + "bios_cross_continue.py": file_hash(Path(__file__).with_name("bios_cross_continue.py")), + Path(__file__).name: file_hash(__file__), + } + + +def select_control_parameters(model): + """The ordinary model passes this same Parameter directly to F.linear.""" + excluded = id(model.token.weight) + selected = [] + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) != excluded) + parameter.grad = None + if parameter.requires_grad: + selected.append(parameter) + assert model.position.weight.requires_grad and not model.token.weight.requires_grad + return selected + + +def sampling_stream(world_seed, chain, steps=512, batch=128): + rng = rng_for(world_seed, 908, chain) + return rng.integers(93, size=(steps, batch)), rng.integers(4096, size=(steps, batch)) + + +def score_arrays(arrays, truth): + for key in ("prediction", "ended", "correct"): + if arrays[key].shape != truth.shape: + raise ValueError("H5 prediction array shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("H5 EOS/correct flags must be Boolean") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def validate_parent_config(config, world): + width = config["model"]["width"] + if width not in STUDY["widths"] or config["world"] not in (0, 1): + raise ValueError("H5 parent outside original size/world matrix") + expected = dict( + vocab_size=world.vocab_size, width=width, layers=8, heads=width // 64, context=128 + ) + if config["model"] != expected or config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("H5 needs original unrestricted low-prevalence architecture") + expected_study = dict( + steps=15360, + lr=1e-4, + documents_per_step=16, + facts_per_document=10, + QA_per_chain_per_step=20, + document_QA_weights=[0.8, 0.2], + ) + if any(config["study"][key] != value for key, value in expected_study.items()): + raise ValueError("H5 parent is not the original learning budget") + if config["seed"] not in (0, 1) or config["condition"] not in CONDITIONS: + raise ValueError("H5 parent outside original initialization/organization matrix") + if config["sources"] != source_hashes() or config["truth_sha256"] != array_hash(world.answers): + raise ValueError("H5 parent source or truth mismatch") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("H5 numerical software differs from parent") + + +def reference_contract(parent, world, old_arrays): + hashes = {} + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + assert len(pair["E"]) == 93 and len(pair["D"]) == 96 and len(pair["replay"]) == 4096 + e, r = sampling_stream(world.seed, chain) + for scope in ("mlp", "all"): + dest = parent / "edits" / f"{name}-exception-{scope}" + with np.load(dest / "sets.npz") as actual: + for key, value in pair.items(): + np.testing.assert_array_equal(actual[key], value) + np.testing.assert_array_equal(actual["old_correct"], old_arrays["correct"]) + np.testing.assert_array_equal(actual["edit_sampling"], e) + np.testing.assert_array_equal(actual["replay_sampling"], r) + points = json.loads((dest / "trajectory.json").read_text()) + if [point["step"] for point in points] != list(CHECKPOINTS): + raise ValueError("Original MLP/All reference checkpoint grid differs") + if json.loads((dest / "complete.json").read_text())["status"] != "complete": + raise ValueError("Original MLP/All reference incomplete") + for step in CHECKPOINTS: + with np.load(dest / f"predictions-{step}.npz") as saved: + arrays = score_arrays(dict(saved), pair["exception"]) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], old_arrays[key]) + for filename in ( + "sets.npz", + "trajectory.json", + "complete.json", + *(f"predictions-{step}.npz" for step in CHECKPOINTS), + ): + hashes[str((dest / filename).relative_to(parent))] = file_hash(dest / filename) + return hashes + + +def load_parent(parent): + config = json.loads((parent / "config.json").read_text()) + world = make_cross_world(config["world"]) + validate_parent_config(config, world) + with np.load(parent / "predictions-15360.npz") as saved: + arrays = score_arrays(dict(saved), world.answers) + references = reference_contract(parent, world, arrays) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if checkpoint["step"] != 15360 or checkpoint["config"] != config["model"]: + raise ValueError("H5 parent checkpoint identity differs") + if ( + complete["status"] != "complete" + or state_hash(checkpoint["model"]) != complete["model_sha256"] + ): + raise ValueError("H5 parent learning checkpoint is not verified complete") + provenance = dict( + directory=str(parent), + model_sha256=complete["model_sha256"], + reference_files_sha256=references, + files_sha256={ + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + ) + return config, world, arrays, checkpoint, provenance + + +def run_case(model, baseline, data, world, parent_arrays, chain, output, identity_hash, device): + dest = output / f"{CHAINS[chain]}-exception-{SCOPE}" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_control_parameters(model) + frozen = baseline["token.weight"] + pair = edit_pair(world, chain) + e, r = sampling_stream(world.seed, chain) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=parent_arrays["correct"], + edit_sampling=e, + replay_sampling=r, + ) + new_data = tensor_queries(world, device, pair["exception"]) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW(selected, lr=3e-5, weight_decay=0.1, fused=device.type == "cuda") + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("H5 resume identity differs") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("H5 resume step differs") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], 3e-5) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS: + if not torch.equal(model.token.weight.detach().cpu(), frozen): + raise ValueError("Frozen input/output token weights changed") + if not timeline or timeline[-1]["step"] != step: + arrays = score_arrays( + evaluate(model, new_data, pair["exception"]), pair["exception"] + ) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_arrays[key]) + timeline.append( + dict( + step=step, + edit_seconds=seconds, + **edit_metrics(world, pair, arrays, parent_arrays["correct"]), + ) + ) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e[step]], device=device) + ri = torch.as_tensor(pair["replay"][r[step]], device=device) + choices = torch.as_tensor(r[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - start + atomic_torch_save( + dict(model=model.state_dict(), config=model.config_dict(), step=512), + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + dict( + status="complete", + scope=SCOPE, + kind="exception", + chain=CHAINS[chain], + final=timeline[-1], + model_sha256=state_hash(model.state_dict()), + frozen_token_sha256=state_hash({"token.weight": frozen}), + ), + ) + print( + json.dumps(dict(event="H5_edit_complete", case=dest.name, final=timeline[-1])), flush=True + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("H5 output must be separate from immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, world, arrays, checkpoint, provenance = load_parent(parent) + device = torch.device(args.device) + identity = dict( + world=world.seed, + seed=config["seed"], + condition=config["condition"], + width=config["model"]["width"], + study=STUDY, + sources=control_sources(), + parent=provenance, + torch=torch.__version__, + cuda=torch.version.cuda, + numpy=np.__version__, + device_type=device.type, + ) + path = output / "config.json" + if path.exists() and json.loads(path.read_text()) != identity: + raise ValueError("Frozen H5 worker contract changed") + if not path.exists(): + write_json(path, identity) + if (output / "complete.json").exists(): + return + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()} + data = tensor_queries(world, device) + try: + observed = score_arrays(evaluate(model, data, world.answers), world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], arrays[key]) + for chain in range(2): + run_case( + model, baseline, data, world, arrays, chain, output, file_hash(path), device + ) + write_json( + output / "complete.json", + dict(status="complete", edit_cases=2, steps=512, scope=SCOPE, finished=time.time()), + ) + except Exception as error: + write_json( + output / "failure.json", + dict(type=type(error).__name__, message=str(error), time=time.time()), + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-readout-control-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_relation_response.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_relation_response.py new file mode 100644 index 0000000000000000000000000000000000000000..2e69b15143ef5b90779481035823b06102c3b5ab --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_relation_response.py @@ -0,0 +1,187 @@ +"""A paired four-cell test of which fact controls a composite answer. + +The editor is unchanged. Derivative probes use answer contrasts, never a +composite target loss. Isolated directions preserve the OTHER direct query's +two a/c and b/c contrasts to first order, not its entire output distribution. +""" + +from dataclasses import replace + +import torch + +from .bios_direction import Suffix +from .bios_direction_cross import cross_tasks + +CELLS = ("aa", "ab", "ba", "bb") +LAYER = 4 + + +def factorial_tasks(world, seed, device): + """Rows select root targets; columns select personal targets; a/b stay fixed.""" + originals = cross_tasks(world, seed, device) + result = [] + for pair_index in range(6): + base = originals[2 * pair_index] + for cell in CELLS: + labels, tokens = base.labels.clone(), base.tokens.clone() + root, actual = base.sets["E"] + labels[root, 0] = base.metadata[cell[0]] + labels[actual, 0] = base.metadata[cell[1]] + labels[base.sets["D"], 0] = base.metadata[cell[0]] + rows = torch.arange(len(tokens), device=tokens.device) + tokens[rows, base.positions[:, 0] + 1] = labels[:, 0] + metadata = dict( + base.metadata, + cell=cell, + pair_index=pair_index, + kind="coherent" if cell[0] == cell[1] else "independent", + root_target=base.metadata[cell[0]], + actual_target=base.metadata[cell[1]], + ) + result.append( + replace( + base, + name=base.name.rsplit("-", 1)[0] + "-" + cell, + labels=labels, + tokens=tokens, + metadata=metadata, + ) + ) + return result + + +def check_reused_task(task, manifest): + """Compare actual information, including teacher-forced EOS prefixes.""" + current = task.manifest() + for key in ("sets", "labels", "old_labels", "tokens_sha256"): + assert current[key] == manifest[key], key + for key in ("world", "seed", "chain", "group", "person", "a", "b", "c", "original_ids"): + assert current["metadata"][key] == manifest["metadata"][key], key + + +def make_probe(model, task): + ids = task.sets["E"] + task.sets["D_focal"] + positions = task.positions[ids, :1] + tokens = task.tokens[ids, :5].clone() + # No desired answer is present even at masked future positions. + tokens.masked_fill_(torch.arange(5, device=tokens.device)[None] > positions, 0) + return Suffix(model, LAYER, tokens, positions) + + +def values(probe, weight, metadata): + logits = probe(weight[None])[0, :, 0] + a, b, c = (metadata[k] for k in ("a", "b", "c")) + contrasts = torch.stack((logits[:, a] - logits[:, c], logits[:, b] - logits[:, c]), -1) + return logits, contrasts + + +def derivatives(probe, weight, metadata): + w = weight.detach().clone().requires_grad_() + logits, contrasts = values(probe, w, metadata) + gradients = torch.stack( + [ + torch.autograd.grad(contrasts[i, j], w, retain_graph=True)[0] + for i in range(3) + for j in range(2) + ] + ).reshape(3, 2, *w.shape) + return logits.detach(), contrasts.detach(), gradients.detach() + + +def isolated_directions(gradients): + """Minimum-norm direct-fact controls; D is excluded from construction. + + A unit control changes the chosen fact's (a-c,b-c) by (+.5,-.5), + hence its a-b contrast by 1; the other fact has both contrasts fixed. + """ + g = gradients[:2].flatten(0, 1).flatten(1).double() + gram = g @ g.T + eig, vec = torch.linalg.eigh(gram) + keep = eig > eig[-1].clamp_min(1e-30) * 1e-10 + inverse = (vec * torch.where(keep, 1 / eig.clamp_min(1e-300), 0)[None]) @ vec.T + targets = torch.tensor([[0.5, -0.5, 0, 0], [0, 0, 0.5, -0.5]], device=g.device) + controls = targets.double() @ inverse @ g + achieved = controls @ g.T + gd = (gradients[2, 0] - gradients[2, 1]).flatten().double() + coefficients = controls @ gd + residual = gd - (gd @ g.T) @ inverse @ g + summary = { + "rank": int(keep.sum()), + "spectrum": eig.cpu().tolist(), + "control_residual": float((achieved - targets).abs().max()), + "root_response": float(coefficients[0]), + "actual_response": float(coefficients[1]), + "unexplained_D_gradient_fraction": float(residual.norm() / gd.norm().clamp_min(1e-30)), + "root_control_norm": float(controls[0].norm()), + "actual_control_norm": float(controls[1].norm()), + } + return controls.reshape(2, *gradients.shape[-2:]).to(gradients.dtype), summary + + +@torch.no_grad() +def calibrate_controls(probe, weight, metadata, gradients, magnitudes): + controls, summary = isolated_directions(gradients) + baseline_logits, baseline = values(probe, weight, metadata) + rows = [] + if summary["control_residual"] > 1e-5: + return summary, rows + for index, name in enumerate(("root", "actual")): + for magnitude in magnitudes: + for sign in (-1, 1): + delta = sign * magnitude * controls[index] + cap = min(1.0, float(1e-3 * weight.norm() / delta.norm().clamp_min(1e-30))) + delta = delta * cap + changed, after = values(probe, weight + delta, metadata) + observed = after - baseline + predicted = (gradients.double() * delta.double()).sum((-1, -2)) + other = 1 - index + logp = baseline_logits.double().log_softmax(-1) + new_logp = changed.double().log_softmax(-1) + kl = (logp.exp() * (logp - new_logp)).sum(-1) + rows.append( + dict( + control=name, + magnitude=magnitude, + sign=sign, + cap=cap, + actual_target_increment=sign * magnitude * cap, + delta_norm=float(delta.norm()), + predicted_ab=(predicted[:, 0] - predicted[:, 1]).cpu().tolist(), + observed_ab=(observed[:, 0] - observed[:, 1]).cpu().tolist(), + other_ac_bc_drift=float(observed[other].abs().max()), + other_output_kl=float(kl[other]), + direct_argmax_changes=int( + (changed[:2].argmax(-1) != baseline_logits[:2].argmax(-1)).sum() + ), + ) + ) + return summary, rows + + +def first_adam_update(model, task, config): + """Exact first-step algebra of the frozen soft-functional Adam editor.""" + ids = task.sets["E"] + task.sets["R"] + suffix = Suffix(model, LAYER, task.tokens[ids], task.positions[ids]) + w = model.blocks[LAYER].mlp.down.weight.detach().clone().requires_grad_() + logits = suffix(w[None])[0] + logp = logits.double().log_softmax(-1) + labels = task.labels[ids] + ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1) + n = len(task.sets["E"]) + # The original-parent KL has exactly zero derivative at the parent. + loss = ce[:n].mean() + ce[n:].mean() + gradient = torch.autograd.grad(loss, w)[0] + m, v = 0.1 * gradient, 0.001 * gradient.square() + t = torch.ones((), device=w.device) + raw = -(m / (1 - 0.9**t)) / ((v / (1 - 0.999**t)).sqrt() + 1e-8) + return config["lr"] * raw + + +def factorial_effects(margins): + aa, ab, ba, bb = (float(margins[cell]) for cell in CELLS) + return dict( + intercept=(aa + ab + ba + bb) / 4, + root=(aa + ab - ba - bb) / 4, + actual=(aa - ab + ba - bb) / 4, + interaction=(aa - ab - ba + bb) / 4, + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..3943eb3bac42c3c9c13d8b3c40061fc830348860 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py @@ -0,0 +1,372 @@ +"""Locked independent-world behavioral confirmation, never a route-mediation claim. + +The original learning implementation and the audited E39 update implementation +are called directly. An external prospective lock is mandatory before execution. +""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_train import learning, source_hashes +from .bios_data import write_json +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import autonomous_two_step +from .bios_shortcut_confirmation_sets import make_confirmation_edit_pair +from .bios_shortcut_control import high_exception_world +from .bios_shortcut_edit_v2 import STUDY as DEVELOPMENT_EDIT_STUDY +from .bios_shortcut_edit_v2 import run_case +from .bios_shortcut_matched_edit import KINDS, PHASES + +PROTOCOL = "v2.9-shortcut-behavior-confirmation" +WORLDS = tuple(range(100, 108)) +LEARNING_CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360) + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + while chunk := stream.read(4 * 1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def confirmation_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + "scripts/prepare_bios_shortcut_confirmation.py": file_hash( + directory.parents[1] / "scripts/prepare_bios_shortcut_confirmation.py" + ), + **{ + name: file_hash(directory / name) + for name in ( + "bios_shortcut_confirmation.py", + "bios_shortcut_confirmation_sets.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit_v2.py", + "bios_cross_continue.py", + "bios_path_diagnostics.py", + ) + }, + } + + +def validate_config(config): + expected = { + "protocol": PROTOCOL, + "worlds": list(WORLDS), + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "phases": list(PHASES), + "chains": list(CHAINS), + "supports": [0, 1], + "width": 256, + "layers": 8, + "heads": 4, + "steps": 15360, + "checkpoints": list(LEARNING_CHECKPOINTS), + "lr": 0.0001, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "learning_runs": 96, + "edit_cases": 768, + "edit_steps": 512, + "edit_checkpoints": [0, 32, 128, 512], + "edit_lr": 0.00003, + "retention_kl": 1.0, + "edit_scope": "mlp", + "edit_mlp_layers": [3, 4, 5], + "edit_batch": 128, + "replay_batch": 128, + "edit_weight_decay": 0.1, + "E": 39, + "D": 96, + "R": 4096, + "base_world_root": "data/bios-shortcut-confirmation-v1", + "source_root": "data/bios-source", + } + for key, value in expected.items(): + if config.get(key) != value: + raise ValueError(f"Prospective confirmation contract differs: {key}") + for key in ("steps", "checkpoints", "lr", "retention_kl", "E", "D", "R"): + source = {"steps": "edit_steps", "checkpoints": "edit_checkpoints", "lr": "edit_lr"} + if DEVELOPMENT_EDIT_STUDY[key] != config[source.get(key, key)]: + raise ValueError(f"Imported E39 scientific update differs: {key}") + if config.get("edit_sampling") != "shared original world932chain stream across supports": + raise ValueError("The two supports retain the original paired sampling stream") + + +def validate_frozen_design(config_path, lock_path): + config = json.loads(Path(config_path).read_text()) + validate_config(config) + lock = json.loads(Path(lock_path).read_text()) + if lock.get("status") != "frozen_before_any_confirmation_model_or_outcome": + raise ValueError("A prospective confirmation lock is required") + if lock["config_sha256"] != file_hash(config_path): + raise ValueError("Confirmation configuration changed after locking") + if lock["sources"] != confirmation_sources(): + raise ValueError("Confirmation scientific sources changed after locking") + environment = {"torch": torch.__version__, "cuda": torch.version.cuda, "numpy": np.__version__} + if lock["environment"] != environment: + raise ValueError("Confirmation numerical environment changed after locking") + if not lock.get("analysis_sources"): + raise ValueError("The prospective analysis implementation must also be locked") + root = Path(__file__).resolve().parents[2] + for relative, checksum in lock["analysis_sources"].items(): + if file_hash(root / relative) != checksum: + raise ValueError(f"Prospective analysis source changed: {relative}") + if not lock.get("data_source_files"): + raise ValueError("Original data source files must be prospectively locked") + for relative, checksum in lock["data_source_files"].items(): + if file_hash(root / relative) != checksum: + raise ValueError(f"Original data source changed: {relative}") + return config, lock + + +def validate_lock(config_path, lock_path, args): + config, lock = validate_frozen_design(config_path, lock_path) + if torch.device(args.device).type != "cuda" or lock.get("device_type") != "cuda": + raise ValueError("Confirmation requires CUDA BF16 execution, never mixed CPU precision") + if args.world not in WORLDS or args.seed not in (0, 1): + raise ValueError("Only the eight reserved worlds and two initializations are allowed") + if args.phase not in PHASES or args.condition not in CONDITIONS: + raise ValueError("Condition outside the prospective matrix") + expected_output = ( + Path(lock["output_root"]) + / args.phase + / "width-256" + / f"world-{args.world}-seed-{args.seed}-{args.condition}" + ).resolve() + if Path(args.output).resolve() != expected_output: + raise ValueError("Output differs from the prospective matrix") + return config, lock + + +def validate_prepared_world(config, config_path, lock_path, world): + if world not in WORLDS: + raise ValueError("Requested world is outside the prospective preparation matrix") + root = Path(__file__).resolve().parents[2] / config["base_world_root"] + receipt = json.loads((root / "preparation-audit.json").read_text()) + lock = json.loads(Path(lock_path).read_text()) + if ( + receipt.get("complete") is not True + or receipt["config_sha256"] != file_hash(config_path) + or receipt["lock_sha256"] != file_hash(lock_path) + or receipt["worlds"] != list(WORLDS) + ): + raise ValueError("Base worlds lack a complete prospectively locked preparation") + if receipt.get("source_files_sha256") != lock["data_source_files"]: + raise ValueError("Prepared world source files differ from the prospective lock") + filenames = ("world.npz", "metadata.json", "audit.json") + expected_files = {f"world-{seed}/{name}" for seed in WORLDS for name in filenames} + if set(receipt.get("files_sha256", {})) != expected_files: + raise ValueError("Prepared world file manifest differs from the prospective matrix") + for name in filenames: + relative = f"world-{world}/{name}" + if receipt["files_sha256"].get(relative) != file_hash(root / relative): + raise ValueError(f"Prepared world changed: {relative}") + metadata = json.loads((root / f"world-{world}/metadata.json").read_text()) + if type(metadata.get("seed")) is not int or metadata["seed"] != world: + raise ValueError("Prepared world metadata seed differs from the requested world") + return root, receipt + + +def case_identity(worker_identity, chain, support, kind, pair): + payload = { + "worker_identity": worker_identity, + "chain": chain, + "support": support, + "kind": kind, + "pair_contract": pair["contract"], + } + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + + +def expected_weight_artifacts(): + names = [f"learning/model-{step}.pt" for step in LEARNING_CHECKPOINTS] + names.append("learning/resume.pt") + names.extend( + f"edits/support-{support}/{chain}-{kind}-mlp/{filename}" + for support in (0, 1) + for chain in CHAINS + for kind in KINDS + for filename in ("model-final.pt", "resume.pt") + ) + return names + + +def scientific_artifacts(output): + for relative in expected_weight_artifacts(): + if not (output / relative).is_file(): + raise ValueError(f"Required confirmation weight artifact is missing: {relative}") + paths = [output / "launch-contract.json", output / "manipulation.npz"] + paths.extend(p for p in (output / "learning").iterdir() if p.is_file()) + paths.extend(p for p in (output / "edits").rglob("*") if p.is_file()) + return { + str(p.relative_to(output)): {"bytes": p.stat().st_size, "sha256": file_hash(p)} + for p in sorted(paths) + } + + +def run(args): + config, _ = validate_lock(args.config, args.lock, args) + output = Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=True) + with (output / ".worker.lock").open("w") as handle: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + base_root, data_receipt = validate_prepared_world( + config, args.config, args.lock, args.world + ) + if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported(): + raise ValueError("A healthy CUDA device with BF16 support is required") + identity = { + "protocol": PROTOCOL, + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "phase": args.phase, + "config_sha256": file_hash(args.config), + "preregistration_lock_sha256": file_hash(args.lock), + "sources": confirmation_sources(), + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": "cuda", + "precision": "BF16 autocast; FP32 model and optimizer", + "prepared_worlds_audit_sha256": file_hash(base_root / "preparation-audit.json"), + "world_files_sha256": { + name: checksum + for name, checksum in data_receipt["files_sha256"].items() + if name.startswith(f"world-{args.world}/") + }, + } + path = output / "launch-contract.json" + if path.exists() and json.loads(path.read_text()) != identity: + raise ValueError("Confirmation worker identity changed") + if not path.exists(): + write_json(path, identity) + if (output / "complete.json").exists(): + return + try: + low = make_cross_world(args.world, source_root=base_root) + high, manipulation, selected, donors = high_exception_world(low) + world = low if args.phase == "low" else high + pairs = { + (chain, support): make_confirmation_edit_pair(low, high, chain, support) + for chain in range(2) + for support in (0, 1) + } + for chain in range(2): + for key in ("groups", "E", "D", "selected_people"): + if np.intersect1d(pairs[chain, 0][key], pairs[chain, 1][key]).size: + raise ValueError(f"The two supports overlap: {key}") + atomic_numpy_save( + output / "manipulation.npz", + selections=selected, + donors=donors, + low_answers=low.answers, + high_answers=high.answers, + high_exceptions=high.exceptions, + ) + study = { + **config, + "confirmation_sources": identity["sources"], + "phase": args.phase, + "manipulation": manipulation, + } + learning_output = output / "learning" + learning_output.mkdir(exist_ok=True) + device = torch.device(args.device) + model, data = learning(args, world, learning_output, study, device) + with np.load(learning_output / "predictions-15360.npz") as saved: + baseline_predictions = { + key: saved[key] for key in ("prediction", "ended", "correct", "value_nll") + } + np.testing.assert_array_equal( + baseline_predictions["correct"], + (baseline_predictions["prediction"] == world.answers) + & baseline_predictions["ended"], + ) + completed = json.loads((learning_output / "learning-complete.json").read_text()) + if completed["model_sha256"] != state_hash(model.state_dict()): + raise ValueError("Learning baseline differs from completed weights") + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update( + {f"direct_{key}": value[ids] for key, value in baseline_predictions.items()} + ) + atomic_numpy_save(learning_output / f"two-step-{name}.npz", **arrays) + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + identity_hash = file_hash(path) + for support in (0, 1): + edit_output = output / "edits" / f"support-{support}" + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain, support], + args.phase, + kind, + chain, + edit_output, + case_identity( + identity_hash, chain, support, kind, pairs[chain, support] + ), + baseline_predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "protocol": PROTOCOL, + "learning_steps": 15360, + "edit_cases": 8, + "edit_steps": 512, + "lock_sha256": file_hash(args.lock), + "artifacts": scientific_artifacts(output), + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--config", required=True) + parser.add_argument("--lock", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py new file mode 100644 index 0000000000000000000000000000000000000000..8535796aba3f18178d69d214c04bc922b0dfa21d --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py @@ -0,0 +1,192 @@ +"""Two prospectively fixed E39 supports; preparation never launches a model. + +Support zero exactly preserves development selection. Support one uses a +separate deterministic stream and excludes the first support's entire groups. +The original E39 audit validates both; all training and target budgets match. +""" + +import numpy as np + +from .bios_data import array_hash, rng_for +from .bios_shortcut_control import audit_high_exception +from .bios_shortcut_matched_edit import ( + KINDS, + PHASES, + U_STRATA, + audit_matched_edit_pair, +) +from .bios_shortcut_matched_edit import ( + make_matched_edit_pair as development_pair, +) + +BUDGET = { + "prevalence_levels": 2, + "worlds": 8, + "initializations": 2, + "organizations": 3, + "models": 96, + "chains": 2, + "update_types": 2, + "supports_per_chain": 2, + "scopes": ["mlp"], + "edit_cases": 768, +} + + +def make_confirmation_edit_pair(low, high, chain, support=0): + """Three roots + 36 actual facts; same IDs and support labels across phases. + + Each selected group contributes six QA-trained and six QA-heldout people + who remain ordinary in the high-prevalence world. Coherent assigns all 12 + to the new default. Exception assigns three default/three alternative in + each split. Histograms match ACROSS all three groups, not within a group. + """ + if chain not in (0, 1) or support not in (0, 1): + raise ValueError("Confirmation fixes two chains and two disjoint supports") + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high worlds must share their identity and query layout") + audit_high_exception(low, high) + first = development_pair(low, high, chain) + if support == 0: + first["contract"].update( + protocol="v2.9-shortcut-behavior-confirmation-E39", + status="prospectively_fixed_confirmation_support", + budget=BUDGET.copy(), + model_checkpoint="width256, independent-world 15360-step low/high learning", + ) + return first + eligible_groups = np.setdiff1d(np.arange(64), first["groups"]) + rng = rng_for(low.seed, 931, chain + 2 * support) + for _ in range(10000): + groups = rng.choice(eligible_groups, 3, replace=False) + if len(np.unique(low.defaults[chain, groups])) == 3: + break + else: + raise RuntimeError("Could not find three groups with distinct default cities") + selected = np.empty((3, 12), dtype=np.int64) + conflict = np.zeros((3, 12), dtype=bool) + conflict[:, :3] = conflict[:, 6:9] = True + targets = { + f"{phase}_{kind}": world.answers.copy() + for phase, world in (("low", low), ("high", high)) + for kind in KINDS + } + new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + for index, group in enumerate(groups): + ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] + if len(eligible) != 8: + raise ValueError("Expected eight still-ordinary people in each QA split") + selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] + actual = low.actual_ids[chain, selected[index]] + derived = low.derived_ids[chain, low.memberships[chain] == group] + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + target[low.root_ids[chain, group]] = new_default[index] + target[derived] = new_default[index] + target[actual] = new_default[index] + if kind == "exception": + target[actual[conflict[index]]] = alternative[index] + edited_people = selected.ravel() + selected_people = np.isin(low.memberships[chain], groups) + original = selected_people & low.exceptions[chain] + newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] + unedited_ordinary = ( + selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) + ) + e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) + d = low.derived_ids[chain, selected_people] + unchanged = np.ones(len(low.answers), dtype=bool) + unchanged[np.concatenate([e, d])] = False + affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] + original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) + newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) + relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(low.answers), -1, dtype=np.int64) + strata[unchanged & original_actual] = 0 + strata[unchanged & newly_actual] = 1 + strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 + strata[unchanged & ~affected_facts & relevant] = 3 + strata[unchanged & ~affected_facts & ~relevant] = 4 + heldout = [] + for stratum in range(5): + ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) + heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) + heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) + heldout = np.array(sorted(heldout), dtype=np.int64) + common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) + common_pool = np.setdiff1d(common_pool, heldout) + if len(common_pool) < 4096: + raise ValueError("Insufficient shared unchanged base facts for R4096") + replay = rng.choice(common_pool, 4096, replace=False) + paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) + pair = { + **targets, + "groups": groups, + "selected_people": selected, + "alternative_assignments": conflict, + "new_default": new_default, + "alternative": alternative, + "E": e, + "D": d, + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, edited_people]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), + "paired_reference_D": paired_reference, + "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "exception_conflict_D": paired_reference.copy(), + "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, original], + "D_newly_exception": low.derived_ids[chain, newly], + "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], + "R": replay, + "U_full": np.flatnonzero(unchanged), + "U_heldout": heldout, + "U_strata": strata, + } + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + actual_for_d = target[low.actual_ids[chain, selected_people]] + pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] + pair["contract"] = { + "protocol": "v2.9-shortcut-behavior-confirmation-E39", + "world": low.seed, + "chain": chain, + "support": support, + "status": "prospectively_fixed_confirmation_support", + "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, + "model_checkpoint": ("width256, independent-world 15360-step low/high learning"), + "histogram_matching_scope": ( + "all three groups combined; also separately for trained/heldout QA" + ), + "coherent_actuals_per_group": "12 new-default (six in each QA split)", + "exception_actuals_per_group": ( + "6 new-default + 6 alternative (three + three in each QA split)" + ), + "paired_reference_semantics": ( + "same 18 people; conflict only in exception, reference only in coherent" + ), + "R_semantics": ( + "4096 identical query IDs with identical original truths " + "and unchanged under all four targets" + ), + "U_semantics": ( + "common query IDs; score each phase against its own truth and old-correct coverage" + ), + "U_strata": U_STRATA.copy(), + "historical_E93_comparable": False, + "low_truth_sha256": array_hash(low.answers), + "high_truth_sha256": array_hash(high.answers), + "array_sha256": {key: array_hash(value) for key, value in pair.items()}, + } + audit_matched_edit_pair(low, high, chain, pair) + return pair diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_control.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_control.py new file mode 100644 index 0000000000000000000000000000000000000000..60ee531b9c2a08e1cf2cfba210a312300b93480d --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_control.py @@ -0,0 +1,242 @@ +"""P3: alter shortcut reliability while preserving marginal answer counts. + +The archived crossover generator and trainer are imported, never rewritten. +The two chains are manipulated simultaneously; QA identities remain unchanged. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import time +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CONDITIONS, audit, documents, make_cross_world, qa_schedule +from .bios_cross_train import learning, source_hashes +from .bios_data import array_hash, rng_for, write_json +from .bios_organization_train import atomic_numpy_save + + +def high_exception_world(old): + """Raise both chains from two to sixteen exceptions per 32-member group.""" + audit(old) + answers, exceptions = old.answers.copy(), old.exceptions.copy() + selections = np.empty((2, 64, 14), dtype=np.int64) + donors = np.empty((2, 14, 64), dtype=np.int64) + for chain in range(2): + rng = rng_for(old.seed, 930, chain) + for group in range(64): + ordinary = np.flatnonzero((old.memberships[chain] == group) & ~old.exceptions[chain]) + people = [] + for query_pool in (old.train_ids[chain], old.heldout_ids[chain]): + eligible = ordinary[np.isin(old.derived_ids[chain, ordinary], query_pool)] + people.extend(rng.permutation(eligible)[:7]) + selections[chain, group] = people + # Every lane contains one ordinary member per group. A city-deranged + # bijection preserves the histogram exactly, separately in each QA split. + for lane in range(14): + for _ in range(10000): + donor = rng.permutation(64) + if np.all(old.defaults[chain, donor] != old.defaults[chain]): + break + else: + raise RuntimeError("Could not construct a city-deranged permutation") + donors[chain, lane] = donor + selected = selections[chain, :, lane] + answers[old.actual_ids[chain, selected]] = old.city_tokens[old.defaults[chain, donor]] + exceptions[chain, selected] = True + world = replace(old, answers=answers, exceptions=exceptions) + record = audit_high_exception(old, world) + record["selection_sha256"] = array_hash(selections) + record["donors_sha256"] = array_hash(donors) + return world, record, selections, donors + + +def audit_high_exception(old, new): + """Fail if the manipulation changes anything outside its declared contract.""" + allowed = old.actual_ids.ravel() + unchanged = np.setdiff1d(np.arange(len(old.answers)), allowed) + np.testing.assert_array_equal(old.answers[unchanged], new.answers[unchanged]) + for field in ( + "prompts", + "lengths", + "relation", + "person", + "memberships", + "defaults", + "membership_ids", + "root_ids", + "actual_ids", + "derived_ids", + "train_ids", + "heldout_ids", + "city_tokens", + ): + np.testing.assert_array_equal(getattr(old, field), getattr(new, field)) + if old.token_labels != new.token_labels: + raise ValueError("Vocabulary changed") + records = [] + for chain in range(2): + ids = old.actual_ids[chain] + np.testing.assert_array_equal(np.sort(old.answers[ids]), np.sort(new.answers[ids])) + truth_exception = ( + new.answers[ids] != new.city_tokens[new.defaults[chain, new.memberships[chain]]] + ) + np.testing.assert_array_equal(truth_exception, new.exceptions[chain]) + if np.any(old.exceptions[chain] & ~new.exceptions[chain]): + raise ValueError("An original exception was removed") + for group in range(64): + members = new.memberships[chain] == group + if int(new.exceptions[chain, members].sum()) != 16: + raise ValueError("Expected sixteen exceptions per group") + for pool in (new.train_ids[chain], new.heldout_ids[chain]): + people = np.flatnonzero(members & np.isin(new.derived_ids[chain], pool)) + if len(people) != 16 or new.exceptions[chain, people].sum() != 8: + raise ValueError("QA split no longer has eight exceptions per group") + for pool in (new.train_ids[chain], new.heldout_ids[chain]): + people = np.flatnonzero(np.isin(new.derived_ids[chain], pool)) + np.testing.assert_array_equal( + np.sort(old.answers[ids[people]]), np.sort(new.answers[ids[people]]) + ) + records.append( + { + "chain": chain, + "old_exceptions": int(old.exceptions[chain].sum()), + "new_exceptions": int(new.exceptions[chain].sum()), + "changed_actual_facts": int((old.answers[ids] != new.answers[ids]).sum()), + "answer_histogram_preserved": True, + "split_histograms_preserved": True, + } + ) + for condition in CONDITIONS: + np.testing.assert_array_equal(documents(old, condition), documents(new, condition)) + np.testing.assert_array_equal(qa_schedule(old, 1280), qa_schedule(new, 1280)) + return { + "passed": True, + "world": old.seed, + "old_truth_sha256": array_hash(old.answers), + "new_truth_sha256": array_hash(new.answers), + "prompts_sha256": array_hash(new.prompts), + "chains": records, + "changed_total": int((old.answers != new.answers).sum()), + "document_identities_and_QA_split_preserved": True, + } + + +def shortcut_sources(): + diagnostic = Path(__file__).with_name("bios_path_diagnostics.py") + return { + **source_hashes(), + Path(__file__).name: hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + diagnostic.name: hashlib.sha256(diagnostic.read_bytes()).hexdigest(), + } + + +def run(args): + out = Path(args.output).resolve() + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + study = json.loads(Path(args.config).read_text()) + if study["width"] != 256 or study["steps"] != 15360: + raise ValueError("P3 freezes width 256 and 15360 steps") + old = make_cross_world(args.world) + world, manipulation, selected, donors = high_exception_world(old) + contract = { + "protocol": "v2.8-p3-shortcut-reliability", + "study": study, + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "sources": shortcut_sources(), + "manipulation": manipulation, + "environment": { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + } + contract_path = out / "launch-contract.json" + if contract_path.exists(): + frozen = json.loads(contract_path.read_text()) + for key in ( + "protocol", + "study", + "world", + "seed", + "condition", + "sources", + "manipulation", + ): + if frozen[key] != contract[key]: + raise ValueError(f"Frozen shortcut contract changed: {key}") + else: + write_json(contract_path, contract) + atomic_numpy_save( + out / "manipulation.npz", + selections=selected, + donors=donors, + old_answers=old.answers, + answers=world.answers, + exceptions=world.exceptions, + train_ids=world.train_ids, + heldout_ids=world.heldout_ids, + ) + if (out / "complete.json").exists(): + return + # Include adapter provenance in the archived trainer's own run identity. + study = {**study, "shortcut_contract": contract["sources"]} + torch.set_num_threads(args.threads) + try: + from .bios_path_diagnostics import autonomous_two_step + + device = torch.device(args.device) + model, _ = learning(args, world, out, study, device) + with np.load(out / f"predictions-{study['steps']}.npz") as saved: + direct = {k: saved[k] for k in ("prediction", "ended", "correct")} + for chain, name in enumerate(("company", "project")): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) + atomic_numpy_save(out / f"two-step-{name}.npz", **arrays) + write_json( + out / "complete.json", + { + "status": "complete", + "phase": "P3-learning-only", + "learning_steps": study["steps"], + "edit_cases": 0, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + { + "type": type(error).__name__, + "message": str(error), + "time": time.time(), + }, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--config", default="configs/bios-shortcut-control-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_edit.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..856a9a8a4fd753c498c4b965d5c30a057bdebffd --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_edit.py @@ -0,0 +1,446 @@ +"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents.""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_shortcut_control import high_exception_world, shortcut_sources +from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +STUDY = { + "protocol": "v2.8-p3-shortcut-matched-E39", + "width": 256, + "parent_step": 15360, + "phases": list(PHASES), + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kinds": list(KINDS), + "scope": "mlp", + "mlp_layers": [3, 4, 5], + "lr": 0.00003, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 96, + "E": 39, + "D": 96, + "R": 4096, + "primary_reference_D": 18, + "primary_reference_D_heldout": 9, + "status": "prepared conditional branch; no best-step selection", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("E39 editing configuration differs from the frozen prepared contract") + + +def editing_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ( + "bios_cross_continue.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit.py", + ) + }, + } + + +def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): + """No phase, organization, initialization, or update-type dependence.""" + rng = rng_for(world_seed, 932, chain) + return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch)) + + +def score_arrays(arrays, truth): + if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): + raise ValueError("Prediction shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("EOS and correctness must be Boolean arrays") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def query_metrics(correct, ids): + n = len(ids) + count = int(correct[ids].sum()) + return {"n": n, "correct": count, "accuracy": count / n if n else None} + + +def retention_metrics(correct, old_correct, ids): + n = len(ids) + known_ids = ids[old_correct[ids]] + broken = int((~correct[known_ids]).sum()) + return { + "n": n, + "known": len(known_ids), + "coverage": len(known_ids) / n if n else None, + "broken": broken, + "damage": broken / len(known_ids) if len(known_ids) else None, + } + + +def edit_metrics(pair, phase, kind, arrays, old_correct): + correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] + if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: + raise ValueError("Old-correct coverage array mismatch") + result = { + key: query_metrics(correct, pair[key]) + for key in ( + "E", + "E_roots", + "E_actual", + "D", + "D_trained", + "D_heldout", + "paired_reference_D", + "paired_reference_D_heldout", + "D_edited_actual", + "D_edited_aligned", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + } + if kind == "exception": + result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) + result["exception_conflict_D_heldout"] = query_metrics( + correct, pair["exception_conflict_D_heldout"] + ) + result["factual_conflict_D"] = query_metrics( + correct, pair[f"{phase}_{kind}_factual_conflict_D"] + ) + for pool in ("U_full", "U_heldout"): + ids = pair[pool] + result[pool] = { + **retention_metrics(correct, old_correct, ids), + "strata": { + str(group): retention_metrics( + correct, old_correct, ids[pair["U_strata"][ids] == group] + ) + for group in range(5) + }, + } + return result + + +def load_parent(parent, phase): + config = json.loads((parent / "config.json").read_text()) + expected_model = dict(vocab_size=4804, width=256, layers=8, heads=4, context=128) + if config["model"] != expected_model or config["study"]["steps"] != 15360: + raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") + if any( + config["study"][key] != value + for key, value in { + "lr": 1e-4, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + }.items() + ): + raise ValueError("E39 parent exposure or learning budget differs") + if ( + config["world"] not in (0, 1) + or config["seed"] not in (0, 1) + or config["condition"] not in CONDITIONS + ): + raise ValueError("Parent is outside the fixed development matrix") + if config["sources"] != source_hashes(): + raise ValueError("Parent frozen trainer sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent numerical software differs") + if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("Low parent is not an original unrestricted-context run") + if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): + raise ValueError("High parent manipulation/source provenance changed") + low = make_cross_world(config["world"]) + high, _, _, _ = high_exception_world(low) + world = low if phase == "low" else high + if config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent truth differs from its declared prevalence phase") + with np.load(parent / "predictions-15360.npz") as saved: + predictions = score_arrays( + {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, + world.answers, + ) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if ( + checkpoint["step"] != 15360 + or checkpoint["config"] != config["model"] + or complete["status"] != "complete" + ): + raise ValueError("Parent learning has not completed the specified checkpoint") + if state_hash(checkpoint["model"]) != complete["model_sha256"]: + raise ValueError("Parent checkpoint differs from completed learning weights") + provenance = { + "directory": str(parent), + "files_sha256": { + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + "model_sha256": complete["model_sha256"], + } + return config, checkpoint, predictions, low, high, world, provenance + + +def run_case( + model, + baseline, + data, + world, + pair, + phase, + kind, + chain, + output, + identity_hash, + parent_predictions, + device, +): + dest = output / f"{CHAINS[chain]}-{kind}-mlp" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + e_choices, r_choices = sampling_stream(world.seed, chain) + saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} + saved_sets.update( + old_correct=parent_predictions["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + atomic_numpy_save(dest / "sets.npz", **saved_sets) + write_json(dest / "data-contract.json", pair["contract"]) + target = pair[f"{phase}_{kind}"] + new_data = tensor_queries(world, device, target) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["R"]), 256): + ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW( + selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("E39 resume identity mismatch") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("E39 resume step mismatch") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, new_data, target) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_predictions[key]) + point = { + "step": step, + "edit_seconds": seconds, + **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "phase": phase, + "chain": CHAINS[chain], + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + print( + json.dumps( + { + "event": "E39_edit_complete", + "case": dest.name, + "E": timeline[-1]["E"]["accuracy"], + "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], + } + ), + flush=True, + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("E39 output must be separate from its immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, checkpoint, predictions, low, high, world, provenance = load_parent( + parent, args.phase + ) + pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] + identity = { + "phase": args.phase, + "world": world.seed, + "seed": config["seed"], + "condition": config["condition"], + "study": STUDY, + "sources": editing_sources(), + "parent": provenance, + "data_contracts": [pair["contract"] for pair in pairs], + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": torch.device(args.device).type, + } + identity_path = output / "config.json" + if identity_path.exists() and json.loads(identity_path.read_text()) != identity: + raise ValueError("E39 editing identity or sources changed") + if not identity_path.exists(): + write_json(identity_path, identity) + if (output / "complete.json").exists(): + return + device = torch.device(args.device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_queries(world, device) + try: + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + observed = evaluate(model, data, world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], predictions[key]) + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain], + args.phase, + kind, + chain, + output, + file_hash(identity_path), + predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": args.phase, + "edit_cases": 4, + "steps": 512, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..52dd3441331f501688eedfe95286f26462de3625 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py @@ -0,0 +1,446 @@ +"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents.""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_shortcut_control import high_exception_world, shortcut_sources +from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +STUDY = { + "protocol": "v2.8-p3-shortcut-matched-E39", + "width": 256, + "parent_step": 15360, + "phases": list(PHASES), + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kinds": list(KINDS), + "scope": "mlp", + "mlp_layers": [3, 4, 5], + "lr": 0.00003, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 96, + "E": 39, + "D": 96, + "R": 4096, + "primary_reference_D": 18, + "primary_reference_D_heldout": 9, + "status": "prepared conditional branch; no best-step selection", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("E39 editing configuration differs from the frozen prepared contract") + + +def editing_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ( + "bios_cross_continue.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit_v2.py", + ) + }, + } + + +def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): + """No phase, organization, initialization, or update-type dependence.""" + rng = rng_for(world_seed, 932, chain) + return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch)) + + +def score_arrays(arrays, truth): + if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): + raise ValueError("Prediction shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("EOS and correctness must be Boolean arrays") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def query_metrics(correct, ids): + n = len(ids) + count = int(correct[ids].sum()) + return {"n": n, "correct": count, "accuracy": count / n if n else None} + + +def retention_metrics(correct, old_correct, ids): + n = len(ids) + known_ids = ids[old_correct[ids]] + broken = int((~correct[known_ids]).sum()) + return { + "n": n, + "known": len(known_ids), + "coverage": len(known_ids) / n if n else None, + "broken": broken, + "damage": broken / len(known_ids) if len(known_ids) else None, + } + + +def edit_metrics(pair, phase, kind, arrays, old_correct): + correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] + if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: + raise ValueError("Old-correct coverage array mismatch") + result = { + key: query_metrics(correct, pair[key]) + for key in ( + "E", + "E_roots", + "E_actual", + "D", + "D_trained", + "D_heldout", + "paired_reference_D", + "paired_reference_D_heldout", + "D_edited_actual", + "D_edited_aligned", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + } + if kind == "exception": + result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) + result["exception_conflict_D_heldout"] = query_metrics( + correct, pair["exception_conflict_D_heldout"] + ) + result["factual_conflict_D"] = query_metrics( + correct, pair[f"{phase}_{kind}_factual_conflict_D"] + ) + for pool in ("U_full", "U_heldout"): + ids = pair[pool] + result[pool] = { + **retention_metrics(correct, old_correct, ids), + "strata": { + str(group): retention_metrics( + correct, old_correct, ids[pair["U_strata"][ids] == group] + ) + for group in range(5) + }, + } + return result + + +def load_parent(parent, phase): + config = json.loads((parent / "config.json").read_text()) + low = make_cross_world(config["world"]) + expected_model = dict(vocab_size=low.vocab_size, width=256, layers=8, heads=4, context=128) + if config["model"] != expected_model or config["study"]["steps"] != 15360: + raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") + if any( + config["study"][key] != value + for key, value in { + "lr": 1e-4, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + }.items() + ): + raise ValueError("E39 parent exposure or learning budget differs") + if ( + config["world"] not in (0, 1) + or config["seed"] not in (0, 1) + or config["condition"] not in CONDITIONS + ): + raise ValueError("Parent is outside the fixed development matrix") + if config["sources"] != source_hashes(): + raise ValueError("Parent frozen trainer sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent numerical software differs") + if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("Low parent is not an original unrestricted-context run") + if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): + raise ValueError("High parent manipulation/source provenance changed") + high, _, _, _ = high_exception_world(low) + world = low if phase == "low" else high + if config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent truth differs from its declared prevalence phase") + with np.load(parent / "predictions-15360.npz") as saved: + predictions = score_arrays( + {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, + world.answers, + ) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if ( + checkpoint["step"] != 15360 + or checkpoint["config"] != config["model"] + or complete["status"] != "complete" + ): + raise ValueError("Parent learning has not completed the specified checkpoint") + if state_hash(checkpoint["model"]) != complete["model_sha256"]: + raise ValueError("Parent checkpoint differs from completed learning weights") + provenance = { + "directory": str(parent), + "files_sha256": { + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + "model_sha256": complete["model_sha256"], + } + return config, checkpoint, predictions, low, high, world, provenance + + +def run_case( + model, + baseline, + data, + world, + pair, + phase, + kind, + chain, + output, + identity_hash, + parent_predictions, + device, +): + dest = output / f"{CHAINS[chain]}-{kind}-mlp" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + e_choices, r_choices = sampling_stream(world.seed, chain) + saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} + saved_sets.update( + old_correct=parent_predictions["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + atomic_numpy_save(dest / "sets.npz", **saved_sets) + write_json(dest / "data-contract.json", pair["contract"]) + target = pair[f"{phase}_{kind}"] + new_data = tensor_queries(world, device, target) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["R"]), 256): + ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW( + selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("E39 resume identity mismatch") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("E39 resume step mismatch") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, new_data, target) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_predictions[key]) + point = { + "step": step, + "edit_seconds": seconds, + **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "phase": phase, + "chain": CHAINS[chain], + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + print( + json.dumps( + { + "event": "E39_edit_complete", + "case": dest.name, + "E": timeline[-1]["E"]["accuracy"], + "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], + } + ), + flush=True, + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("E39 output must be separate from its immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, checkpoint, predictions, low, high, world, provenance = load_parent( + parent, args.phase + ) + pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] + identity = { + "phase": args.phase, + "world": world.seed, + "seed": config["seed"], + "condition": config["condition"], + "study": STUDY, + "sources": editing_sources(), + "parent": provenance, + "data_contracts": [pair["contract"] for pair in pairs], + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": torch.device(args.device).type, + } + identity_path = output / "config.json" + if identity_path.exists() and json.loads(identity_path.read_text()) != identity: + raise ValueError("E39 editing identity or sources changed") + if not identity_path.exists(): + write_json(identity_path, identity) + if (output / "complete.json").exists(): + return + device = torch.device(args.device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_queries(world, device) + try: + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + observed = evaluate(model, data, world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], predictions[key]) + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain], + args.phase, + kind, + chain, + output, + file_hash(identity_path), + predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": args.phase, + "edit_cases": 4, + "steps": 512, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..684e672ca551a48aacb2f4bc81db94092282f4cf --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py @@ -0,0 +1,327 @@ +"""Prepared E39 update sets shared by low/high shortcut-reliability worlds. + +This file generates and audits data only. It neither trains nor edits a model. +The 96 proposed MLP edits are distinct from the archived E93 experiment. +""" + +import numpy as np + +from .bios_data import array_hash, rng_for +from .bios_shortcut_control import audit_high_exception + +KINDS = ("coherent", "exception") +PHASES = ("low", "high") +BUDGET = { + "prevalence_levels": 2, + "worlds": 2, + "initializations": 2, + "organizations": 3, + "models": 24, + "chains": 2, + "update_types": 2, + "supports_per_chain": 1, + "scopes": ["mlp"], + "edit_cases": 96, +} +U_STRATA = { + "0": "original_exception_actual_in_affected_groups", + "1": "newly_exception_actual_in_affected_groups", + "2": "other_unchanged_facts_of_affected_people", + "3": "remaining_same_chain_facts", + "4": "remaining_cross_chain_or_independent_facts", +} + + +def make_matched_edit_pair(low, high, chain, support=0): + """Three roots + 36 actual facts; same IDs and support labels across phases. + + Each selected group contributes six QA-trained and six QA-heldout people + who remain ordinary in the high-prevalence world. Coherent assigns all 12 + to the new default. Exception assigns three default/three alternative in + each split. Histograms match ACROSS all three groups, not within a group. + """ + if chain not in (0, 1) or support != 0: + raise ValueError("The prepared contract fixes two chains and support zero") + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high worlds must share their identity and query layout") + audit_high_exception(low, high) + rng = rng_for(low.seed, 931, chain) + for _ in range(10000): + groups = rng.choice(64, 3, replace=False) + if len(np.unique(low.defaults[chain, groups])) == 3: + break + else: + raise RuntimeError("Could not find three groups with distinct default cities") + selected = np.empty((3, 12), dtype=np.int64) + conflict = np.zeros((3, 12), dtype=bool) + conflict[:, :3] = conflict[:, 6:9] = True + targets = { + f"{phase}_{kind}": world.answers.copy() + for phase, world in (("low", low), ("high", high)) + for kind in KINDS + } + new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + for index, group in enumerate(groups): + ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] + if len(eligible) != 8: + raise ValueError("Expected eight still-ordinary people in each QA split") + selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] + actual = low.actual_ids[chain, selected[index]] + derived = low.derived_ids[chain, low.memberships[chain] == group] + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + target[low.root_ids[chain, group]] = new_default[index] + target[derived] = new_default[index] + target[actual] = new_default[index] + if kind == "exception": + target[actual[conflict[index]]] = alternative[index] + edited_people = selected.ravel() + selected_people = np.isin(low.memberships[chain], groups) + original = selected_people & low.exceptions[chain] + newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] + unedited_ordinary = ( + selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) + ) + e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) + d = low.derived_ids[chain, selected_people] + unchanged = np.ones(len(low.answers), dtype=bool) + unchanged[np.concatenate([e, d])] = False + affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] + original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) + newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) + relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(low.answers), -1, dtype=np.int64) + strata[unchanged & original_actual] = 0 + strata[unchanged & newly_actual] = 1 + strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 + strata[unchanged & ~affected_facts & relevant] = 3 + strata[unchanged & ~affected_facts & ~relevant] = 4 + heldout = [] + for stratum in range(5): + ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) + heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) + heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) + heldout = np.array(sorted(heldout), dtype=np.int64) + common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) + common_pool = np.setdiff1d(common_pool, heldout) + if len(common_pool) < 4096: + raise ValueError("Insufficient shared unchanged base facts for R4096") + replay = rng.choice(common_pool, 4096, replace=False) + paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) + pair = { + **targets, + "groups": groups, + "selected_people": selected, + "alternative_assignments": conflict, + "new_default": new_default, + "alternative": alternative, + "E": e, + "D": d, + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, edited_people]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), + "paired_reference_D": paired_reference, + "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "exception_conflict_D": paired_reference.copy(), + "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, original], + "D_newly_exception": low.derived_ids[chain, newly], + "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], + "R": replay, + "U_full": np.flatnonzero(unchanged), + "U_heldout": heldout, + "U_strata": strata, + } + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + actual_for_d = target[low.actual_ids[chain, selected_people]] + pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] + pair["contract"] = { + "protocol": "v2.8-p3-shortcut-matched-E39-prepared", + "world": low.seed, + "chain": chain, + "support": support, + "status": "data_only_not_executed", + "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, + "model_checkpoint": ( + "width256, original 15360-step learning; not P2 30720-step continuation" + ), + "histogram_matching_scope": ( + "all three groups combined; also separately for trained/heldout QA" + ), + "coherent_actuals_per_group": "12 new-default (six in each QA split)", + "exception_actuals_per_group": ( + "6 new-default + 6 alternative (three + three in each QA split)" + ), + "paired_reference_semantics": ( + "same 18 people; conflict only in exception, reference only in coherent" + ), + "R_semantics": ( + "4096 identical query IDs with identical original truths " + "and unchanged under all four targets" + ), + "U_semantics": ( + "common query IDs; score each phase against its own truth and old-correct coverage" + ), + "U_strata": U_STRATA.copy(), + "historical_E93_comparable": False, + "low_truth_sha256": array_hash(low.answers), + "high_truth_sha256": array_hash(high.answers), + "array_sha256": {key: array_hash(value) for key, value in pair.items()}, + } + audit_matched_edit_pair(low, high, chain, pair) + return pair + + +def audit_matched_edit_pair(low, high, chain, pair): + """Verify ID, target, split, marginal, primary-subset, and replay contracts.""" + audit_high_exception(low, high) + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high world identities differ") + e, d, selected, groups = (pair[key] for key in ("E", "D", "selected_people", "groups")) + if len(e) != 39 or len(np.unique(e)) != 39 or len(d) != 96 or len(np.unique(d)) != 96: + raise ValueError("E39/D96 support changed") + if len(groups) != 3 or len(np.unique(low.defaults[chain, groups])) != 3: + raise ValueError("Expected three groups with distinct original defaults") + if selected.shape != (3, 12) or len(np.unique(selected)) != 36: + raise ValueError("Expected twelve distinct people in each selected group") + if high.exceptions[chain, selected].any(): + raise ValueError("Selected edit people must be ordinary in both worlds") + np.testing.assert_array_equal( + pair["new_default"], low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + ) + np.testing.assert_array_equal( + pair["alternative"], low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + ) + np.testing.assert_array_equal( + d, low.derived_ids[chain, np.isin(low.memberships[chain], groups)] + ) + np.testing.assert_array_equal( + e, np.sort(np.r_[low.root_ids[chain, groups], low.actual_ids[chain, selected.ravel()]]) + ) + conflict = pair["alternative_assignments"] + if conflict.shape != (3, 12) or conflict.dtype != np.bool_: + raise ValueError("Invalid alternative assignment mask") + for index, group in enumerate(groups): + if not np.all(low.memberships[chain, selected[index]] == group): + raise ValueError("Selected person belongs to the wrong group") + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + people = selected[index, split * 6 : (split + 1) * 6] + if not np.isin(low.derived_ids[chain, people], pool).all(): + raise ValueError("Selected QA split changed") + if conflict[index, split * 6 : (split + 1) * 6].sum() != 3: + raise ValueError("Each group/split must have three default and three alternative") + root = low.root_ids[chain, group] + derived = low.derived_ids[chain, low.memberships[chain] == group] + actual = low.actual_ids[chain, selected[index]] + for phase in PHASES: + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + if target[root] != pair["new_default"][index] or not np.all( + target[derived] == target[root] + ): + raise ValueError( + "The three root rotations and their full propagation targets must agree" + ) + expected = np.full(12, target[root], dtype=np.int64) + if kind == "exception": + expected[conflict[index]] = pair["alternative"][index] + np.testing.assert_array_equal(target[actual], expected) + changed = np.union1d(e, d) + for phase, world in (("low", low), ("high", high)): + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + np.testing.assert_array_equal(np.flatnonzero(target != world.answers), changed) + for kind in KINDS: + np.testing.assert_array_equal(pair[f"low_{kind}"][changed], pair[f"high_{kind}"][changed]) + for _split, pool in ( + ("all", low.derived_ids[chain]), + ("trained", low.train_ids[chain]), + ("heldout", low.heldout_ids[chain]), + ): + people = selected.ravel()[np.isin(low.derived_ids[chain, selected.ravel()], pool)] + actual = low.actual_ids[chain, people] + np.testing.assert_array_equal( + np.sort(pair["low_coherent"][actual]), np.sort(pair["low_exception"][actual]) + ) + reference = np.sort(low.derived_ids[chain, selected[conflict]]) + np.testing.assert_array_equal(pair["paired_reference_D"], reference) + np.testing.assert_array_equal(pair["exception_conflict_D"], reference) + heldout_reference = np.intersect1d(reference, low.heldout_ids[chain]) + np.testing.assert_array_equal(pair["exception_conflict_D_heldout"], heldout_reference) + np.testing.assert_array_equal(pair["paired_reference_D_heldout"], heldout_reference) + if len(reference) != 18 or len(heldout_reference) != 9: + raise ValueError("Expected eighteen primary exception conflicts, nine heldout") + partition = [ + pair[key] + for key in ( + "D_edited_actual", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + ] + if [len(ids) for ids in partition] != [36, 6, 42, 12]: + raise ValueError("Incorrect fixed propagation strata") + np.testing.assert_array_equal(np.sort(np.concatenate(partition)), d) + affected = np.isin(low.memberships[chain], groups) + expected_subsets = { + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, selected.ravel()]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, selected.ravel()]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, affected & low.exceptions[chain]], + "D_newly_exception": low.derived_ids[ + chain, affected & high.exceptions[chain] & ~low.exceptions[chain] + ], + } + for key, expected in expected_subsets.items(): + np.testing.assert_array_equal(pair[key], expected) + for phase in PHASES: + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + conflicts = d[target[d] != target[low.actual_ids[chain, affected]]] + np.testing.assert_array_equal(pair[f"{phase}_{kind}_factual_conflict_D"], conflicts) + u = np.setdiff1d(np.arange(len(low.answers)), changed) + np.testing.assert_array_equal(pair["U_full"], u) + np.testing.assert_array_equal(pair["U_strata"] >= 0, np.isin(np.arange(len(low.answers)), u)) + replay = pair["R"] + if len(replay) != 4096 or len(np.unique(replay)) != 4096 or np.any(replay >= low.n_base): + raise ValueError("R must contain 4096 unique base-fact IDs") + if not np.isin(replay, u).all() or np.intersect1d(replay, pair["U_heldout"]).size: + raise ValueError("Replay leaks changed support/propagation or heldout retention") + if not np.isin(pair["U_heldout"], u).all(): + raise ValueError("Heldout retention includes changed targets") + np.testing.assert_array_equal(low.answers[replay], high.answers[replay]) + for phase in PHASES: + for kind in KINDS: + np.testing.assert_array_equal(pair[f"{phase}_{kind}"][replay], low.answers[replay]) + for key, value in pair.items(): + if isinstance(value, np.ndarray) and pair["contract"]["array_sha256"][key] != array_hash( + value + ): + raise ValueError(f"Matched update array provenance changed: {key}") + return { + "passed": True, + "E": 39, + "D": 96, + "exception_conflict_D": 18, + "exception_conflict_D_heldout": 9, + "R": 4096, + "budget_edit_cases": 96, + "histograms_match_across_three_groups_and_within_QA_split": True, + } diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_train.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_train.py new file mode 100644 index 0000000000000000000000000000000000000000..958bf5b4de4feec20d76d07a5d28016fec584d7a --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bios_train.py @@ -0,0 +1,353 @@ +"""Reproducible symbolic development trajectories for bioS-Work-v1. + +Every evaluated answer is greedily generated without a correct-answer prefix. +Two generated tokens is the fixed symbolic grammar budget (one value plus EOS). +""" + +import argparse +import hashlib +import json +import os +import platform +import subprocess +import time +from contextlib import nullcontext +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import ( + EOS, + N_BASE, + N_QUERIES, + RELATIONS, + array_hash, + curriculum, + load_world, + write_json, +) +from .bios_model import CausalLM, ModelConfig, matmul_flops + + +def precision(device): + return ( + torch.autocast(device_type="cuda", dtype=torch.bfloat16) + if device.type == "cuda" + else nullcontext() + ) + + +def tensor_data(world, device, answers=None): + answer = torch.as_tensor(world.answers if answers is None else answers, device=device) + prompts = torch.as_tensor(world.prompts, device=device) + lengths = torch.as_tensor(world.lengths, device=device) + tokens = torch.zeros((N_QUERIES, 6), dtype=torch.long, device=device) + tokens[:, :5] = prompts + rows = torch.arange(N_QUERIES, device=device) + tokens[rows, lengths] = answer + tokens[lengths == 4, 5] = EOS + positions = torch.stack([lengths - 1, lengths], dim=1) + labels = torch.stack([answer, torch.full_like(answer, EOS)], dim=1) + return { + "prompts": prompts, + "lengths": lengths, + "tokens": tokens, + "positions": positions, + "labels": labels, + } + + +@torch.no_grad() +def evaluate(model, data, world, batch_size=512, answers=None): + device = data["tokens"].device + targets = world.answers if answers is None else answers + predictions, ended, nll = [], [], [] + model.eval() + for begin in range(0, N_QUERIES, batch_size): + end = min(begin + batch_size, N_QUERIES) + lengths = data["lengths"][begin:end] + rows = torch.arange(end - begin, device=device) + with precision(device): + logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float() + first = logits.argmax(-1) + continuation = torch.zeros((end - begin, 6), dtype=torch.long, device=device) + continuation[:, :5] = data["prompts"][begin:end] + continuation[rows, lengths] = first + second = model(continuation, lengths[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + labels = torch.as_tensor(targets[begin:end], device=device) + nll.append(F.cross_entropy(logits, labels, reduction="none").cpu().numpy()) + predictions, ended, nll = ( + np.concatenate(predictions), + np.concatenate(ended), + np.concatenate(nll), + ) + correct = (predictions == targets) & ended + strata = { + "employer": world.relation == 0, + "company_default": world.relation == 1, + "actual_nonexception": (world.relation == 2) + & ~world.exceptions[np.maximum(world.person, 0)], + "actual_old_exception": (world.relation == 2) + & world.exceptions[np.maximum(world.person, 0)], + "independent_attributes": np.isin(world.relation, [3, 4, 5, 6]), + } + metrics = { + "base_accuracy": float(correct[:N_BASE].mean()), + "derived_accuracy": float(correct[N_BASE:].mean()), + "value_nll": float(nll[:N_BASE].mean()), + "nontermination_rate": float((~ended).mean()), + "strata": {k: float(correct[v].mean()) for k, v in strata.items()}, + "learning_threshold_passed": bool( + correct[:N_BASE].mean() >= 0.99 and correct[N_BASE:].mean() >= 0.99 + ), + } + return metrics, { + "prediction": predictions, + "ended": ended, + "correct": correct, + "value_nll": nll, + } + + +def code_fingerprint(): + root = Path(__file__).resolve().parents[2] + files = sorted((root / "src" / "llm_memory_editability").glob("*.py")) + return { + "git_revision": subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=root, text=True + ).strip(), + "git_dirty": bool( + subprocess.check_output(["git", "status", "--porcelain"], cwd=root, text=True).strip() + ), + "source_sha256": { + str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in files + }, + } + + +def train(args): + device = torch.device(args.device) + torch.set_num_threads(args.threads) + torch.manual_seed(args.seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + world = load_world(args.world) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + resume = torch.load(out / "resume.pt", weights_only=False) if args.resume else None + if resume is None and (out / "config.json").exists(): + raise ValueError("Output already contains a run; use a fresh output directory") + schedule = curriculum(world, args.order, args.steps) + model = CausalLM(ModelConfig(world.vocab_size)).to(device) + data = tensor_data(world, device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + checkpoints = sorted( + {0, *range(660, 5281, 660), *range(7280, args.steps + 1, 2000), args.steps} + ) + config = { + **vars(args), + "model": model.config_dict(), + "protocol": "v2.3", + "phase": "development", + "world_seed": world.seed, + "parameters": sum(p.numel() for p in model.parameters()), + "torch": torch.__version__, + "python": platform.python_version(), + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast, FP32 weights/loss/Adam moments", + "checkpoints": checkpoints, + "schedule_sha256": array_hash(schedule), + "truth_sha256": array_hash(world.answers), + "flops_method": "executed-shape matmul estimate; elementwise and evaluation excluded", + **code_fingerprint(), + } + timeline, anchors = [], {} + counts = np.zeros(N_QUERIES, dtype=np.int64) + weighted_exposure = np.zeros(8) + train_seconds = 0.0 + losses = [] + steps_since_checkpoint = 0 + first_step = 0 + if resume is None: + write_json(out / "config.json", config) + np.save(out / "schedule.npy", schedule) + else: + # Exact continuation from the last predefined checkpoint's full training state. + original = json.loads((out / "config.json").read_text()) + for key in ("schedule_sha256", "truth_sha256", "seed", "order", "steps", "lr"): + if original[key] != config[key]: + raise ValueError(f"Resume mismatch on {key}") + model.load_state_dict(resume["model"]) + optimizer.load_state_dict(resume["optimizer"]) + torch.set_rng_state(resume["torch_rng"]) + if device.type == "cuda" and resume["cuda_rng"] is not None: + torch.cuda.set_rng_state(resume["cuda_rng"], device) + timeline, anchors = resume["timeline"], resume["anchors"] + counts, weighted_exposure = resume["counts"], resume["weighted_exposure"] + train_seconds = resume["train_seconds"] + first_step = resume["step"] + resumes = ( + json.loads((out / "resumes.json").read_text()) + if (out / "resumes.json").exists() + else [] + ) + resumes.append({"from_step": first_step, **code_fingerprint()}) + write_json(out / "resumes.json", resumes) + if device.type == "cuda": + torch.cuda.reset_peak_memory_stats(device) + for step in range(first_step, args.steps + 1): + if step in checkpoints and not (resume is not None and step == first_step): + start_eval = time.perf_counter() + metrics, arrays = evaluate(model, data, world) + for anchor, known in anchors.items(): + metrics[f"forgetting_since_{anchor}"] = ( + float((~arrays["correct"][known]).mean()) if known.any() else None + ) + if step in (2640, 5280): + anchors[step] = arrays["correct"].copy() + np.savez_compressed(out / f"predictions-{step}.npz", **arrays, exposure=counts) + # CPU state for portability; all predefined checkpoints retained. + torch.save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + record = { + "step": step, + **metrics, + "train_seconds": train_seconds, + "train_matmul_flops_estimate": step * matmul_flops(model.config, 128), + "presentations": int(counts.sum()), + "coverage_base": float((counts[:N_BASE] > 0).mean()), + "coverage_derived": float((counts[N_BASE:] > 0).mean()), + "world_tokens": int((counts * (world.lengths + 2)).sum()), + "input_tokens_including_padding": step * 128 * 6, + "supervised_tokens": step * 128 * 2, + "lr_weighted_exposure_by_relation": dict( + zip((*RELATIONS, "derived"), weighted_exposure.tolist(), strict=True) + ), + "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "eval_and_checkpoint_seconds": time.perf_counter() - start_eval, + "mean_training_loss_since_previous": float(np.mean(losses)) if losses else None, + } + timeline.append(record) + write_json(out / "learning.json", timeline) + print( + json.dumps( + { + "event": "checkpoint", + "step": step, + "base": metrics["base_accuracy"], + "derived": metrics["derived_accuracy"], + "train_seconds": train_seconds, + } + ), + flush=True, + ) + losses = [] + steps_since_checkpoint = 0 + state = { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "timeline": timeline, + "anchors": anchors, + "counts": counts, + "weighted_exposure": weighted_exposure, + "train_seconds": train_seconds, + "step": step, + } + torch.save(state, out / "resume.pt.tmp") + os.replace(out / "resume.pt.tmp", out / "resume.pt") + if step == args.steps: + break + model.train() + lr = args.lr * min((step + 1) / 2000, 1.0) + for group in optimizer.param_groups: + group["lr"] = lr + ids_np = schedule[step] + ids = torch.as_tensor(ids_np, device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(data["tokens"][ids], data["positions"][ids]) + loss = F.cross_entropy( + logits.float().reshape(-1, world.vocab_size), data["labels"][ids].reshape(-1) + ) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(loss) or not torch.isfinite(norm): + write_json( + out / "failure.json", + { + "step": step, + "reason": "nonfinite loss or gradient", + "train_seconds": train_seconds, + }, + ) + raise FloatingPointError("Nonfinite loss or gradient") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - started + losses.append(loss.item()) + np.add.at(counts, ids_np, 1) + weighted_exposure += np.bincount(world.relation[ids_np], minlength=8) * lr + steps_since_checkpoint += 1 + if (step + 1) % 100 == 0: + print( + json.dumps( + { + "event": "progress", + "step": step + 1, + "loss": float(np.mean(losses[-100:])), + "train_seconds": train_seconds, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "step": args.steps, + "status": "complete", + "final": timeline[-1], + "exposure_sha256": array_hash(counts), + }, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--order", choices=["SA", "AS"], required=True) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--steps", type=int, default=13280) + parser.add_argument("--lr", type=float, default=1e-4) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--resume", action="store_true") + train(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bridge_reencoding.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bridge_reencoding.py new file mode 100644 index 0000000000000000000000000000000000000000..1dbbe769879cff4d2b00a6c39164102b50d035e3 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bridge_reencoding.py @@ -0,0 +1,438 @@ +"""Fixed-weight, self-decoded bridge re-encoding in existing small GPTs. + +The intervention uses the original tied readout over the complete vocabulary. +Only the explicitly named oracle condition accesses graph answers at inference. +The wrong_entity control is an alternative to the model's decoded token, not a +guaranteed incorrect answer: its accidental agreement with truth is reported. +""" + +from __future__ import annotations + +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import build_world, model_digest +from .representation_alignment import RepresentationGPT, new_model +from .storage_composition import data_digest, evaluate, file_hash, generate_rows +from .text_pretrain import WORDS, composite_sentence + +CONDITIONS = ("baseline", "self_decode", "wrong_entity", "oracle") + + +def reencode_state(state, embedding, alpha, variant="norm_matched"): + """Interpolate residual and normalized embedding, without renormalizing the sum. + + norm_matched gives the replacement embedding the original state's norm. + paper_unit uses a unit embedding directly. Neither preserves the mixture's + norm in general; alpha=0 returns the original tensor exactly. + """ + if not 0 <= alpha <= 1: + raise ValueError("alpha must be between zero and one") + if variant not in ("norm_matched", "paper_unit"): + raise ValueError("Unknown re-encoding variant") + if alpha == 0: + return state + replacement = F.normalize(embedding, dim=-1) + if variant == "norm_matched": + replacement = state.norm(dim=-1, keepdim=True) * replacement + return (1 - alpha) * state + alpha * replacement + + +def alternative_entity(decoded, bridge_start, bridge_count): + """A non-self bridge-entity choice, independent of the true bridge identity.""" + if bridge_count < 2: + raise ValueError("At least two bridge entity tokens are required") + return bridge_start + torch.remainder(decoded - bridge_start + 1, bridge_count) + + +class ReencodingGPT(RepresentationGPT): + """Original computation with a single intervention at block 0, position 3.""" + + def configure(self, condition, alpha, oracle_table=None, variant="norm_matched"): + if condition not in CONDITIONS: + raise ValueError(f"Unknown condition: {condition}") + if not 0 <= alpha <= 1: + raise ValueError("alpha must be between zero and one") + if variant not in ("norm_matched", "paper_unit"): + raise ValueError("Unknown re-encoding variant") + if condition == "oracle" and oracle_table is None: + raise ValueError("Oracle condition requires an explicit diagnostic truth table") + self.condition, self.alpha, self.variant = condition, float(alpha), variant + # Deliberately outside state_dict: neither weights nor model hashes change. + self.oracle_table = oracle_table if condition == "oracle" else None + + def _choice(self, state, tokens): + decoded = F.linear(self.ln_final(state), self.token.weight).argmax(-1) + selected = decoded + oracle_available = torch.zeros_like(decoded, dtype=torch.bool) + if self.condition == "wrong_entity": + selected = alternative_entity(decoded, self.bridge_start, self.bridge_count) + elif self.condition == "oracle": + oracle = self.oracle_table[tokens[:, 1], tokens[:, 3]] + oracle_available = oracle >= 0 + # Invalid autonomously generated heads have no graph truth. Do not + # fabricate an oracle answer; retain the model's decoded token. + selected = torch.where(oracle_available, oracle, decoded) + return decoded, selected, oracle_available + + def forward(self, tokens, positions=None, repeats=None, return_bridge=False): + if not return_bridge and (self.condition == "baseline" or self.alpha == 0): + return super().forward(tokens, positions=positions, repeats=repeats) + if tokens.shape[1] < 4: + raise ValueError("The intervention requires the causal first-relation prefix") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + info = None + for index, block in enumerate(self.iter_blocks(repeats)): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + if index == 0: + state = x[:, 3] + decoded, selected, oracle_available = self._choice(state, tokens) + replacement = ( + state + if self.condition == "baseline" + else reencode_state(state, self.token(selected), self.alpha, self.variant) + ) + if self.condition != "baseline" and self.alpha: + x = x.clone() + x[:, 3] = replacement + info = { + "state": state, + "replacement": replacement, + "decoded": decoded, + "selected": selected, + "oracle_available": oracle_available, + } + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, self.token.weight) + return (logits, info) if return_bridge else logits + + +def _device_settings(device): + device = torch.device(device) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + return device + + +def _load(spec, device): + parent = Path(spec["parent_dir"]).resolve() + checkpoint = parent / "model.pt" + payload = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = new_model(payload["spec"], device) + model.load_state_dict(payload["model"]) + model.__class__ = ReencodingGPT + model.bridge_start = len(WORDS) + payload["spec"]["heads_n"] + model.bridge_count = payload["spec"]["bridges_n"] + model.configure("baseline", 0) + model.eval().requires_grad_(False) + world = dict(np.load(parent / "world.npz")) + rebuilt = build_world(payload["spec"]) + if data_digest(world) != data_digest(rebuilt): + raise AssertionError("Saved world differs from the parent specification") + oracle = torch.full( + (model.config.vocab_size, model.config.vocab_size), -1, device=device, dtype=torch.long + ) + for h, r, target in np.concatenate((world["common_atomic"], world["extra_atomic"])): + oracle[h, r] = int(target) + return model, world, oracle, payload["spec"], checkpoint + + +@torch.no_grad() +def _diagnostics(model, rows, device, batch_size): + prompts = np.asarray([composite_sentence(row)[:7] for row in rows]) + collected = {} + model.eval() + for start in range(0, len(rows), batch_size): + tokens = torch.as_tensor(prompts[start : start + batch_size], device=device) + _, info = model(tokens, return_bridge=True) + values = { + "decoded_bridge": info["decoded"], + "selected_bridge": info["selected"], + "oracle_available": info["oracle_available"], + "state_norm": info["state"].norm(dim=-1), + "replacement_norm": info["replacement"].norm(dim=-1), + } + for key, value in values.items(): + collected.setdefault(key, []).append(value.cpu().numpy()) + result = {key: np.concatenate(value) for key, value in collected.items()} + result["decoded_bridge_correct"] = result["decoded_bridge"] == rows[:, 2] + result["selected_bridge_correct"] = result["selected_bridge"] == rows[:, 2] + result["decoded_is_entity"] = result["decoded_bridge"] >= len(WORDS) + return result + + +def _subset_metric(correct, mask): + return { + "n": int(mask.sum()), + "coverage": float(mask.mean()), + "accuracy": float(correct[mask].mean()) if mask.any() else None, + } + + +@torch.no_grad() +def _evaluate_condition(model, world, device, batch_size): + # Reuse the established complete answer/period/EOS scorer unchanged. Its + # canonical batch is 512; diagnostics use the same shapes for exact decoding. + if batch_size != 512: + raise ValueError("Use batch_size=512 to preserve established evaluation arithmetic") + metrics, predictions = evaluate(model, world, "low", device) + model.eval() + for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): + generated = predictions[name + "_generated"] + metrics[name]["period_accuracy"] = float((generated[:, 1] == 5).mean()) + metrics[name]["eos_accuracy"] = float((generated[:, 2] == 1).mean()) + metrics[name]["format_accuracy"] = float( + ((generated[:, 1] == 5) & (generated[:, 2] == 1)).mean() + ) + for name in ("familiar_test", "strict_test"): + rows = world[name] + info = _diagnostics(model, rows, device, batch_size) + predictions.update({name + "_" + key: value for key, value in info.items()}) + for key in ("decoded_bridge_correct", "selected_bridge_correct", "decoded_is_entity"): + metrics[name][key + "_coverage"] = float(info[key].mean()) + if model.condition == "wrong_entity": + metrics[name]["alternative_accidental_gold_match"] = float( + info["selected_bridge_correct"].mean() + ) + correct = predictions[name + "_correct"] + metrics[name]["self_bridge_correct_subset"] = _subset_metric( + correct, info["decoded_bridge_correct"] + ) + first = rows[:, [0, 1, 2]] + second = rows[:, [2, 3, 4]] + for role, atoms in (("first", first), ("second", second)): + _, raw = generate_rows(model, atoms, device, batch_size=batch_size) + predictions.update({f"{name}_{role}_{key}": value for key, value in raw.items()}) + autonomous_second = second.copy() + autonomous_second[:, 0] = predictions[name + "_first_generated"][:, 0] + _, raw = generate_rows(model, autonomous_second, device, batch_size=batch_size) + predictions.update({f"{name}_autonomous_{key}": value for key, value in raw.items()}) + return metrics, predictions + + +def cases(spec): + """One baseline and the frozen alpha/variant/condition matrix.""" + conditions = list(spec.get("conditions", CONDITIONS)) + if len(conditions) != len(set(conditions)) or any(c not in CONDITIONS for c in conditions): + raise ValueError("Conditions must be distinct known names") + alphas = spec.get("alphas", [spec.get("alpha", 0)]) + variants = spec.get("variants", ["norm_matched"]) + if len(alphas) != len(set(alphas)) or not alphas or any(not 0 <= a <= 1 for a in alphas): + raise ValueError("alphas must contain distinct values in [0,1]") + if len(variants) != len(set(variants)) or not variants: + raise ValueError("variants must be distinct and nonempty") + if any(v not in ("norm_matched", "paper_unit") for v in variants): + raise ValueError("Unknown re-encoding variant") + matrix = {"baseline": {"condition": "baseline", "alpha": 0, "variant": "norm_matched"}} + for variant in variants: + for alpha in alphas: + for condition in conditions: + if condition == "baseline": + continue + name = f"{variant}-a{float(alpha):g}-{condition}" + matrix[name] = {"condition": condition, "alpha": float(alpha), "variant": variant} + return matrix + + +def _evaluate_all(model, world, oracle, spec, callback=None): + matrix = cases(spec) + metrics, arrays = {}, {} + for name, case in matrix.items(): + model.configure( + case["condition"], + case["alpha"], + oracle if case["condition"] == "oracle" else None, + case["variant"], + ) + metrics[name], predictions = _evaluate_condition( + model, world, next(model.parameters()).device, spec.get("batch_size", 512) + ) + arrays.update({name + "__" + key: value for key, value in predictions.items()}) + if callback is not None: + callback(name, case, metrics[name], predictions) + for name in ("familiar_test", "strict_test"): + baseline = arrays[f"baseline__{name}_coverage"] + # This is the fixed pre-intervention prerequisite pool for every case. + # In particular, the destructive alternative-entity control cannot + # determine which chains enter the main conditional comparison. + arrays[f"common__{name}_atomic_correct"] = baseline + for condition in matrix: + correct = arrays[f"{condition}__{name}_correct"] + arrays[f"{condition}__{name}_baseline_common_atoms"] = baseline + metrics[condition][name]["fixed_baseline_atoms_subset"] = _subset_metric( + correct, baseline + ) + self_ok = arrays[f"{condition}__{name}_decoded_bridge_correct"] + joint = baseline & self_ok + arrays[f"{condition}__{name}_common_atoms_and_self_bridge"] = joint + metrics[condition][name]["common_atoms_and_self_bridge_subset"] = _subset_metric( + correct, joint + ) + model.configure("baseline", 0) + return metrics, arrays + + +def run(spec, out, device="cuda:2"): + """Evaluate one existing checkpoint; never train or overwrite an attempt.""" + out = Path(out) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + out.mkdir(parents=True, exist_ok=True) + device = _device_settings(device) + started = time.perf_counter() + model, world, oracle, parent_spec, checkpoint = _load(spec, device) + digest = model_digest(model) + source = { + str(Path(__file__).resolve()): file_hash(__file__), + "parent_checkpoint": file_hash(checkpoint), + } + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "source": source, + "world_sha256": data_digest(world), + "model_sha256": digest, + "pid": os.getpid(), + "device": str(device), + "started_utc": utc(), + "new_training_updates": 0, + "optimizer_updates": 0, + "cases": cases(spec), + "formula_norm_matched": "(1-alpha)*h + alpha*||h||*normalize(E_decoded)", + "formula_paper_unit": "(1-alpha)*h + alpha*normalize(E_decoded)", + "decoder": "original ln_final and tied output, argmax over the full vocabulary", + "wrong_entity_scope": "non-self bridge entity, independent of gold; may equal true bridge", + "bridge_token_start": model.bridge_start, + "bridge_token_count": model.bridge_count, + "main_prerequisite_subset": "both necessary atoms correct under the fixed baseline", + "alpha_zero_exact_bypass": True, + "allow_tf32": True, + } + write_json(out / "run.json", manifest) + np.savez_compressed(out / "world.npz", **world) + history = [] + + def record(name, case, metrics, predictions): + history.append( + { + "step": len(history) + 1, + "case": name, + **case, + "metrics": metrics, + "optimizer_updates": 0, + "wall_seconds": time.perf_counter() - started, + "created_utc": utc(), + } + ) + # Each condition is durable before the next one starts. + np.savez_compressed(out / f"predictions-{name}.npz", **predictions) + write_json(out / "learning.json", history) + write_json( + out / "status.json", + { + "state": "running", + "step": len(history), + "budget": len(manifest["cases"]), + "optimizer_updates": 0, + }, + ) + + metrics, predictions = _evaluate_all(model, world, oracle, spec, record) + assert model_digest(model) == digest, "Evaluation changed model parameters" + # Final common-prerequisite subsets are known only after the full matrix. + write_json(out / "learning.json", history) + # At zero weight all conditions must recover complete baseline generation. + for key, value in predictions.items(): + if key.endswith(("_generated", "_answer_nll")): + case, suffix = key.split("__", 1) + if manifest["cases"][case]["alpha"] == 0: + np.testing.assert_array_equal(value, predictions["baseline__" + suffix]) + np.savez_compressed(out / "predictions.npz", **predictions) + write_json(out / "metrics.json", metrics) + result = { + "state": "evaluation-complete-awaiting-independent-audit", + "finished_utc": utc(), + "wall_seconds": time.perf_counter() - started, + "model_sha256": digest, + "new_training_updates": 0, + "optimizer_updates": 0, + "conditions": list(metrics), + "prediction_arrays": len(predictions), + "step": len(history), + } + write_json(out / "evaluation-complete.json", result) + write_json(out / "status.json", {**result, "step": len(history)}) + return result + + +def audit(out, device="cuda:2"): + """Reload weights and independently recompute every saved prediction array.""" + out = Path(out) + device = _device_settings(device) + manifest = json.loads((out / "run.json").read_text()) + model, world, oracle, _, checkpoint = _load(manifest["spec"], device) + assert file_hash(checkpoint) == manifest["source"]["parent_checkpoint"] + assert model_digest(model) == manifest["model_sha256"] + assert data_digest(world) == manifest["world_sha256"] + metrics, actual = _evaluate_all(model, world, oracle, manifest["spec"]) + saved = dict(np.load(out / "predictions.npz")) + assert set(saved) == set(actual), "Prediction array set changed" + max_error = 0.0 + for key, value in actual.items(): + if value.dtype.kind == "f": + max_error = max(max_error, float(np.max(np.abs(value - saved[key])))) + np.testing.assert_allclose(value, saved[key], atol=1e-5, rtol=1e-5) + else: + np.testing.assert_array_equal(value, saved[key]) + # Recount complete-answer accuracy independently of the established scorer. + for condition, groups in metrics.items(): + for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): + pred = actual[f"{condition}__{name}_generated"] + correct = (pred[:, 0] == world[name][:, -1]) & (pred[:, 1] == 5) & (pred[:, 2] == 1) + np.testing.assert_array_equal(correct, actual[f"{condition}__{name}_correct"]) + assert float(correct.mean()) == groups[name]["accuracy"] + assert model_digest(model) == manifest["model_sha256"] + result = { + "passed": True, + "independently_reloaded": True, + "raw_predictions_recounted": True, + "prediction_arrays": len(actual), + "max_float_error": max_error, + "audit_pid": os.getpid(), + "independent_process": os.getpid() != manifest["pid"], + "finished_utc": utc(), + "metrics": metrics, + } + write_json(out / "audit.json", result) + complete = json.loads((out / "evaluation-complete.json").read_text()) + complete.update(state="complete", independently_reloaded=True, audit_finished_utc=utc()) + write_json(out / "complete.json", complete) + write_json(out / "status.json", {**complete, "step": len(metrics), "optimizer_updates": 0}) + return result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bridge_workspace.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bridge_workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3ee68821631607b4922cfce3654cd2784d82ba --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/bridge_workspace.py @@ -0,0 +1,1112 @@ +"""Causal entity-coordinate interventions using an averaged prefix Jacobian. + +This is a restricted adaptation of Anthropic's Jacobian lens: calibration and +donors contain only the first fact's query prefix. No relation suffix or answer +gradient is used to construct a direction. Execution layers count shared block +occurrences separately. All model parameters remain frozen. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import time +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import file_hash + +SWAPS = ("swap", "swap_x2", "random_swap", "full_prefix", "swap_back") +ERASURES = ( + "erase_state", + "erase_mlp", + "erase_attention", + "random_state", + "random_mlp", + "random_attention", + "restore_mlp", + "fixed_entity_mlp", + "fixed_entity_random_mlp", +) + + +class ModelView: + """Expose native attention/MLP increments without replacing trained modules.""" + + def __init__(self, model): + if model.training: + raise ValueError("Interventions require eval mode") + self.model = model + self.large = hasattr(model, "transformer") + if self.large: + t = model.transformer + self.embedding, self.position, self.norm = t.wte, t.wpe, t.ln_f + self.blocks = list(t.h) * model.repeats + self.heads = model.config.n_head + else: + self.embedding, self.position, self.norm = model.token, model.position, model.ln_final + self.blocks = list(model.iter_blocks()) + self.heads = model.config.heads + self.width = self.embedding.weight.shape[1] + self.device = self.embedding.weight.device + + def embed(self, tokens): + return self.embedding(tokens) + self.position( + torch.arange(tokens.shape[1], device=self.device) + ) + + def parts(self, x, block, *, math_attention=False): + if self.large: + z = block.ln_1(x) + q, k, v = block.attn.c_attn(z).split(self.width, dim=-1) + project, ln2 = block.attn.c_proj, block.ln_2 + else: + z = block.ln1(x) + q, k, v = block.attention.qkv(z).chunk(3, dim=-1) + project, ln2 = block.attention.proj, block.ln2 + shape = (len(x), x.shape[1], self.heads, self.width // self.heads) + q, k, v = (a.reshape(shape).transpose(1, 2) for a in (q, k, v)) + if math_attention: + # The explicit FP32 expression permits batched VJPs on torch 2.6. + scores = q @ k.transpose(-1, -2) / (self.width // self.heads) ** 0.5 + mask = torch.ones(x.shape[1], x.shape[1], device=self.device, dtype=torch.bool).tril() + y = scores.masked_fill(~mask, -torch.inf).softmax(-1) @ v + else: + y = F.scaled_dot_product_attention(q, k, v, is_causal=True) + attention = project(y.transpose(1, 2).reshape(len(x), x.shape[1], self.width)) + after_attention = x + attention + mlp = block.mlp(ln2(after_attention)) + return after_attention + mlp, attention, mlp + + def hidden( + self, tokens, *, layer=None, sender=None, delta=None, capture=False, math_attention=False + ): + x, states, attentions, mlps = self.embed(tokens), [], [], [] + for index, block in enumerate(self.blocks): + x, attention, mlp = self.parts(x, block, math_attention=math_attention) + if capture: + states.append(x[:, sender].detach()) + attentions.append(attention[:, sender].detach()) + mlps.append(mlp[:, sender].detach()) + if index == layer: + if sender is None or delta is None or delta.shape != x[:, sender].shape: + raise ValueError("A patch requires one delta per example at a fixed sender") + mask = F.one_hot(torch.tensor(sender, device=self.device), x.shape[1]).to(x.dtype) + x = x + mask[None, :, None] * delta[:, None, :] + if capture: + return x, tuple(torch.stack(a) for a in (states, attentions, mlps)) + return x + + def logits(self, tokens, **patch): + return F.linear(self.norm(self.hidden(tokens, **patch)[:, -1]), self.embedding.weight) + + +def average_prefix_jacobian(view, prefixes, sender, *, chunk=32): + """E[d h_final,sender / d h_layer,sender], with labels absent from the graph. + + A shared shift applied to all independent calibration prompts differentiates + their mean output, exactly averaging their Jacobians. Parameters need no + gradients. The endpoint is the residual before the final LayerNorm. + """ + if any(p.requires_grad for p in view.model.parameters()): + raise ValueError("Freeze model parameters before constructing the lens") + with torch.no_grad(): + x, boundaries = view.embed(prefixes), [] + for block in view.blocks: + x, _, _ = view.parts(x, block, math_attention=True) + boundaries.append(x.detach()) + jacobians = [] + identity = torch.eye(view.width, device=view.device) + for layer, boundary in enumerate(boundaries): + shift = torch.zeros(view.width, device=view.device, requires_grad=True) + mask = F.one_hot(torch.tensor(sender, device=view.device), prefixes.shape[1]).float() + x = boundary + mask[None, :, None] * shift[None, None, :] + for block in view.blocks[layer + 1 :]: + x, _, _ = view.parts(x, block, math_attention=True) + endpoint = x[:, sender].mean(0) + rows = [] + for start in range(0, view.width, chunk): + rows.append( + torch.autograd.grad( + endpoint, + shift, + grad_outputs=identity[start : start + chunk], + is_grads_batched=True, + retain_graph=start + chunk < view.width, + )[0].detach() + ) + jacobians.append(torch.cat(rows)) + return torch.stack(jacobians) + + +def swap_coordinates(state, basis): + """Swap two coefficients in a nonorthogonal frame, preserving its complement.""" + if basis.shape != (*state.shape, 2): + raise ValueError("Expected [example, width, two semantic axes]") + coefficients = (torch.linalg.pinv(basis.double()) @ state.double()[..., None]).squeeze(-1) + difference = coefficients.flip(-1) - coefficients + return state + (basis.double() @ difference[..., None]).squeeze(-1).to(state.dtype) + + +def projection(state, direction): + direction = F.normalize(direction, dim=-1) + return (state * direction).sum(-1, keepdim=True) * direction + + +def match_norm(delta, reference): + norm = delta.norm(dim=-1, keepdim=True) + if bool(((norm < 1e-12) & (reference.norm(dim=-1, keepdim=True) > 1e-6)).any()): + raise ValueError("Degenerate random control") + return delta * reference.norm(dim=-1, keepdim=True) / norm.clamp_min(1e-12) + + +def control_observation(changed, baseline): + """Record numerical control outcomes without silently dropping sensitive cases.""" + mask = np.any(changed != baseline, axis=1) + return { + "n_queries": len(baseline), + "generated_rows_changed": int(mask.sum()), + "answer_rows_changed": int((changed[:, 0] != baseline[:, 0]).sum()), + "changed_query_indices": np.flatnonzero(mask).tolist(), + "changed_fraction": float(mask.mean()), + "exact": bool(not mask.any()), + } + + +def _rank(seed, *values): + return hashlib.sha256(json.dumps([seed, *map(int, values)]).encode()).digest() + + +def select_pairs(atoms, first_families, seed, per_family, *, ood=None): + """Choose prefixes/donors and all shared continuations using graph truth only. + + Donors use the same r1 and first-fact family. Every pair has at least two + distinct shared r2 with different original/counterfactual tails. A pair is + selected before scoring; its exact same prefix intervention serves every r2. + """ + atoms = np.asarray(atoms, dtype=np.int64) + outgoing, relation = defaultdict(dict), defaultdict(list) + for index, (head, r, tail) in enumerate(atoms): + if int(r) in outgoing[int(head)]: + raise ValueError("Ambiguous atomic truth") + outgoing[int(head)][int(r)] = (int(tail), index) + relation[int(r)].append(index) + groups, queries, coverage = [], [], {} + for name, indices in first_families.items(): + allowed = set(map(int, indices)) + eligible = [] + for first in sorted(allowed): + head, r1, bridge = map(int, atoms[first]) + candidates = [] + for donor in relation[r1]: + dh, _, db = map(int, atoms[donor]) + if donor not in allowed or dh == head or db == bridge: + continue + common = sorted(set(outgoing[bridge]) & set(outgoing[db])) + common = [ + r + for r in common + if outgoing[bridge][r][0] != outgoing[db][r][0] + and not {outgoing[bridge][r][0], outgoing[db][r][0]} & {head, dh, bridge, db} + ] + if len(common) >= 2: + candidates.append((donor, common)) + if candidates: + donor, common = min(candidates, key=lambda v: _rank(seed, first, v[0])) + eligible.append((first, donor, common)) + eligible.sort(key=lambda v: _rank(seed, v[0])) + coverage[name] = {"candidate_first_facts": len(allowed), "eligible": len(eligible)} + for first, donor, common in eligible[:per_family]: + head, r1, bridge = map(int, atoms[first]) + dh, _, db = map(int, atoms[donor]) + group = len(groups) + groups.append([head, r1, bridge, dh, db, first, donor]) + for r2 in common: + tail, second = outgoing[bridge][r2] + ct, cf_second = outgoing[db][r2] + kind = ( + name + if ood is None + else ("ood" if ood[first] else "id") + ("_ood" if ood[second] else "_id") + ) + queries.append((group, r2, tail, ct, second, cf_second, kind)) + coverage[name]["selected"] = min(len(eligible), per_family) + if not groups: + raise ValueError("No graph-eligible cross-relation pairs; do not reroll") + return { + "groups": np.asarray(groups, dtype=np.int64), + "queries": np.asarray([r[:6] for r in queries], dtype=np.int64), + "strata": np.asarray([r[6] for r in queries]), + "counterfactual_strata": np.asarray( + [ + r[6] + if ood is None + else ("ood" if ood[groups[r[0]][6]] else "id") + ("_ood" if ood[r[5]] else "_id") + for r in queries + ] + ), + "coverage": coverage, + } + + +def prefixes(facts, large, metadata): + facts = np.asarray(facts) + if large: + return np.column_stack( + (facts[:, 0] + metadata["entity_offset"], facts[:, 1] + metadata["relation_offset"]) + ) + return np.column_stack( + (np.full(len(facts), 2), facts[:, 0], np.full(len(facts), 3), facts[:, 1]) + ) + + +def prompts(rows, large, metadata): + if large: + from .grokking_reproduction import encode_rows + + return encode_rows(rows, metadata)[0][:, : rows.shape[1] - 1] + from .text_pretrain import atomic_sentence, composite_sentence + + render = atomic_sentence if rows.shape[1] == 3 else composite_sentence + length = 5 if rows.shape[1] == 3 else 7 + return np.asarray([render(row)[:length] for row in rows]) + + +def query_training_masks(world, payload, groups, queries, large): + """Count composition exposure without using scores or answer correctness.""" + if large: + support = round(payload["spec"]["phi"] * (~world["ood"]).sum()) + trained = world["chains"][world["train_order"][:support]][:, :3] + else: + trained = world["train_composite"][:, [0, 1, 3]] + trained = set(map(tuple, trained)) + recipient = np.asarray([(groups[g, 0], groups[g, 1], r2) in trained for g, r2, *_ in queries]) + donor = np.asarray([(groups[g, 3], groups[g, 1], r2) in trained for g, r2, *_ in queries]) + return { + "recipient_query_trained": recipient, + "counterfactual_query_trained": donor, + "both_queries_untrained": ~recipient & ~donor, + } + + +def load_task(spec, device): + payload = torch.load(spec["checkpoint"], map_location="cpu", weights_only=False) + if "checkpoint_step" in spec: + saved_step = payload.get("step", payload["spec"].get("steps")) + assert saved_step == spec["checkpoint_step"], "Wrong checkpoint training step" + if spec["family"] == "reproduction": + from .grokking_reproduction import construct + + data = Path(spec["data"]) + metadata = json.loads((data / "complete.json").read_text()) + model = construct(payload["spec"], metadata, device) + world = dict(np.load(data / "world.npz")) + panels = dict(np.load(data / "panels.npz")) + atoms = world["atoms"].astype(np.int64) + families = {"id": np.flatnonzero(~world["ood"]), "ood": np.flatnonzero(world["ood"])} + ood = world["ood"] + entities = np.arange( + metadata["entity_offset"], metadata["entity_offset"] + metadata["entities"] + ) + else: + from .representation_alignment import new_model + + model = new_model(payload["spec"], device) + world = dict(np.load(Path(spec["checkpoint"]).parent / "world.npz")) + metadata = {"entity_offset": 0} + atoms = np.concatenate((world["common_atomic"], world["anchor_atomic"])) + families = {} + for name in ("familiar_test", "strict_test"): + firsts = set(map(tuple, world[name][:, :3])) + families[name] = np.asarray([i for i, a in enumerate(atoms) if tuple(a) in firsts]) + ood = None + entities = np.arange(21, model.config.vocab_size) + panels = {k: world[k] for k in ("familiar_test", "strict_test")} + model.load_state_dict(payload["model"]) + model.eval().requires_grad_(False) + return ModelView(model), payload, metadata, world, atoms, families, ood, entities, panels + + +@torch.no_grad() +def trace_in_batches(view, tokens, sender, batch_size, amp): + collected = [] + for start in range(0, len(tokens), batch_size): + batch = torch.as_tensor(tokens[start : start + batch_size], device=view.device) + with torch.autocast("cuda", dtype=torch.bfloat16, enabled=amp): + _, trace = view.hidden(batch, sender=sender, capture=True) + collected.append(tuple(a.float() for a in trace)) + return tuple(torch.cat([a[j] for a in collected], dim=1) for j in range(3)) + + +@torch.no_grad() +def generate( + view, + tokens, + targets, + counterfactual, + metadata, + batch_size, + *, + layer=None, + sender=None, + delta=None, +): + """Greedy generation with feedback; scoring retains both target probabilities.""" + offset = metadata["entity_offset"] + targets, counterfactual = targets + offset, counterfactual + offset + generated, original_logp, cf_logp, top_ids, top_scores = [], [], [], [], [] + for start in range(0, len(tokens), batch_size): + x = torch.as_tensor(tokens[start : start + batch_size], device=view.device) + patch = ( + {} + if layer is None + else {"layer": layer, "sender": sender, "delta": delta[start : start + batch_size]} + ) + draws = [] + for index in range(2 if view.large else 3): + with torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): + logits = view.logits(x, **patch).float() + if index == 0: + logs = logits.log_softmax(-1) + arange = torch.arange(len(x), device=view.device) + original_logp.append( + logs[ + arange, + torch.as_tensor(targets[start : start + batch_size], device=view.device), + ] + .cpu() + .numpy() + ) + cf_logp.append( + logs[ + arange, + torch.as_tensor( + counterfactual[start : start + batch_size], device=view.device + ), + ] + .cpu() + .numpy() + ) + scores, ids = logs.topk(min(10, logs.shape[-1]), dim=-1) + top_ids.append(ids.cpu().numpy()) + top_scores.append(scores.cpu().numpy()) + answer = logits.argmax(-1) + draws.append(answer.cpu().numpy()) + x = torch.cat((x, answer[:, None]), dim=1) + generated.append(np.stack(draws, axis=1)) + return { + "generated": np.concatenate(generated), + "original_logp": np.concatenate(original_logp), + "cf_logp": np.concatenate(cf_logp), + "top_ids": np.concatenate(top_ids), + "top_logp": np.concatenate(top_scores), + } + + +def summarize(result, targets, counterfactual, metadata, strata, groups=None): + generated = result["generated"] + original = generated[:, 0] == targets + metadata["entity_offset"] + cf = generated[:, 0] == counterfactual + metadata["entity_offset"] + format_ok = ( + generated[:, 1] == metadata["end_marker"] + if "end_marker" in metadata + else (generated[:, 1] == 5) & (generated[:, 2] == 1) + ) + output = {} + for name in ("all", *sorted(set(strata))): + mask = np.ones(len(strata), dtype=bool) if name == "all" else strata == name + row = { + "n_queries": int(mask.sum()), + "answer_accuracy": float(original[mask].mean()), + "accuracy": float((original & format_ok)[mask].mean()), + "cf_answer_accuracy": float(cf[mask].mean()), + "cf_accuracy": float((cf & format_ok)[mask].mean()), + "format_accuracy": float(format_ok[mask].mean()), + "answer_nll": float(-result["original_logp"][mask].mean()), + "cf_nll": float(-result["cf_logp"][mask].mean()), + } + if groups is not None: + unique = np.unique(groups[mask]) + row["n_first_facts"] = len(unique) + row["all_relations_cf_accuracy"] = float( + np.mean([cf[mask & (groups == g)].all() for g in unique]) + ) + row["mean_first_fact_cf_accuracy"] = float( + np.mean([cf[mask & (groups == g)].mean() for g in unique]) + ) + output[name] = row + return output + + +def run(spec, settings, out, gpu): + """Run one checkpoint with all execution layers, including failed interventions.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device(f"cuda:{gpu}") + began = time.perf_counter() + view, payload, metadata, world, atoms, families, ood, entities, panels = load_task(spec, device) + digest_before = model_digest(view.model) + write_json( + out / "run.json", + { + "spec": { + **spec, + "settings": settings, + "checkpoint_step": payload.get("step", payload["spec"].get("steps")), + }, + "checkpoint_sha256": file_hash(spec["checkpoint"]), + "initial_model_sha256": digest_before, + "world_sha256": file_hash(Path(spec["data"]) / "world.npz") + if view.large + else file_hash(Path(spec["checkpoint"]).parent / "world.npz"), + "job_type": "causal-intervention", + "pid": os.getpid(), + "gpu": gpu, + "gpu_name": torch.cuda.get_device_name(gpu), + "dtype": "BF16 native / FP32 Jacobian" if view.large else "FP32", + "parameters": sum(p.numel() for p in view.model.parameters()), + "vocab_size": len(view.embedding.weight), + "tags": ["bridge-workspace", spec["phase"], "no-training"], + "created_utc": utc(), + }, + ) + history, cursor = [], 0 + + def log(stage, metrics): + nonlocal cursor + history.append( + { + "step": cursor, + "metrics": metrics, + "wall_seconds": time.perf_counter() - began, + "checkpoint_training_step": payload.get("step", payload["spec"].get("steps", 0)), + } + ) + write_json(out / "learning.json", history) + write_json(out / "status.json", {"state": "running", "stage": stage, "step": cursor}) + print( + json.dumps( + { + "run": spec["name"], + "stage": stage, + "index": cursor, + "wall_seconds": history[-1]["wall_seconds"], + } + ), + flush=True, + ) + cursor += 1 + + log("loaded", {}) + pairs = select_pairs( + atoms, families, settings["selection_seed"], settings["prefixes_per_family"], ood=ood + ) + groups, q = pairs["groups"], pairs["queries"] + used_first = set(groups[:, 5]) | set(groups[:, 6]) + calibration = np.asarray([i for i in range(len(atoms)) if i not in used_first]) + calibration = sorted(calibration, key=lambda i: _rank(settings["calibration_seed"], i))[ + : settings["calibration_prompts"] + ] + sender = 1 if view.large else 3 + cp = prefixes(atoms[calibration], view.large, metadata) + tensors = torch.as_tensor(cp, device=device) + jacobians = average_prefix_jacobian(view, tensors, sender, chunk=settings["jacobian_chunk"]) + torch.save( + {"jacobians": jacobians.cpu(), "calibration_atomic_indices": calibration, "prefixes": cp}, + out / "lens.pt", + ) + log("jacobian_lens", {"calibration_prompts": len(cp), "executed_layers": len(view.blocks)}) + trace = trace_in_batches( + view, + prefixes(groups[:, :3], view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + donor_facts = np.column_stack((groups[:, 3], groups[:, 1], groups[:, 4])) + donor_states = trace_in_batches( + view, + prefixes(donor_facts, view.large, metadata), + sender, + settings["batch_size"], + view.large, + )[0] + rows = ( + np.column_stack((groups[q[:, 0], 0], groups[q[:, 0], 1], q[:, 1], q[:, 2])) + if view.large + else np.column_stack( + (groups[q[:, 0], 0], groups[q[:, 0], 1], groups[q[:, 0], 2], q[:, 1], q[:, 2]) + ) + ) + tokens = prompts(rows, view.large, metadata) + training_masks = query_training_masks(world, payload, groups, q, view.large) + # Fix a native panel per stratum without consulting any predictions. + native_rows, native_strata = [], [] + for name in ( + ("test_ii", "test_io", "test_oi", "test_oo") + if view.large + else ("familiar_test", "strict_test") + ): + selected = panels[name][: settings["native_per_stratum"]] + native_rows.append(selected) + native_strata.extend([name] * len(selected)) + native_rows, native_strata = np.concatenate(native_rows), np.asarray(native_strata) + lookup = {(int(h), int(r)): (int(t), i) for i, (h, r, t) in enumerate(atoms)} + native_facts = np.asarray([(h, r, lookup[int(h), int(r)][0]) for h, r in native_rows[:, :2]]) + unique_bridges, bridge_counts = np.unique(native_facts[:, 2], return_counts=True) + fixed_entity = int(unique_bridges[bridge_counts.argmax()]) + fixed_target = native_facts[:, 2] == fixed_entity + ntokens = prompts(native_rows, view.large, metadata) + ntrace = trace_in_batches( + view, + prefixes(native_facts, view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + all_needed = set(groups[:, 5]) | set(groups[:, 6]) | set(q[:, 4]) | set(q[:, 5]) + for row, fact in zip(native_rows, native_facts, strict=True): + r2 = row[2] if view.large else row[3] + all_needed.add(lookup[int(fact[0]), int(fact[1])][1]) + all_needed.add(lookup[int(fact[2]), int(r2)][1]) + needed_ids = np.asarray(sorted(all_needed)) + needed = atoms[needed_ids] + atrace = trace_in_batches( + view, prefixes(needed, view.large, metadata), sender, settings["batch_size"], view.large + ) + torch.save( + { + "recipient": tuple(a.cpu() for a in trace), + "donor_states": donor_states.cpu(), + "native": tuple(a.cpu() for a in ntrace), + "atomic": tuple(a.cpu() for a in atrace), + }, + out / "prefix-traces.pt", + ) + atomic = generate( + view, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + metadata, + settings["batch_size"], + ) + atomic_ok = atomic["generated"][:, 0] == needed[:, -1] + metadata["entity_offset"] + atomic_correct = dict(zip(needed_ids, atomic_ok, strict=True)) + prereq = np.asarray( + [ + all(atomic_correct[int(i)] for i in (groups[g, 5], groups[g, 6], second, cf_second)) + for g, _, _, _, second, cf_second in q + ] + ) + np.savez_compressed( + out / "selection.npz", + **{k: v for k, v in pairs.items() if k != "coverage"}, + rows=rows, + native_rows=native_rows, + native_strata=native_strata, + fixed_entity=np.asarray(fixed_entity), + fixed_entity_target=fixed_target, + **training_masks, + prerequisite_correct=prereq, + needed_atomic_indices=needed_ids, + **{"atomic_" + k: v for k, v in atomic.items()}, + ) + write_json(out / "coverage.json", pairs["coverage"]) + # Independent native implementation equivalence and prefix-causality audit. + audit_tokens = torch.as_tensor(tokens[: min(8, len(tokens))], device=device) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): + native = view.model( + audit_tokens, + positions=torch.full((len(audit_tokens), 1), audit_tokens.shape[1] - 1, device=device), + )[:, 0].float() + traced = view.logits(audit_tokens).float() + _, full_trace = view.hidden(audit_tokens, sender=sender, capture=True) + causal_error = float( + (full_trace[0].float() - trace[0][:, q[: len(audit_tokens), 0]]).abs().max() + ) + torch.testing.assert_close( + full_trace[0].float(), + trace[0][:, q[: len(audit_tokens), 0]], + atol=0.05 if view.large else 2e-5, + rtol=0.005 if view.large else 2e-5, + ) + torch.testing.assert_close( + native, traced, atol=0.05 if view.large else 1e-5, rtol=0.005 if view.large else 1e-5 + ) + if not torch.equal(native.argmax(-1), traced.argmax(-1)): + raise AssertionError("Native/traced greedy answers differ") + summary = {} + + def measure( + family, + condition, + layer, + input_tokens, + target, + cf_target, + strata, + delta=None, + query_groups=None, + ): + result = generate( + view, + input_tokens, + target, + cf_target, + metadata, + settings["batch_size"], + layer=layer if delta is not None else None, + sender=sender, + delta=delta, + ) + np.savez_compressed(out / f"{family}-{condition}-l{layer:02d}.npz", **result) + metrics = summarize(result, target, cf_target, metadata, strata, query_groups) + if family == "swap" and prereq.any(): + metrics["prerequisites_correct"] = summarize( + {k: a[prereq] for k, a in result.items()}, + target[prereq], + cf_target[prereq], + metadata, + strata[prereq], + query_groups[prereq], + )["all"] + if family == "swap" and training_masks["both_queries_untrained"].any(): + mask = training_masks["both_queries_untrained"] + metrics["both_queries_untrained"] = summarize( + {k: a[mask] for k, a in result.items()}, + target[mask], + cf_target[mask], + metadata, + strata[mask], + query_groups[mask], + )["all"] + if family == "native" and (condition.startswith("fixed_entity") or condition == "baseline"): + for label, mask in ( + ("fixed_entity_target", fixed_target), + ("fixed_entity_unrelated", ~fixed_target), + ): + if mask.any(): + metrics[label] = summarize( + {k: a[mask] for k, a in result.items()}, + target[mask], + cf_target[mask], + metadata, + strata[mask], + )["all"] + summary[f"{family}/{condition}/{layer}"] = metrics + write_json(out / "summary.json", summary) + log(f"{family}-{condition}-l{layer}", {family: {condition: {f"layer_{layer}": metrics}}}) + + measure("swap", "baseline", -1, tokens, q[:, 2], q[:, 3], pairs["strata"], query_groups=q[:, 0]) + measure( + "native", "baseline", -1, ntokens, native_rows[:, -1], native_rows[:, -1], native_strata + ) + measure( + "atomic", + "baseline", + -1, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + np.full(len(needed), "needed_atoms"), + ) + states, attentions, mlps = trace + rng = torch.Generator(device=device).manual_seed(settings["rotation_seed"]) + rotation, _ = torch.linalg.qr(torch.randn(view.width, view.width, device=device, generator=rng)) + swap_errors, restore_errors = [], [] + diagnostics = [] + axis_families = settings.get("axis_families", ["prefix_jacobian"]) + if not set(axis_families) <= {"prefix_jacobian", "input_embedding"}: + raise ValueError("Unknown direction family") + for layer, jacobian, axis_family in ( + (layer, j, family) for layer, j in enumerate(jacobians) for family in axis_families + ): + suffix = "_embedding" if axis_family == "input_embedding" else "" + directions = F.normalize( + view.embedding.weight[torch.as_tensor(entities, device=device)].float() + @ (torch.eye(view.width, device=device) if suffix else jacobian), + dim=-1, + ) + index = {int(e): i for i, e in enumerate(entities)} + source = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 2]]] + dest = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 4]]] + basis = torch.stack((source, dest), dim=-1) + swapped = swap_coordinates(states[layer], basis) + restored = swap_coordinates(swapped, basis) + swap_errors.append(float((restored - states[layer]).abs().max())) + random_basis = rotation[None] @ basis + swap_delta = swapped - states[layer] + torch.save( + { + "basis": basis.cpu(), + "rotation": rotation.cpu(), + "swap_delta": swap_delta.cpu(), + "axis_family": axis_family, + }, + out / f"patch-{axis_family}-l{layer:02d}.pt", + ) + deltas = { + "swap": swap_delta, + "swap_x2": 2 * swap_delta, + "random_swap": match_norm( + swap_coordinates(states[layer], random_basis) - states[layer], swap_delta + ), + "full_prefix": donor_states[layer] - states[layer], + "swap_back": restored - states[layer], + } + for condition in SWAPS: + measure( + "swap", + condition + suffix, + layer, + tokens, + q[:, 2], + q[:, 3], + pairs["strata"], + deltas[condition][q[:, 0]], + q[:, 0], + ) + native_direction = directions[ + [index[int(b + metadata["entity_offset"])] for b in native_facts[:, 2]] + ] + native_state, native_attention, native_mlp = (a[layer] for a in ntrace) + fixed_direction = directions[index[fixed_entity + metadata["entity_offset"]]][ + None + ].expand_as(native_direction) + fixed_mlp = projection(native_mlp, fixed_direction) + removed_mlp = projection(native_mlp, native_direction) + # All sublayers still execute. Only the selected sender's semantic component + # is subtracted from the actual local update at the boundary. + local_restore = native_state - removed_mlp + removed_mlp + restore_errors.append(float((local_restore - native_state).abs().max())) + erasures = { + "erase_state": -projection(native_state, native_direction), + "erase_mlp": -removed_mlp, + "erase_attention": -projection(native_attention, native_direction), + "random_state": match_norm( + -projection(native_state, native_direction @ rotation.T), + -projection(native_state, native_direction), + ), + "random_mlp": match_norm( + -projection(native_mlp, native_direction @ rotation.T), -removed_mlp + ), + "random_attention": match_norm( + -projection(native_attention, native_direction @ rotation.T), + -projection(native_attention, native_direction), + ), + "restore_mlp": local_restore - native_state, + "fixed_entity_mlp": -fixed_mlp, + "fixed_entity_random_mlp": match_norm( + -projection(native_mlp, fixed_direction @ rotation.T), + -fixed_mlp, + ), + } + for condition in ERASURES: + measure( + "native", + condition + suffix, + layer, + ntokens, + native_rows[:, -1], + native_rows[:, -1], + native_strata, + erasures[condition], + ) + # Relevant single-hop facts are scored under exactly the same local deletion. + adirection = directions[[index[int(b + metadata["entity_offset"])] for b in needed[:, 2]]] + atomic_delta = -projection(atrace[2][layer], adirection) + measure( + "atomic", + "erase_mlp" + suffix, + layer, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + np.full(len(needed), "needed_atoms"), + atomic_delta, + ) + with torch.no_grad(): + raw = F.linear(view.norm(states[layer]), view.embedding.weight).argmax(-1) + lens = F.linear(view.norm(states[layer] @ jacobian.T), view.embedding.weight).argmax(-1) + diagnostics.append( + { + "layer": layer, + "axis_family": axis_family, + "native_bridge_readout_accuracy": float( + ( + raw + == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) + ) + .float() + .mean() + ), + "prefix_jacobian_bridge_readout_accuracy": float( + ( + lens + == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) + ) + .float() + .mean() + ), + "swap_norm_mean": float(swap_delta.norm(dim=-1).mean()), + "native_mlp_removed_norm_mean": float(removed_mlp.norm(dim=-1).mean()), + } + ) + digest_after = model_digest(view.model) + if digest_before != digest_after or any(p.grad is not None for p in view.model.parameters()): + raise AssertionError("Intervention changed model parameters or accumulated gradients") + write_json( + out / "implementation-audit.json", + { + "parameters_unchanged": True, + "native_tracer_max_logit_error": float((native - traced).abs().max()), + "prefix_causal_state_max_error": causal_error, + "swap_inverse_max_errors": swap_errors, + "mlp_restore_max_errors": restore_errors, + "n_needed_atomic_facts": len(needed), + "needed_atomic_answer_accuracy": float(atomic_ok.mean()), + "swap_prerequisite_query_coverage": float(prereq.mean()), + "scoring": ( + "greedy feedback, original/counterfactual answer plus termination; " + "query and first-fact denominators separate" + ), + }, + ) + write_json(out / "diagnostics.json", diagnostics) + log("complete", {"complete": {"evaluations": len(summary)}}) + write_json( + out / "interventions-complete.json", + { + "finished_utc": utc(), + "evaluations": len(summary), + "model_sha256": digest_after, + "wall_seconds": time.perf_counter() - began, + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device), + "new_training_updates": 0, + }, + ) + write_json(out / "status.json", {"state": "awaiting_reload_audit", "step": cursor - 1}) + + +def audit_run(out, gpu): + """Reload in an independent process and reproduce fixed raw prediction subsets.""" + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + metadata_run = json.loads((out / "run.json").read_text()) + spec = metadata_run["spec"] + settings = spec["settings"] + view, _, metadata, _, atoms, _, _, entities, _ = load_task(spec, f"cuda:{gpu}") + assert model_digest(view.model) == metadata_run["initial_model_sha256"] + assert os.getpid() != metadata_run["pid"], "Reload must use a separate process" + selection = dict(np.load(out / "selection.npz")) + groups, queries = selection["groups"], selection["queries"] + jacobians = torch.load(out / "lens.pt", map_location=view.device, weights_only=False)[ + "jacobians" + ] + sender = 1 if view.large else 3 + trace = trace_in_batches( + view, + prefixes(groups[:, :3], view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + states = trace[0] + native_rows = selection["native_rows"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + facts = np.asarray([(h, r, lookup[int(h), int(r)]) for h, r in native_rows[:, :2]]) + ntrace = trace_in_batches( + view, prefixes(facts, view.large, metadata), sender, settings["batch_size"], view.large + ) + swap_indices = np.unique(np.linspace(0, len(queries) - 1, min(32, len(queries)), dtype=int)) + native_indices = np.unique( + np.linspace(0, len(native_rows) - 1, min(32, len(native_rows)), dtype=int) + ) + summary = json.loads((out / "summary.json").read_text()) + comparisons, max_logp_error, identity_controls = [], 0.0, [] + + def check(family, condition, layer, indices, rows, target, cf, delta=None): + nonlocal max_logp_error + + # Baseline is independently executed through the model's own forward. + class NativeView(ModelView): + def logits(self, tokens, **_): + positions = torch.full((len(tokens), 1), tokens.shape[1] - 1, device=self.device) + return self.model(tokens, positions=positions)[:, 0] + + actual = generate( + NativeView(view.model) if condition == "baseline" else view, + prompts(rows, view.large, metadata), + target, + cf, + metadata, + settings["batch_size"], + layer=layer if delta is not None else None, + sender=sender, + delta=delta, + ) + # Preserve original batch shapes: compacting selected rows changes BF16 + # GEMM rounding. Select the audit subset only after the full generation. + actual = {key: value[indices] for key, value in actual.items()} + expected = dict(np.load(out / f"{family}-{condition}-l{layer:02d}.npz")) + if not np.array_equal(actual["generated"], expected["generated"][indices]): + raise AssertionError(f"Reload generation mismatch: {family}/{condition}/{layer}") + for key in ("original_logp", "cf_logp"): + error = float(np.max(np.abs(actual[key] - expected[key][indices]))) + max_logp_error = max(max_logp_error, error) + np.testing.assert_allclose( + actual[key], + expected[key][indices], + atol=0.04 if view.large else 3e-5, + rtol=0.002 if view.large else 2e-5, + ) + comparisons.append( + {"family": family, "condition": condition, "layer": layer, "queries": len(indices)} + ) + + check("swap", "baseline", -1, swap_indices, selection["rows"], queries[:, 2], queries[:, 3]) + check( + "native", + "baseline", + -1, + native_indices, + native_rows, + native_rows[:, -1], + native_rows[:, -1], + ) + entity_index = {int(e): i for i, e in enumerate(entities)} + for layer, jacobian in enumerate(jacobians): + for axis_family in settings.get("axis_families", ["prefix_jacobian"]): + suffix = "_embedding" if axis_family == "input_embedding" else "" + directions = F.normalize( + view.embedding.weight[torch.as_tensor(entities, device=view.device)].float() + @ (torch.eye(view.width, device=view.device) if suffix else jacobian), + dim=-1, + ) + source = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 2]] + ] + dest = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 4]] + ] + delta = ( + swap_coordinates(states[layer], torch.stack((source, dest), dim=-1)) - states[layer] + ) + check( + "swap", + "swap" + suffix, + layer, + swap_indices, + selection["rows"], + queries[:, 2], + queries[:, 3], + delta[queries[:, 0]], + ) + native_direction = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in facts[:, 2]] + ] + native_delta = -projection(ntrace[2][layer], native_direction) + check( + "native", + "erase_mlp" + suffix, + layer, + native_indices, + native_rows, + native_rows[:, -1], + native_rows[:, -1], + native_delta, + ) + # Structural and numerical controls must retain native generation. + for family, condition in ( + ("swap", "swap_back" + suffix), + ("native", "restore_mlp" + suffix), + ): + raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] + baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] + identity_controls.append( + { + "family": family, + "condition": condition, + "layer": layer, + **control_observation(raw, baseline), + } + ) + if layer == len(view.blocks) - 1: + for key in summary: + family, condition, occurrence = key.split("/") + if int(occurrence) != layer or family == "atomic": + continue + raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] + baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] + assert np.array_equal(raw, baseline), ( + key, + "final sender must not affect later positions", + ) + assert model_digest(view.model) == metadata_run["initial_model_sha256"] + previous = out / "implementation-audit.json" + if not previous.exists() and (out / "audit.json").exists(): + previous.write_bytes((out / "audit.json").read_bytes()) + write_json( + out / "audit.json", + { + "independent_process": True, + "pid": os.getpid(), + "gpu": gpu, + "finished_utc": utc(), + "parameters_unchanged": True, + "generations_exact": True, + "identity_controls_exact": all(c["exact"] for c in identity_controls), + "identity_control_observations": identity_controls, + "scope": ( + "Fixed subset reload predictions exact; numerical inverse/restore " + "outcomes recorded separately" + ), + "max_log_probability_error": max_logp_error, + "evaluations": comparisons, + "implementation_audit_sha256": file_hash(previous), + "audit_source_sha256": file_hash(__file__), + }, + ) + if (out / "interventions-complete.json").exists(): + complete = json.loads((out / "interventions-complete.json").read_text()) + complete["independently_reloaded"] = True + complete["audit_finished_utc"] = utc() + write_json(out / "complete.json", complete) + write_json( + out / "status.json", + { + "state": "complete", + "independently_reloaded": True, + "step": json.loads((out / "learning.json").read_text())[-1]["step"], + }, + ) + print( + json.dumps( + { + "run": out.name, + "independent_reload": "passed", + "evaluations": len(comparisons), + "max_log_probability_error": max_logp_error, + } + ), + flush=True, + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/capacity_controls.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/capacity_controls.py new file mode 100644 index 0000000000000000000000000000000000000000..3806e6b81fda1ae9bc25fd74e38f846ddd3a456d --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/capacity_controls.py @@ -0,0 +1,64 @@ +"""Controls separating knowledge load, derived supervision, and serial recall.""" + +from __future__ import annotations + +import numpy as np + +from .capacity_scaling import DIGIT, EOS, TYPE_B + + +def training_indices(world, spec, epoch): + """Keep the historical mixed stream exactly, or replace derived examples. + + Replay preserves the mixed stream's batch sizes/updates and each original + atomic slot. Extra slots carry balanced atomic replay, never held-out labels. + """ + atoms = len(world["atomic"]) + mixed = atoms + len(world["train_composition"]) + mode = spec.get("training_mode", "mixed") + if mode not in {"mixed", "atomic", "atomic_replay"}: + raise ValueError(mode) + n = atoms if mode == "atomic" else mixed + rng = np.random.default_rng(np.random.SeedSequence([spec["stream_seed"], epoch])) + order = rng.permutation(n) + if mode == "atomic_replay": + replay_rng = np.random.default_rng( + np.random.SeedSequence([spec["stream_seed"], epoch, 771]) + ) + replacements = np.resize(replay_rng.permutation(atoms), mixed - atoms) + source = np.concatenate((np.arange(atoms), replacements)) + return source[order] + return order + + +def decode_bridge(predictions): + """Reject malformed/out-of-domain predictions instead of oracle repairing.""" + p = np.asarray(predictions) + d = p[:, 1:5] - DIGIT + valid = ( + (p[:, 0] == TYPE_B) + & (p[:, 5] == EOS) + & ((d >= 0) & (d < 16)).all(1) + & (d[:, :2] == 0).all(1) + ) + values = (np.clip(d, 0, 15) * np.array([4096, 256, 16, 1])).sum(1) + return np.where(valid, values, 0), valid + + +def first_queries(compositions): + rows = np.zeros_like(compositions) + rows[:, 0] = 0 + rows[:, 1:3] = compositions[:, 1:3] + rows[:, 3] = -1 + rows[:, 5:] = -1 + return rows + + +def second_queries(compositions, bridges): + rows = np.zeros_like(compositions) + rows[:, 0] = 1 + rows[:, 1] = bridges + rows[:, 2] = compositions[:, 3] + rows[:, 3] = -1 + rows[:, 5:] = -1 + return rows diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/capacity_scaling.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/capacity_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c152e8710de107c8fb2f4ba2275cdea5cbdcf3 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/capacity_scaling.py @@ -0,0 +1,193 @@ +"""Fixed-vocabulary random worlds for the capacity development experiment. + +Knowledge is in independent A->B and B->C maps. Composition labels are derived, +never counted as independent information. This is a QA adaptation, not bioS. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +PAD, BOS, EOS, ANSWER = 0, 1, 2, 3 +TYPE_A, TYPE_B, TYPE_C = 4, 5, 6 +DIGIT, REL_A, REL_B = 7, 23, 27 +VOCAB, CONTEXT, ANSWER_LENGTH = 31, 14, 6 + + +def digest_arrays(arrays): + h = hashlib.sha256() + for key, value in sorted(arrays.items()): + value = np.ascontiguousarray(value) + h.update(key.encode()) + h.update(str(value.shape).encode()) + h.update(str(value.dtype).encode()) + h.update(value.tobytes()) + return h.hexdigest() + + +def generate_world(spec): + """Rows: kind, subject, r1, r2, answer, necessary_atom_1, necessary_atom_2. + + The maximum address universe and all maps are generated before choosing a + load. Prefix worlds are nested. Background controls keep the entire low-load + composition training/evaluation sets, including necessary facts, unchanged. + """ + seed, heads = spec["world_seed"], spec["heads_n"] + maximum, values, relations = spec["max_heads"], spec["values_n"], spec["relations"] + if not (1 <= heads <= maximum <= 65536 and values == 256 and relations == 4): + raise ValueError("This version requires 256 values, four relations, <=65536 heads") + support_heads = spec.get("support_heads_n", heads) + if not 1 <= support_heads <= heads: + raise ValueError("Invalid support prefix") + + def rng(part): + return np.random.default_rng(np.random.SeedSequence([seed, part])) + + first = rng(0).integers(values, size=(maximum, relations), dtype=np.int64)[:heads] + second = rng(1).integers(values, size=(values, relations), dtype=np.int64) + eligible_first = rng(2).random((maximum, relations))[:support_heads] < 0.75 + eligible_second = rng(3).random((values, relations)) < 0.75 + first_n = heads * relations + h, r = np.indices(first.shape).reshape(2, -1) + atoms_a = np.column_stack( + ( + np.zeros(first_n, dtype=int), + h, + r, + -np.ones(first_n, dtype=int), + first.ravel(), + np.arange(first_n), + -np.ones(first_n, dtype=int), + ) + ) + b, r2 = np.indices(second.shape).reshape(2, -1) + second_n = second.size + atoms_b = np.column_stack( + ( + np.ones(second_n, dtype=int), + b, + r2, + -np.ones(second_n, dtype=int), + second.ravel(), + first_n + np.arange(second_n), + -np.ones(second_n, dtype=int), + ) + ) + atoms = np.concatenate((atoms_a, atoms_b)).astype(np.int64) + h, r1, r2 = np.indices((support_heads, relations, relations)).reshape(3, -1) + bridge = first[h, r1] + a_id, b_id = h * relations + r1, first_n + bridge * relations + r2 + comps = np.column_stack((np.full(len(h), 2), h, r1, r2, second[bridge, r2], a_id, b_id)).astype( + np.int64 + ) + train_mask = ( + eligible_first[h, r1] & eligible_second[bridge, r2] & (((r2 - h - r1) % relations) < 2) + ) + trained = np.zeros(len(atoms), dtype=bool) + trained[comps[train_mask, 5:].ravel()] = True + seen1, seen2 = trained[a_id], trained[b_id] + world = { + "first": first, + "second": second, + "atomic": atoms, + "train_composition": comps[train_mask], + } + for name, mask in { + "II": seen1 & seen2, + "IO": seen1 & ~seen2, + "OI": ~seen1 & seen2, + "OO": ~seen1 & ~seen2, + }.items(): + ids = np.flatnonzero(mask & ~train_mask) + # Selection stream does not depend on load in fixed-target controls. + take = rng(20 + ["II", "IO", "OI", "OO"].index(name)).permutation(ids) + world[name] = comps[take[: spec["evaluation_per_pool"]]] + world[name + "_population"] = np.array([len(ids)], dtype=np.int64) + panel_rng = rng(30) + for name in ("atomic", "train_composition"): + ids = panel_rng.permutation(len(world[name]))[: spec["evaluation_per_pool"]] + world[name + "_panel"] = world[name][ids] + world["role_counts"] = np.stack( + [np.bincount(world["train_composition"][:, col], minlength=len(atoms)) for col in (5, 6)] + ) + return world + + +def digits(values): + values = np.asarray(values, dtype=np.int64) + return DIGIT + ((values[:, None] >> np.array([12, 8, 4, 0])) & 15) + + +def pack(rows): + """Right padding is causally downstream; only answer+EOS is supervised.""" + rows = np.asarray(rows, dtype=np.int64) + x = np.zeros((len(rows), CONTEXT), dtype=np.int64) + composition = rows[:, 0] == 2 + prefix_length = np.where(composition, 9, 8) + x[:, 0] = BOS + x[:, 1] = np.where(rows[:, 0] == 1, TYPE_B, TYPE_A) + x[:, 2:6] = digits(rows[:, 1]) + x[:, 6] = np.where(rows[:, 0] == 1, REL_B, REL_A) + rows[:, 2] + x[:, 7] = np.where(composition, REL_B + rows[:, 3], ANSWER) + x[composition, 8] = ANSWER + labels = np.column_stack( + (np.where(rows[:, 0] == 0, TYPE_B, TYPE_C), digits(rows[:, 4]), np.full(len(rows), EOS)) + ) + positions = prefix_length[:, None] - 1 + np.arange(ANSWER_LENGTH) + x[np.arange(len(rows))[:, None], positions[:, 1:]] = labels[:, :-1] + return x, positions, labels + + +def information_ledger(world, parameters, knowledge_nll=None): + facts = len(world["atomic"]) + bits = facts * math.log2(world["second"].shape[0]) + result = { + "independent_facts": facts, + "world_bits": bits, + "parameters": parameters, + "adjusted_parameters": parameters, + "data_bits_per_parameter": bits / parameters, + "composition_independent_bits": 0, + } + if knowledge_nll is not None: + learned = bits - facts * knowledge_nll / math.log(2) + result.update(learned_bits_raw=learned, learned_bits_per_parameter=learned / parameters) + return result + + +def model_parameter_count(width, layers=2): + # Tied token/output weights, learned positions, two biased projections each + # in attention/MLP, per-block and final LayerNorms. + return (VOCAB + CONTEXT) * width + layers * (12 * width**2 + 13 * width) + 2 * width + + +def prerequisite_pass(metrics, thresholds): + return all( + metrics[key]["accuracy"] >= thresholds[key] for key in ("atomic", "train_composition", "II") + ) + + +def grid_capacity(points, metric, threshold, atomic_threshold): + """Report sampled successes and censoring, never silently assume monotonicity.""" + points = sorted(points, key=lambda p: p["bits"]) + passed = [p["atomic"] >= atomic_threshold and p[metric] >= threshold for p in points] + reversals = any(passed[i] and not passed[i - 1] for i in range(1, len(passed))) + successes = [p["bits"] for p, ok in zip(points, passed, strict=True) if ok] + lower = max(successes) if successes else None + failures_above = [ + p["bits"] + for p, ok in zip(points, passed, strict=True) + if not ok and (lower is None or p["bits"] > lower) + ] + return { + "largest_observed_passing_bits": lower, + "next_observed_failing_bits": min(failures_above) if failures_above else None, + "nonmonotonic_grid": reversals, + "interpretation": "sampled_grid_only; bracket requires monotone interpolation", + "censoring": "below_grid" + if lower is None + else ("above_grid" if not failures_above else "bracketed_on_grid"), + } diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/cli.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..1aec4627fdf91a196893b3a6d47c8188da55d55b --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/cli.py @@ -0,0 +1,32 @@ +"""Command-line interface for the deterministic matrix illustration.""" + +import argparse +import json +from pathlib import Path + +from .experiments import run_minimal_example + + +def main(argv: list[str] | None = None) -> int: + """Print the analytical report as JSON and optionally save a copy.""" + parser = argparse.ArgumentParser(description="Run the analytical low-rank editability example.") + parser.add_argument( + "--rank", type=int, default=1, help="total rank budget: 0, 1 (default), or 2" + ) + parser.add_argument( + "--atol", type=float, default=1e-10, help="positive absolute singular-value tolerance" + ) + parser.add_argument( + "--output", type=Path, help="also save JSON to this path (creates parent directories)" + ) + args = parser.parse_args(argv) + try: + report = run_minimal_example(rank=args.rank, atol=args.atol) + serialized = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(serialized + "\n", encoding="utf-8") + except (ValueError, OSError) as exc: + parser.error(str(exc)) + print(serialized) + return 0 diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/composition_curves.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/composition_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..13009dcfa856d01722da32842dcc3a7fe078a635 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/composition_curves.py @@ -0,0 +1,477 @@ +"""Distinct composition support and knowledge-load curves on random relation graphs. + +The graph, answer/EOS objective, GPT blocks and optimizer reuse the previously +successful Wang et al. adaptation. A fixed maximum entity vocabulary keeps +parameters identical across loads. Development and confirmation worlds differ. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import ( + EpochStream, + GraphStep, + SmallGPT, + evaluate_rows, + make_optimizer, + pack_rows, + two_calls, + utc, + write_json, +) +from .grok_depth_data import audit_world, build_world + + +def sha256(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def array_hash(arrays): + digest = hashlib.sha256() + for name, value in sorted(arrays.items()): + digest.update(name.encode()) + digest.update(np.asarray(value.shape, dtype=" len(order): + raise ValueError("Distinct support request exceeds the reserved training pool") + arrays = { + key: base[key].copy() + for key in ("atomic", "id_atomic", "ood_atomic", "test_composite", "ood_composite") + } + eligible = base["unused_composite"][order].copy() + for rows in [*arrays.values(), eligible]: + rows[:, 1:-1] += maximum - n + identity = array_hash({**arrays, "eligible": eligible}) + arrays["train_composite"] = eligible[:requested].copy() + lookup = np.full((maximum, spec["relations"]), -1, dtype=np.int64) + atomic = arrays["atomic"] + lookup[atomic[:, 0] - 2, atomic[:, 1] - maximum - 2] = np.arange(len(atomic)) + first, second = constituent_indices(arrays["train_composite"], atomic, lookup, maximum) + first_counts = np.bincount(first, minlength=len(atomic)) + second_counts = np.bincount(second, minlength=len(atomic)) + role = {} + for name in ("test_composite", "ood_composite"): + one, two = constituent_indices(arrays[name], atomic, lookup, maximum) + role[name] = { + "n": len(one), + "both_facts_seen_in_required_roles": ( + float(((first_counts[one] > 0) & (second_counts[two] > 0)).mean()) + if len(one) + else None + ), + } + panel_rng = np.random.default_rng(np.random.SeedSequence([spec["world_seed"], n, 960602])) + panels = {} + for key, name in [ + ("atomic", "atomic"), + ("id_atomic", "atomic_id"), + ("ood_atomic", "atomic_ood"), + ("test_composite", "II"), + ("ood_composite", "OO"), + ]: + rows = arrays[key] + ids = panel_rng.choice(len(rows), min(spec["evaluation_size"], len(rows)), replace=False) + panels[name] = rows[ids].copy() + panels["train_composition"] = arrays["train_composite"][: spec["evaluation_size"]].copy() + metadata = { + "world_seed": spec["world_seed"], + "entities": n, + "max_entities": maximum, + "relations": spec["relations"], + "degree": spec["degree"], + "vocab_size": maximum + spec["relations"] + 2, + "atomic_examples": len(atomic), + "id_atomic_examples": len(arrays["id_atomic"]), + "composition_examples": requested, + "eligible_compositions": len(eligible), + "phi_actual": requested / len(arrays["id_atomic"]), + "world_sha256": identity, + "dataset_sha256": array_hash(arrays), + "knowledge_bits": len(atomic) * math.log2(n), + "entropy_condition": "independent uniform tails, conditional on head/relation keys", + "composition_additional_independent_bits": 0, + "role_coverage": role, + "panel_counts": {key: len(value) for key, value in panels.items()}, + "full_counts": {key: len(value) for key, value in arrays.items()}, + "graph_source": base["metadata"]["source_url"], + "graph_source_commit": base["metadata"]["source_commit"], + "graph_audit": base["metadata"]["dataset_sha256"], + } + return arrays, panels, metadata + + +def constituent_indices(rows, atomic, lookup, maximum): + first = lookup[rows[:, 0] - 2, rows[:, 1] - maximum - 2] + if np.any(first < 0): + raise ValueError("Unknown first-hop fact") + second = lookup[atomic[first, 2] - 2, rows[:, 2] - maximum - 2] + if np.any(second < 0) or not np.array_equal(atomic[second, 2], rows[:, -1]): + raise ValueError("Composition truth differs from graph traversal") + return first, second + + +def budget_nodes(spec, total): + matched = math.ceil(spec["target_exposures"] * total / spec["batch_size"]) + compute = spec["compute_steps"] + end = spec.get("fixed_steps", max(compute, matched)) + nodes = {0, end, *range(2000, min(end, 128000) + 1, 2000)} + nodes.update(s for s in (256, 512, 1000, compute, matched) if s <= end) + nodes.update(range(192000, end, 64000)) + return sorted(nodes), {"compute": compute, "exposure": matched, "end": end} + + +def construct(spec, device): + torch.manual_seed(spec["initialization"]) + cfg = ModelConfig( + vocab_size=spec["max_entities"] + spec["relations"] + 2, + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + return SmallGPT(cfg, dropout=spec["dropout"]).to(device), cfg + + +def model_hash(model): + digest = hashlib.sha256() + for name, tensor in model.state_dict().items(): + digest.update(name.encode()) + digest.update(tensor.detach().cpu().contiguous().numpy().tobytes()) + return digest.hexdigest() + + +def measure(model, panels, device): + metrics, predictions = {}, {} + for name, rows in panels.items(): + metrics[name], values = evaluate_rows(model, rows, device, batch_size=512) + if len(rows): + metrics[name]["answer_nll"] = float(values["nll"][:, 0].mean()) + predictions.update({name + "_" + key: value for key, value in values.items()}) + return metrics, predictions + + +def train(spec, out, resume=False): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device("cuda:0") + torch.cuda.set_device(device) + arrays, panels, data = prepare_world(spec) + model, cfg = construct(spec, device) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + packed = [pack_rows(arrays[key]) for key in ("atomic", "train_composite")] + table = tuple( + torch.as_tensor(np.concatenate([a, b]), device=device) for a, b in zip(*packed, strict=True) + ) + atomic_n, composition_n = data["atomic_examples"], data["composition_examples"] + total = atomic_n + composition_n + stream = EpochStream(total, spec["stream_seed"]) + nodes, budgets = budget_nodes(spec, total) + start, seconds = 0, 0.0 + counts = {"atomic": 0, "composition": 0} + initial_hash = model_hash(model) + if resume: + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if saved["spec"] != spec or saved["world_sha256"] != data["world_sha256"]: + raise ValueError("Resume identity mismatch") + model.load_state_dict(saved["model"]) + optimizer.load_state_dict(saved["optimizer"]) + lr = optimizer.param_groups[0]["lr"] + for group in optimizer.param_groups: + group["lr"] = lr + stream.load_state_dict(saved["stream"]) + counts, seconds, start = saved["counts"], saved["seconds"], saved["step"] + torch.set_rng_state(saved["cpu_rng"].cpu()) + torch.cuda.set_rng_state(saved["cuda_rng"].cpu()) + initial_hash = json.loads((out / "run.json").read_text())["initial_model_sha256"] + out.mkdir(parents=True, exist_ok=True) + metadata = { + "spec": spec, + "phase": spec["phase"], + "pid": os.getpid(), + "gpu": int(os.environ.get("PHYSICAL_GPU", 0)), + "gpu_name": torch.cuda.get_device_name(), + "parameters": sum(p.numel() for p in model.parameters()), + "initial_model_sha256": initial_hash, + "world_sha256": data["world_sha256"], + "dtype": "FP32 parameters/optimizer/forward; TF32 matmul", + "torch": torch.__version__, + "numpy": np.__version__, + "budgets": budgets, + "evaluation_nodes": nodes, + **data, + } + write_json(out / "run.json", metadata) + write_json(out / "data-audit.json", data) + np.savez_compressed(out / "world.npz", **arrays) + np.savez_compressed(out / "panels.npz", **panels) + t0 = time.perf_counter() + graph = GraphStep(model, optimizer, table, spec["batch_size"]) + capture = time.perf_counter() - t0 + per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) + history = json.loads((out / "learning.json").read_text()) if resume else [] + history = [record for record in history if record["step"] <= start] + begun = time.perf_counter() + + def checkpoint(step, loss=None): + metrics, predictions = measure(model, panels, device) + record = { + "step": step, + "utc": utc(), + "metrics": metrics, + "training_seconds": seconds, + "wall_seconds": time.perf_counter() - begun, + "capture_seconds": capture, + "examples": step * spec["batch_size"], + "atomic_examples_seen": counts["atomic"], + "composition_examples_seen": counts["composition"], + "atomic_epochs": counts["atomic"] / atomic_n, + "composition_epochs": counts["composition"] / composition_n if composition_n else 0, + "minimum_record_exposures": (step * spec["batch_size"]) // total, + "maximum_record_exposures": math.ceil(step * spec["batch_size"] / total), + "supervised_tokens": step * spec["batch_size"] * 2, + "executed_input_tokens": step * spec["batch_size"] * 4, + "estimated_matmul_training_flops": step * per_step, + "loss": loss, + "learning_rate": float(lr.detach()), + } + history.append(record) + write_json(out / "learning.json", history) + payload = { + "spec": spec, + "world_sha256": data["world_sha256"], + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "seconds": seconds, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(), + } + torch.save(payload, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in budgets.values(): + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step}.pt", + ) + np.savez_compressed(out / f"predictions-{step}.npz", **predictions) + status = { + "state": "trained" if step == budgets["end"] else "running", + "step": step, + "budget": budgets["end"], + "atomic": metrics["atomic"]["accuracy"], + "II": metrics["II"]["accuracy"], + "updated_utc": utc(), + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + + if not resume: + checkpoint(0) + for end in (node for node in nodes if node > start): + torch.cuda.synchronize() + t0 = time.perf_counter() + loss = None + step = start + while step < end: + length = min(256, end - step) + indices = stream.take(length * spec["batch_size"]).reshape(length, -1) + atom_count = int((indices < atomic_n).sum()) + counts["atomic"] += atom_count + counts["composition"] += indices.size - atom_count + gpu_indices = torch.as_tensor(indices, device=device) + for j in range(length): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + loss = graph(gpu_indices[j]) + step += length + torch.cuda.synchronize() + seconds += time.perf_counter() - t0 + value = float(loss.detach()) + if not math.isfinite(value): + raise FloatingPointError(f"Nonfinite loss at {end}") + checkpoint(end, value) + start = end + full_panels = { + "atomic": arrays["atomic"], + "atomic_id": arrays["id_atomic"], + "atomic_ood": arrays["ood_atomic"], + "II": arrays["test_composite"], + "OO": arrays["ood_composite"], + } + full, predictions = measure(model, full_panels, device) + full["external_two_calls"] = two_calls(model, panels["II"], device) + np.savez_compressed(out / "full-predictions.npz", **predictions) + write_json( + out / "complete.json", + { + "step": start, + "spec": spec, + "parameters": metadata["parameters"], + "training_seconds": seconds, + "wall_seconds": time.perf_counter() - begun, + "endpoint": history[-1], + "full_metrics": full, + "finished_utc": utc(), + }, + ) + + +def audit(spec, out): + """Reload both predeclared comparison checkpoints and independently recount.""" + out = Path(out) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + arrays, panels, data = prepare_world(spec) + recorded = dict(np.load(out / "world.npz")) + if array_hash(recorded) != data["dataset_sha256"]: + raise ValueError("Saved world differs from deterministic reconstruction") + meta = json.loads((out / "run.json").read_text()) + if meta["world_sha256"] != data["world_sha256"]: + raise ValueError("World identity mismatch") + history = json.loads((out / "learning.json").read_text()) + nodes, budgets = budget_nodes(spec, data["atomic_examples"] + data["composition_examples"]) + if [record["step"] for record in history] != nodes: + raise ValueError("Missing or reordered evaluation nodes") + model, cfg = construct(spec, "cuda:0") + if sum(p.numel() for p in model.parameters()) != meta["parameters"]: + raise ValueError("Parameter count mismatch") + per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) + for record in history: + examples = record["step"] * spec["batch_size"] + if record["examples"] != examples or examples != ( + record["atomic_examples_seen"] + record["composition_examples_seen"] + ): + raise ValueError("Exposure arithmetic mismatch") + if record["estimated_matmul_training_flops"] != record["step"] * per_step: + raise ValueError("Executed-shape FLOP mismatch") + reloaded = [] + for step in sorted(set(budgets.values()) & set(nodes)): + saved = torch.load(out / f"weights-{step}.pt", weights_only=False, map_location="cuda:0") + if saved["spec"] != spec or saved["step"] != step: + raise ValueError("Checkpoint identity mismatch") + model.load_state_dict(saved["model"]) + metrics, predictions = measure(model, panels, "cuda:0") + original = dict(np.load(out / f"predictions-{step}.npz")) + for key, values in predictions.items(): + if key.endswith("_nll"): + np.testing.assert_allclose(values, original[key], rtol=1e-5, atol=1e-6) + elif not np.array_equal(values, original[key]): + raise ValueError(f"Reloaded predictions changed: {step} {key}") + prior = next(record for record in history if record["step"] == step)["metrics"] + for name, metric in metrics.items(): + if metric["accuracy"] != prior[name]["accuracy"]: + raise ValueError("Metric recount mismatch") + reloaded.append(step) + full_panels = { + "atomic": arrays["atomic"], + "atomic_id": arrays["id_atomic"], + "atomic_ood": arrays["ood_atomic"], + "II": arrays["test_composite"], + "OO": arrays["ood_composite"], + } + full, predictions = measure(model, full_panels, "cuda:0") + original = dict(np.load(out / "full-predictions.npz")) + for key, value in predictions.items(): + np.testing.assert_allclose(value, original[key], rtol=1e-5, atol=1e-6) + full["external_two_calls"] = two_calls(model, panels["II"], "cuda:0") + write_json( + out / "audit.json", + {"passed": True, "reloaded_steps": reloaded, "full_metrics": full, "utc": utc()}, + ) + write_json(out / "status.json", {"state": "complete", "step": budgets["end"], "utc": utc()}) + + +def calibrated_choice(records, thresholds): + """Development-only success gate; prefer smaller registered model when both pass.""" + candidates = [] + for spec, metrics in records: + passed = all(metrics[key]["accuracy"] >= value for key, value in thresholds.items()) + if passed: + candidates.append(spec) + return min(candidates, key=lambda spec: spec["layers"]) if candidates else None + + +def confirmation_specs(config, selected): + specs = [] + for index, seed in enumerate(config["confirmation_worlds"]): + for phi in config["support_phi"]: + specs.append( + { + **selected, + "phase": "confirmation", + "world_seed": seed, + "initialization": config["initialization"] + index, + "stream_seed": config["stream_seed"] + index, + "name": f"support-w{index + 1}-phi{phi:g}", + "phi": phi, + "entities": config["base_spec"]["entities"], + } + ) + return specs + + +def anchors_pass(records, worlds, thresholds): + """Require exactly the registered independent worlds; no cherry-picked anchors.""" + observed = [spec["world_seed"] for spec, _ in records] + if len(observed) != len(worlds) or set(observed) != set(worlds): + return False + return all( + all(metrics[key]["accuracy"] >= threshold for key, threshold in thresholds.items()) + for _, metrics in records + ) + + +def load_specs(config, selected): + specs = [] + for index, seed in enumerate(config["confirmation_worlds"]): + for n in config["load_entities"][1:]: + specs.append( + { + **selected, + "phase": "confirmation", + "world_seed": seed, + "initialization": config["initialization"] + index, + "stream_seed": config["stream_seed"] + index, + "name": f"load-w{index + 1}-n{n}", + "phi": config["anchor_phi"], + "entities": n, + } + ) + return specs diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/curve_tracking.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/curve_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..526a40aecb32ed282e9de766f3162546d80403ac --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/curve_tracking.py @@ -0,0 +1,36 @@ +"""Retry transient W&B connection failures without changing scientific trajectories.""" + +import json +import time +import traceback +from datetime import datetime, timezone +from pathlib import Path + +from . import interface_tracking +from .experiment_tracking import write_json + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def main(): + import sys + + root = Path(sys.argv[sys.argv.index("--root") + 1]) + for attempt in range(1, 145): + try: + interface_tracking.main() + return + except Exception: + path = root / "tracking-retries.json" + history = json.loads(path.read_text()) if path.exists() else [] + history.append({"attempt": attempt, "utc": utc(), "error": traceback.format_exc()}) + write_json(path, history) + print(json.dumps({"tracking_retry": attempt, "utc": utc()}), flush=True) + time.sleep(min(60, 5 * attempt)) + raise RuntimeError("W&B retry budget exhausted; scientific artifacts remain intact") + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/depth_step.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/depth_step.py new file mode 100644 index 0000000000000000000000000000000000000000..8f828c9ccea5c225dd4fc257587afe3c0ff7c6bf --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/depth_step.py @@ -0,0 +1,669 @@ +"""Ordinary end-to-end GPT depth and optimization-time development experiment. + +The frozen random graph is shared across two-, three- and four-hop training. +Only terminal entities enter composition text; intermediate truth is used for +evaluation and audit. Existing experimental implementations remain unchanged. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_data import build_world as single_length_world +from .grok_loop_model import LoopGPT, flops +from .latent_scaling import model_digest +from .storage_composition import FullTokenStep, file_hash +from .storage_frontier import learning_rate + +BOS, EOS, PAD, ENTITY_OFFSET = 2, 1, 0, 3 +HOPS = (2, 3, 4) +TRAIN_SPLITS = ("atomic", "train_2", "train_3", "train_4") +EVALUATION_SPLITS = ("atomic",) + tuple( + f"{split}_{hop}" for hop in HOPS for split in ("train", "familiar", "strict") +) +DATA_DEFAULTS = { + "entities": 64, + "relations": 4, + "degree": 4, + "phi": 4.0, + "id_fraction": 0.75, + "id_test_fraction": 0.2, + "evaluation_size": 512, +} +SOURCE_FILES = [ + "src/llm_memory_editability/bios_model.py", + "src/llm_memory_editability/grok_depth.py", + "src/llm_memory_editability/grok_depth_data.py", + "src/llm_memory_editability/grok_loop_data.py", + "src/llm_memory_editability/grok_multihop_data.py", + "src/llm_memory_editability/grok_loop_model.py", + "src/llm_memory_editability/latent_scaling.py", + "src/llm_memory_editability/storage_composition.py", + "src/llm_memory_editability/storage_frontier.py", + "src/llm_memory_editability/text_pretrain.py", + "src/llm_memory_editability/depth_step.py", + "scripts/run_depth_step.py", + "tests/test_depth_step.py", +] + + +def data_digest(world): + digest = hashlib.sha256() + for name in EVALUATION_SPLITS: + rows = world[name] + digest.update(name.encode()) + digest.update(np.asarray(rows.shape, dtype="= relation_offset)): + raise ValueError("Invalid entity token: " + name) + if np.any( + (rows[:, 1:-1] < relation_offset) | (rows[:, 1:-1] >= relation_offset + relations) + ): + raise ValueError("Invalid relation token: " + name) + if len(set(map(tuple, rows[:, :-1]))) != len(rows): + raise ValueError("Duplicate complete query: " + name) + _, edges = truth_path_details(world, rows) + if name.startswith(("train_", "familiar_")) and not id_mask[edges].all(): + raise ValueError("Non-ID fact in familiar training/test: " + name) + if name.startswith("strict_") and id_mask[edges].any(): + raise ValueError("ID fact in strict composition: " + name) + counts[name] = len(rows) + if len(world["atomic"]) != entities * meta["degree"]: + raise ValueError("Atomic graph degree does not match the contract") + for hop in HOPS: + query_sets = [ + set(map(tuple, world[f"{split}_{hop}"][:, :-1])) + for split in ("train", "familiar", "strict") + ] + if any(query_sets[i] & query_sets[j] for i in range(3) for j in range(i)): + raise ValueError("Complete query leakage between length-specific splits") + trained_edges = set() + for hop in HOPS: + trained_edges.update(truth_path_details(world, world[f"train_{hop}"])[1].ravel()) + for hop in HOPS: + strict_edges = set(truth_path_details(world, world[f"strict_{hop}"])[1].ravel()) + if strict_edges & trained_edges: + raise ValueError("Strict facts participated in another length's composition training") + digest = data_digest(world) + if "dataset_sha256" in meta and meta["dataset_sha256"] != digest: + raise ValueError("Frozen dataset digest differs from actual arrays") + return { + "passed": True, + "counts": counts, + "dataset_sha256": digest, + "truth_edges_independently_traversed": True, + "complete_query_overlap": 0, + "all_strict_facts_absent_from_composition_training": True, + "cross_length_subpath_holdout": False, + } + + +def build_world(spec): + seed = spec.get("world_seed", spec.get("world")) + if seed is None: + raise ValueError("A fixed world_seed is required") + settings = {key: spec.get(key, value) for key, value in DATA_DEFAULTS.items()} + world, shared_atoms, shared_ids = {}, None, None + source_metadata = {} + for hop in HOPS: + original = single_length_world({"world_seed": seed, "hops": hop, **settings}) + # The historical graph reserves only PAD/EOS and uses entity offset 2. + # Shift every entity/relation token once to reserve the explicit BOS=2. + atoms = original["atomic"] + 1 + id_set = set(map(tuple, original["id_atomic"])) + id_mask = np.asarray([tuple(row) in id_set for row in original["atomic"]], dtype=bool) + if shared_atoms is None: + shared_atoms, shared_ids = atoms.copy(), id_mask.copy() + elif not np.array_equal(shared_atoms, atoms) or not np.array_equal(shared_ids, id_mask): + raise ValueError("Path lengths do not share identical graph and ID mask") + world[f"train_{hop}"] = original["train_composite"] + 1 + world[f"familiar_{hop}"] = original["test_full_composite"] + 1 + world[f"strict_{hop}"] = original["ood_composite"] + 1 + source_metadata[str(hop)] = original["metadata"] + world["atomic"] = shared_atoms + world["metadata"] = { + "world_seed": int(seed), + **settings, + "id_mask": shared_ids.tolist(), + "source_worlds": source_metadata, + "same_atomic_and_id_mask_all_lengths": True, + "source_entity_offset": 2, + "entity_offset": ENTITY_OFFSET, + "source_token_shift": 1, + "separator_token": ENTITY_OFFSET + settings["entities"] + settings["relations"], + "vocab_size": ENTITY_OFFSET + settings["entities"] + settings["relations"] + 1, + "evaluation_pools": "Complete test_full_composite and ood_composite", + "composition_supervision": "Terminal entity only; no intermediate entity", + "training_objective": "All nonpadding next tokens including EOS", + "holdout": "Complete queries held out within each length; not subpaths across lengths", + } + report = audit_world(world) + world["metadata"]["dataset_sha256"] = report["dataset_sha256"] + world["metadata"]["independent_audit"] = report + expected = spec.get("frozen_data_sha256") + if expected is not None and expected != report["dataset_sha256"]: + raise ValueError("Rebuilt data differ from the frozen specification") + return world + + +def construct(spec, device): + if spec.get("context", 9) < 9: + raise ValueError("Context must support four-hop answer and EOS") + config = ModelConfig( + vocab_size=ENTITY_OFFSET + spec.get("entities", 64) + spec.get("relations", 4) + 1, + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=spec.get("context", 9), + ) + if config.layers > 6: + raise ValueError("Canonical paired initialization is limited to six unique blocks") + torch.manual_seed(spec["initialization"]) + canonical = LoopGPT( + replace(config, layers=6), + repeats=1, + dropout=spec.get("dropout", 0.0), + initialization="scaled_effective", + ) + model = LoopGPT( + config, + repeats=spec["repeats"], + dropout=spec.get("dropout", 0.0), + initialization="scaled_effective", + ) + initial = canonical.state_dict() + state = {} + factor = math.sqrt(6 / (config.layers * spec["repeats"])) + for key in model.state_dict(): + value = initial[key].clone() + if key.endswith(("attention.proj.weight", "mlp.down.weight")): + value.mul_(factor) + state[key] = value + model.load_state_dict(state) + return model.to(device) + + +def prompt_rows(rows, separator=71): + rows = np.asarray(rows, dtype=np.int64) + return np.c_[ + np.full(len(rows), BOS, dtype=np.int64), + rows[:, :-1], + np.full(len(rows), separator, dtype=np.int64), + ] + + +def pack_rows(rows, sequence=8, separator=71): + """All nonpadding next-token labels; compact rows contain no intermediate nodes.""" + rows = np.asarray(rows, dtype=np.int64) + sentence = np.c_[ + prompt_rows(rows, separator), rows[:, -1], np.full(len(rows), EOS, dtype=np.int64) + ] + length = sentence.shape[1] - 1 + if length > sequence: + raise ValueError("Packed sequence is too short") + tokens = np.zeros((len(rows), sequence), dtype=np.int64) + labels = np.full_like(tokens, -100) + tokens[:, :length], labels[:, :length] = sentence[:, :-1], sentence[:, 1:] + return tokens, labels + + +def run_name(spec): + seed = spec.get("world_seed", spec.get("world")) + return ( + f"w{seed}-i{spec['initialization']}-d{spec['width']}" + f"-l{spec['layers']}-r{spec['repeats']}-s{spec['steps']}" + ) + + +def _mean(values): + return float(np.asarray(values).mean()) if len(values) else None + + +@torch.no_grad() +def generate_rows(model, rows, device, separator=71, batch_size=512): + """Ordinary full forward, then free tail/EOS generation with answer feedback.""" + rows = np.asarray(rows, dtype=np.int64) + generated, nll = [], [] + for start in range(0, len(rows), batch_size): + batch = rows[start : start + batch_size] + tokens = torch.as_tensor(prompt_rows(batch, separator), device=device) + first = model(tokens)[:, -1] + target = torch.as_tensor(batch[:, -1], device=device) + nll.append(F.cross_entropy(first, target, reduction="none").cpu().numpy()) + answer = first.argmax(-1) + tokens = torch.cat([tokens, answer[:, None]], dim=1) + stop = model(tokens)[:, -1].argmax(-1) + generated.append(torch.stack([answer, stop], dim=1).cpu().numpy()) + pred = np.concatenate(generated) if generated else np.empty((0, 2), dtype=np.int64) + nll = np.concatenate(nll) if nll else np.empty(0, dtype=np.float32) + answer_correct = pred[:, 0] == rows[:, -1] + correct = answer_correct & (pred[:, 1] == EOS) + return { + "n": len(rows), + "accuracy": _mean(correct), + "answer_accuracy": _mean(answer_correct), + "answer_nll": _mean(nll), + }, {"generated": pred, "correct": correct, "answer_nll": nll} + + +@torch.no_grad() +def evaluate(model, world, device): + before = model.training + model.eval() + metrics, predictions = {}, {} + separator = world["metadata"]["separator_token"] + try: + atomic_metrics, atomic_pred = generate_rows(model, world["atomic"], device, separator) + metrics["atomic"] = atomic_metrics + predictions.update({"atomic_" + key: value for key, value in atomic_pred.items()}) + for name in EVALUATION_SPLITS[1:]: + rows = world[name] + task_metrics, direct = generate_rows(model, rows, device, separator) + nodes, edges = truth_path_details(world, rows) + coverage = atomic_pred["correct"][edges].all(axis=1) + current = rows[:, 0].copy() + hops = rows.shape[1] - 2 + calls = np.empty((len(rows), hops, 2), dtype=np.int64) + for hop in range(hops): + query = np.c_[current, rows[:, hop + 1], nodes[:, hop + 1]] + _, result = generate_rows(model, query, device, separator) + calls[:, hop] = result["generated"] + current = result["generated"][:, 0] + formats = (calls[:, :, 1] == EOS).all(axis=1) + autonomous_correct = formats & (current == rows[:, -1]) + path_correct = formats & (calls[:, :, 0] == nodes[:, 1:]).all(axis=1) + task_metrics.update( + { + "atomic_correct_coverage": _mean(coverage), + "conditional_accuracy": _mean(direct["correct"][coverage]), + "autonomous_two_calls": _mean(autonomous_correct), + "autonomous_path_accuracy": _mean(path_correct), + "hop_count": hops, + } + ) + metrics[name] = task_metrics + direct.update( + { + "coverage": coverage, + "autonomous_generated": calls, + "autonomous_correct": autonomous_correct, + "autonomous_path_correct": path_correct, + } + ) + predictions.update({name + "_" + key: value for key, value in direct.items()}) + finally: + model.train(before) + return metrics, predictions + + +def _validate_spec(spec): + nodes = spec["nodes"] + if nodes != sorted(set(nodes)) or nodes[0] != 0 or nodes[-1] != spec["steps"]: + raise ValueError("Nodes must increase from initialization to the fixed endpoint") + if not set(spec["checkpoint_nodes"]) <= set(nodes) or not {0, spec["steps"]} <= set( + spec["checkpoint_nodes"] + ): + raise ValueError("Checkpoint nodes must include initialization and endpoint") + if spec["batch_size"] != 128 or spec.get("dropout", 0.0) != 0.0: + raise ValueError("The fixed design requires four 32-example streams and dropout zero") + if spec.get("model_initialization", "scaled_effective") != "scaled_effective": + raise ValueError("The batch uses scaled_effective residual initialization") + + +def _save_world(out, world): + np.savez_compressed(out / "world.npz", **{key: world[key] for key in EVALUATION_SPLITS}) + write_json(out / "world-metadata.json", world["metadata"]) + + +def _check_source(source): + if not source or any(file_hash(path) != digest for path, digest in source.items()): + raise RuntimeError("Actual source differs from the required frozen source hashes") + + +def _validate_output(out): + """Permit scheduler control files while preserving every existing experiment artifact.""" + out = Path(out) + if out.exists(): + for path in out.iterdir(): + allowed = path.is_file() and ( + path.name == "input-spec.json" or path.name.endswith("-process.log") + ) + if not allowed: + raise FileExistsError( + "Do not overwrite an existing experiment artifact: " + str(path) + ) + + +def train(spec, out, source, device="cuda:0"): + _validate_spec(spec) + _check_source(source) + if "frozen_data_sha256" not in spec: + raise ValueError("Training requires frozen_data_sha256") + out = Path(out) + _validate_output(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(torch.device(device)) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + started_process = time.perf_counter() + world = build_world(spec) + digest = data_digest(world) + _save_world(out, world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_digest = model_digest(model) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + strata = [world[name] for name in TRAIN_SPLITS] + sizes = [len(rows) for rows in strata] + if any(size == 0 for size in sizes): + raise ValueError("Do not reroll a world with an empty sampled training stratum") + packed = [pack_rows(rows, separator=world["metadata"]["separator_token"]) for rows in strata] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True) + ) + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + graph = FullTokenStep(model, optimizer, table, spec["batch_size"], clip=spec.get("clip", 1.0)) + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 8, output_positions=8) + token_step = 32 * sum(int((labels[0] >= 0).sum()) for _, labels in packed) + history, step, training_seconds = [], 0, 0.0 + + def measure(loss=None): + metrics, predictions = evaluate(model, world, device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0.0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + np.savez_compressed( + out / f"exposures-{step:06d}.npz", + **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, + ) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["checkpoint_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"model-{step:06d}.pt", + ) + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["atomic"]["accuracy"], + "familiar": {str(hop): metrics[f"familiar_{hop}"]["accuracy"] for hop in HOPS}, + } + ), + flush=True, + ) + return row + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize() + started = time.perf_counter() + while step < end: + updates = min(128, end - step) + indices = [] + for i, stream in enumerate(streams): + draws = stream.take(updates * 32).reshape(updates, 32) + counts[i] += np.bincount(draws.ravel(), minlength=sizes[i]) + indices.append(draws + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(updates): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += updates + torch.cuda.synchronize() + training_seconds += time.perf_counter() - started + loss_value = float(loss) + if not np.isfinite(loss_value): + raise FloatingPointError("Nonfinite loss at step " + str(step)) + endpoint = measure(loss_value) + np.savez_compressed( + out / "exposures.npz", + **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, + ) + result = { + "spec": spec, + "source": source, + "data_sha256": digest, + "initial_model_sha256": initial_digest, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "strata_counts": dict(zip(TRAIN_SPLITS, sizes, strict=True)), + "endpoint": endpoint, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + "estimated_training_flops": step * flop_step, + "training_seconds": training_seconds, + "process_seconds": time.perf_counter() - started_process, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device), + "tf32": True, + }, + } + write_json(out / "complete.json", result) + return result + + +def compare_metrics(actual, expected): + if set(actual) != set(expected): + raise AssertionError("Metric task keys differ") + for task, values in actual.items(): + if set(values) != set(expected[task]): + raise AssertionError("Metric field keys differ") + for key, value in values.items(): + if key == "answer_nll" and value is not None: + np.testing.assert_allclose(value, expected[task][key], rtol=1e-5, atol=1e-5) + elif value != expected[task][key]: + raise AssertionError(f"Saved metric differs: {task}.{key}") + + +def compare_predictions(actual, path): + maximum = 0.0 + with np.load(path) as saved: + if set(actual) != set(saved.files): + raise AssertionError("Prediction keys differ") + for key, value in actual.items(): + if key.endswith("answer_nll"): + np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) + if value.size: + maximum = max(maximum, float(np.abs(value - saved[key]).max())) + else: + np.testing.assert_array_equal(value, saved[key]) + return maximum + + +def audit(out, device="cuda:0"): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(torch.device(device)) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + result = json.loads((out / "complete.json").read_text()) + recorded = json.loads((out / "spec.json").read_text()) + source, spec = result["source"], result["spec"] + _check_source(source) + _validate_spec(spec) + if recorded["spec"] != spec or recorded["source"] != source: + raise AssertionError("Recorded specification/source differ") + if file_hash(out / "latest.pt") != result["checkpoint_sha256"]: + raise AssertionError("Latest checkpoint hash differs") + world = build_world(spec) + digest = data_digest(world) + if digest != result["data_sha256"] or digest != recorded["data_sha256"]: + raise AssertionError("Rebuilt data differ from records") + if json.loads((out / "world-metadata.json").read_text()) != world["metadata"]: + raise AssertionError("Archived world metadata differ") + with np.load(out / "world.npz") as archived: + if set(archived.files) != set(EVALUATION_SPLITS): + raise AssertionError("Archived world keys differ") + for name in EVALUATION_SPLITS: + np.testing.assert_array_equal(archived[name], world[name]) + model = construct(spec, device) + if model_digest(model) != result["initial_model_sha256"]: + raise AssertionError("Paired initialization differs") + history = json.loads((out / "learning.json").read_text()) + if [row["step"] for row in history] != spec["nodes"]: + raise AssertionError("Recorded learning nodes differ") + by_node = {row["step"]: row for row in history} + if by_node[spec["steps"]] != result["endpoint"]: + raise AssertionError("Endpoint differs from the learning curve") + maximum = 0.0 + for node in spec["checkpoint_nodes"]: + checkpoint = torch.load( + out / f"model-{node:06d}.pt", map_location=device, weights_only=False + ) + if checkpoint["spec"] != spec or checkpoint["step"] != node: + raise AssertionError("Checkpoint specification/node differ") + model.load_state_dict(checkpoint["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, by_node[node]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{node:06d}.npz") + ) + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if ( + saved["spec"] != spec + or saved["source"] != source + or saved["step"] != spec["steps"] + or saved["data_sha256"] != digest + ): + raise AssertionError("Latest state identity differs") + sizes = [len(world[name]) for name in TRAIN_SPLITS] + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + previous = 0 + for node in spec["nodes"]: + for i, stream in enumerate(streams): + draws = ( + stream.take((node - previous) * 32) + if node > previous + else np.empty(0, dtype=np.int64) + ) + counts[i] += np.bincount(draws, minlength=sizes[i]) + with np.load(out / f"exposures-{node:06d}.npz") as actual: + for name, count in zip(TRAIN_SPLITS, counts, strict=True): + np.testing.assert_array_equal(actual[name], count) + previous = node + with np.load(out / "exposures.npz") as actual: + for i, (name, count) in enumerate(zip(TRAIN_SPLITS, counts, strict=True)): + np.testing.assert_array_equal(actual[name], count) + np.testing.assert_array_equal(saved["counts"][i], count) + if count.sum() != spec["steps"] * 32 or np.ptp(count) > 1: + raise AssertionError("EpochStream actual exposures are unbalanced") + stream = EpochStream(sizes[i], spec["stream_seed"] + i) + stream.load_state_dict(saved["streams"][i]) + np.testing.assert_array_equal(stream.take(32), streams[i].take(32)) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, result["endpoint"]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{spec['steps']:06d}.npz") + ) + checked = { + "passed": True, + "dataset_rebuilt_and_archived_exact": True, + "initial_model_exact": True, + "checkpoint_nodes": spec["checkpoint_nodes"], + "endpoint_tokens_exact": True, + "all_nodes_exposure_counters_exact": True, + "stream_state_continuation_exact": True, + "max_nll_difference": maximum, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "utc": utc(), + } + write_json(out / "audit.json", checked) + return checked diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..fc14c085184dc030670f1eea92655b73d0eec7c8 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py @@ -0,0 +1,371 @@ +"""Answer-only MLP editing calibration with frozen parent-logit regularization. + +This development grid changes the editor objective and learning rate, preserving +the completed v1 experiment. KL on a finite replay set is a regularizer, not an +exact preservation constraint. Kdev checks the operation; U never selects it. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import EOS, pack_rows +from .depth_step import SOURCE_FILES as TRAIN_SOURCES +from .depth_step_mechanism import edit_cases, generate +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import file_hash + +SOURCE_FILES = list( + dict.fromkeys( + [ + *TRAIN_SOURCES, + "src/llm_memory_editability/depth_step_mechanism.py", + "src/llm_memory_editability/depth_step_edit_calibration.py", + "scripts/calibrate_depth_step_edit.py", + "tests/test_depth_step_edit_calibration.py", + ] + ) +) +PARAMETER = "blocks.0.mlp.down.weight" +NODES = (0, 20, 100, 200) +LEARNING_RATES = (0.0001, 0.001, 0.003) + + +def _array_hash(array): + array = np.asarray(array) + digest = hashlib.sha256(str(array.dtype).encode()) + digest.update(np.asarray(array.shape, dtype="answer and teacher-forced answer->EOS supervision.""" + rows = np.asarray(rows, dtype=np.int64) + tokens, labels = pack_rows(rows, separator=world["metadata"]["separator_token"]) + positions = np.tile([rows.shape[1], rows.shape[1] + 1], (len(rows), 1)) + batch_indices = np.arange(len(rows))[:, None] + selected = labels[batch_indices, positions] + if not np.array_equal(selected, np.c_[rows[:, -1], np.full(len(rows), EOS)]): + raise ValueError("Answer/EOS positions disagree with the packed sequence") + return tuple(torch.as_tensor(value, device=device) for value in (tokens, positions, selected)) + + +def answer_eos_logits(model, batch): + tokens, positions, _labels = batch + return model(tokens, positions=positions) + + +def target_and_replay_loss(model, target_batch, replay_batch, parent_log_probabilities): + """CE only on two factual-output tokens; KL(parent || edited), equally weighted.""" + if parent_log_probabilities.requires_grad: + raise ValueError("Parent logits must be detached") + target_logits = answer_eos_logits(model, target_batch) + ce = F.cross_entropy(target_logits.flatten(0, 1), target_batch[2].flatten()) + replay_log = answer_eos_logits(model, replay_batch).log_softmax(-1) + kl = F.kl_div( + replay_log.flatten(0, 1), + parent_log_probabilities.flatten(0, 1), + reduction="batchmean", + log_target=True, + ) + return ce + kl, ce, kl + + +def _measure(model, case, world, device, step): + metrics, raw = {}, {} + for name, rows in case["tasks"].items(): + values, predictions = generate(model, rows, world, device) + if name in case["original_d_rows"]: + original = case["original_d_rows"][name] + changed = rows[:, -1] != original[:, -1] + predicted = predictions["predictions"] + correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) + old_correct = (predicted[:, 0] == original[:, -1]) & (predicted[:, 1] == EOS) + values.update( + { + "changed_answer_n": int(changed.sum()), + "changed_answer_coverage": float(changed.mean()) if len(rows) else None, + "changed_answer_accuracy": float(correct[changed].mean()) + if changed.any() + else None, + "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None, + } + ) + metrics[name] = values + raw.update({f"step{step}_{name}_{key}": value for key, value in predictions.items()}) + return metrics, raw + + +def calibrated_edit_one(model, case, world, device, arm, lr, nodes=NODES): + """One independently initialized branch, with fixed parent KL reference.""" + if arm not in {"edit", "review"}: + raise ValueError("Arm must be edit or review") + if tuple(nodes) != tuple(sorted(set(nodes))) or not nodes or nodes[0] != 0: + raise ValueError("Nodes must increase from zero") + parent_hash = model_digest(model) + edited = copy.deepcopy(model).eval() + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == PARAMETER) + parameter.grad = None + before = {name: value.detach().clone() for name, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[PARAMETER] + optimizer = torch.optim.Adam([parameter], lr=lr) + target_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) + target_batch = answer_eos_batch(target_rows, world, device) + replay_batch = answer_eos_batch(case["tasks"]["R_atomic"], world, device) + with torch.no_grad(): + parent_log = answer_eos_logits(model, replay_batch).log_softmax(-1).detach() + raw = { + "parent_replay_log_probabilities": parent_log.cpu().numpy(), + "replay_teacherforced_labels": replay_batch[2].cpu().numpy(), + } + for name, old_rows in case["original_d_rows"].items(): + raw[name + "_original_rows"] = old_rows + raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] + step, history, loss_values = 0, [], None + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, ce, kl = target_and_replay_loss(edited, target_batch, replay_batch, parent_log) + loss.backward() + optimizer.step() + step += 1 + loss_values = { + "total": float(loss.detach()), + "target_ce": float(ce.detach()), + "replay_kl": float(kl.detach()), + } + metrics, predictions = _measure(edited, case, world, device, step) + raw.update(predictions) + target_name = "E_new" if arm == "edit" else "E_old" + keep_pass = metrics["Kdev_atomic"]["accuracy"] >= 0.95 + target_pass = metrics[target_name]["accuracy"] == 1.0 + history.append( + { + "step": step, + "loss": loss_values, + "metrics": metrics, + "Kdev_at_least_95_percent": keep_pass, + "target_atomic_success": target_pass, + "calibration_operation_pass": keep_pass and target_pass, + } + ) + changed = [ + name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) + ] + if set(changed) - {PARAMETER}: + raise ValueError("A frozen state tensor changed") + if model_digest(model) != parent_hash: + raise ValueError("Original checkpoint model changed") + delta = parameter.detach() - before[PARAMETER] + raw["mlp_down_weight_delta"] = delta.cpu().numpy() + record = { + "arm": arm, + "lr": lr, + "atomic_index": case["atomic_index"], + "old_fact": case["old_fact"], + "new_fact": case["new_fact"], + "replay_indices": case["replay_indices"], + "keep_dev_indices": case["keep_dev_indices"], + "unused_atomic_indices": case["unused_atomic_indices"], + "parent_model_sha256": parent_hash, + "final_model_sha256": model_digest(edited), + "initial_down_weight_sha256": _array_hash(before[PARAMETER].cpu().numpy()), + "final_down_weight_sha256": _array_hash(parameter.detach().cpu().numpy()), + "updated_parameter": PARAMETER, + "changed_state_tensors": changed, + "weight_delta_l2": float(delta.norm()), + "history": history, + } + return record, raw + + +def prepare_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): + """Freeze data, all arms, sources, and initial weights before any model inference.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + if any(lr <= 0 or not np.isfinite(lr) for lr in learning_rates): + raise ValueError("Invalid learning rate") + cases, remaining = calibration_cases(world, n_cases=n_cases) + serialized = [] + for case in cases: + entry = { + key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"} + } + entry["task_rows"] = {key: value.tolist() for key, value in case["tasks"].items()} + entry["task_sha256"] = {key: _array_hash(value) for key, value in case["tasks"].items()} + entry["original_d_rows"] = { + key: value.tolist() for key, value in case["original_d_rows"].items() + } + serialized.append(entry) + config = { + "phase": "development_calibration", + "created_utc": utc(), + "source_checkpoint": source, + "source": {path: file_hash(path) for path in SOURCE_FILES}, + "parent_model_sha256": model_digest(model), + "initial_down_weight_sha256": _array_hash( + model.blocks[0].mlp.down.weight.detach().cpu().numpy() + ), + "learning_rates": list(learning_rates), + "nodes": list(NODES), + "cases": serialized, + "n_cases": n_cases, + "matrix": [ + {"case": i, "lr": lr, "arm": arm} + for i in range(n_cases) + for lr in learning_rates + for arm in ("edit", "review") + ], + "reserved_original_case_indices": remaining, + "reserved_cases_are_independent_world_confirmation": False, + "optimizer": "Adam, no weight decay", + "parameter": PARAMETER, + "objective": "target answer/EOS CE + KL(parent || edited) on 32 replay answer/EOS logits", + "replay_kl_weight": 1.0, + "supervised_prefix_tokens": 0, + "trained_compositions": 0, + "Kdev_selection": "First 32 lexicographic atoms excluding E, R, necessary successors", + "Kdev_threshold": 0.95, + "U_selection": "All remaining atomic facts, including unused necessary successors", + "U_or_D_select_editor": False, + "all_grid_failures_retained": True, + "executions_affected_by_shared_edit": model.repeats, + "limits": [ + "Finite replay KL is not strict output preservation", + "A successful Kdev check does not establish unobserved U preservation", + "Cases share one development world and original checkpoints", + ], + } + write_json(out / "calibration-config.json", config) + return config, cases + + +def load_prepared_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): + """Validate an existing prepared configuration, without rewriting it.""" + out = Path(out) + config_file = out / "calibration-config.json" + config = json.loads(config_file.read_text()) + if any(path.name != config_file.name for path in out.iterdir()): + raise FileExistsError("Existing branch artifacts prevent a repeated execution") + if config["learning_rates"] != list(learning_rates) or config["n_cases"] != n_cases: + raise ValueError("Requested grid differs from prepared calibration") + expected_source = config["source_checkpoint"] + for key in ("checkpoint_sha256", "dataset_sha256", "step", "spec"): + if source[key] != expected_source[key]: + raise ValueError("Checkpoint or data differ from prepared calibration: " + key) + if model_digest(model) != config["parent_model_sha256"]: + raise ValueError("Parent parameter hash differs from prepared calibration") + expected_matrix = [ + {"case": i, "lr": lr, "arm": arm} + for i in range(n_cases) + for lr in learning_rates + for arm in ("edit", "review") + ] + if config["matrix"] != expected_matrix or config["nodes"] != list(NODES): + raise ValueError("Prepared update matrix or nodes changed") + if ( + config["parameter"] != PARAMETER + or config["replay_kl_weight"] != 1.0 + or config["Kdev_threshold"] != 0.95 + or config["U_or_D_select_editor"] + ): + raise ValueError("Prepared operation contract changed") + cases, remaining = calibration_cases(world, n_cases=n_cases) + if remaining != config["reserved_original_case_indices"]: + raise ValueError("Reserved cases changed") + for case, frozen in zip(cases, config["cases"], strict=True): + for key in ( + "atomic_index", + "old_fact", + "new_fact", + "replay_indices", + "keep_dev_indices", + "unused_atomic_indices", + "propagation_scope", + ): + if case[key] != frozen[key]: + raise ValueError("Case selection changed: " + key) + if set(case["tasks"]) != set(frozen["task_rows"]): + raise ValueError("Prepared task set changed") + for name, rows in case["tasks"].items(): + if ( + rows.tolist() != frozen["task_rows"][name] + or _array_hash(rows) != frozen["task_sha256"][name] + ): + raise ValueError("Prepared task rows changed: " + name) + for name, rows in case["original_d_rows"].items(): + if rows.tolist() != frozen["original_d_rows"][name]: + raise ValueError("Prepared original D labels changed") + for path, expected in config["source"].items(): + if file_hash(path) != expected: + raise ValueError("Source changed after calibration freeze: " + path) + return config, cases + + +def execute_calibration(model, world, config, cases, out, device): + out = Path(out) + if model_digest(model) != config["parent_model_sha256"]: + raise ValueError("Parent parameter hash differs from frozen configuration") + for path, expected in config["source"].items(): + if file_hash(path) != expected: + raise ValueError("Source changed after calibration freeze: " + path) + for case, expected in zip(cases, config["cases"], strict=True): + for name, rows in case["tasks"].items(): + if _array_hash(rows) != expected["task_sha256"][name]: + raise ValueError("Task rows changed after freeze: " + name) + started = time.perf_counter() + records = [] + for item in config["matrix"]: + number, lr, arm = item["case"], item["lr"], item["arm"] + record, raw = calibrated_edit_one( + model, cases[number], world, device, arm, lr, nodes=tuple(config["nodes"]) + ) + label = f"case{number:02d}-lr{lr:.4f}-{arm}" + np.savez_compressed(out / (label + "-raw.npz"), **raw) + write_json(out / (label + ".json"), record) + records.append(record) + print(f"Calibration branch completed: {label}", flush=True) + report = { + "phase": "development_calibration", + "records": records, + "config_sha256": file_hash(out / "calibration-config.json"), + "completed_branches": len(records), + "wall_seconds": time.perf_counter() - started, + "model_selection_by_U_or_D": False, + } + write_json(out / "calibration-summary.json", report) + return report diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/depth_step_mechanism.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/depth_step_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb78cafec65ea5b0a4031d27502f7d0c4b00e16 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/depth_step_mechanism.py @@ -0,0 +1,589 @@ +"""Descriptive entity readouts, pure-first-hop interventions and MLP edits. + +No fitted probe or performance predictor is used. Residual readouts and raw MLP +cosines are descriptions; only interventions test a causal contribution. The +truth graph chooses queries, donors and edits before any model is evaluated. +""" + +from __future__ import annotations + +import copy +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import ENTITY_OFFSET, EOS, construct, pack_rows, prompt_rows, truth_path_details +from .grok_depth import utc, write_json +from .storage_composition import file_hash + + +def traced_forward(model, tokens, patches=None): + """Use the real SDPA computation and record every executed block/position. + + Patches map (zero-based execution, 'mlp_delta' or 'postresidual', position) + to a batch of replacement vectors. Repeated executions of a shared block + remain separately indexed. Attention maps are descriptive manual softmax; + the forward uses the same SDPA primitive as LoopGPT. + """ + if model.training: + raise ValueError("Tracing requires evaluation mode") + patches = patches or {} + length = tokens.shape[1] + x = model.token(tokens) + model.position(torch.arange(length, device=tokens.device)) + cache = {key: [] for key in ("attention_map", "attention_delta", "mlp_delta", "postresidual")} + consumed = set() + for index, block in enumerate(model.iter_blocks()): + z = block.ln1(x) + batch, _, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + q, k, v = (part.transpose(1, 2) for part in (q, k, v)) + scores = (q @ k.transpose(-1, -2)) / math.sqrt(width // a.heads) + causal = torch.ones(length, length, device=tokens.device, dtype=torch.bool).tril() + attention_map = scores.masked_fill(~causal, -torch.inf).softmax(-1) + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0.0) + attention_delta = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + attention_delta + mlp_delta = block.mlp(block.ln2(x)) + for key, replacement in patches.items(): + layer, component, position = key + if layer == index and component == "mlp_delta": + if replacement.shape != mlp_delta[:, position].shape: + raise ValueError("Patch shape differs from selected MLP position") + mlp_delta = mlp_delta.clone() + mlp_delta[:, position] = replacement + consumed.add(key) + x = x + mlp_delta + for key, replacement in patches.items(): + layer, component, position = key + if layer == index and component == "postresidual": + if replacement.shape != x[:, position].shape: + raise ValueError("Patch shape differs from selected residual position") + x = x.clone() + x[:, position] = replacement + consumed.add(key) + for key, value in ( + ("attention_map", attention_map), + ("attention_delta", attention_delta), + ("mlp_delta", mlp_delta), + ("postresidual", x), + ): + cache[key].append(value.detach()) + if consumed != set(patches): + raise ValueError("Unknown execution/component in patch") + logits = F.linear(model.ln_final(x), model.token.weight) + return logits, {key: torch.stack(values) for key, values in cache.items()} + + +def _separator(world): + return int(world["metadata"]["separator_token"]) + + +def _mean(values): + return float(np.mean(values)) if len(values) else None + + +@torch.no_grad() +def generate(model, rows, world, device, batch_size=256): + """Free answer then free EOS, retaining full-vocabulary probabilities.""" + rows = np.asarray(rows, dtype=np.int64) + predictions, probabilities, gold_probabilities = [], [], [] + for begin in range(0, len(rows), batch_size): + selected = rows[begin : begin + batch_size] + tokens = torch.as_tensor(prompt_rows(selected, _separator(world)), device=device) + probability = model(tokens)[:, -1].softmax(-1) + answer = probability.argmax(-1) + eos = model(torch.cat((tokens, answer[:, None]), dim=1))[:, -1].argmax(-1) + predictions.append(torch.stack((answer, eos), 1).cpu().numpy()) + probabilities.append(probability.cpu().numpy()) + gold_probabilities.append( + probability[ + torch.arange(len(selected), device=device), + torch.as_tensor(selected[:, -1], device=device), + ] + .cpu() + .numpy() + ) + vocab = model.config.vocab_size + predicted = np.concatenate(predictions) if predictions else np.empty((0, 2), dtype=np.int64) + prob = ( + np.concatenate(probabilities) if probabilities else np.empty((0, vocab), dtype=np.float32) + ) + gold_prob = np.concatenate(gold_probabilities) if gold_probabilities else np.empty(0) + correct = predicted[:, 0] == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": _mean(correct), + "accuracy": _mean(correct & (predicted[:, 1] == EOS)), + "gold_probability": _mean(gold_prob), + }, {"rows": rows, "predictions": predicted, "answer_probabilities": prob} + + +def select_donors(world, rows): + """Lexicographic donors know exactly one fact and no target second relation.""" + atoms = world["atomic"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + nodes, _ = truth_path_details(world, rows) + same, changed, changed_tail = [], [], [] + for row, path in zip(rows, nodes, strict=True): + h, r1, r2, old_tail = map(int, row) + bridge = int(path[1]) + identical = next( + (i for i in order if int(atoms[i, 2]) == bridge and tuple(atoms[i, :2]) != (h, r1)), -1 + ) + different = next( + ( + i + for i in order + if int(atoms[i, 2]) != bridge + and (int(atoms[i, 2]), r2) in lookup + and lookup[(int(atoms[i, 2]), r2)] != old_tail + ), + -1, + ) + same.append(identical) + changed.append(different) + changed_tail.append(lookup[(int(atoms[different, 2]), r2)] if different >= 0 else -1) + return { + "same_bridge_atomic_indices": np.asarray(same, dtype=np.int64), + "different_bridge_atomic_indices": np.asarray(changed, dtype=np.int64), + "different_bridge_tail": np.asarray(changed_tail, dtype=np.int64), + } + + +@torch.no_grad() +def entity_readouts(model, cache, targets, entities): + """Apply the unmodified final norm/tied readout; raw MLP cosine is separate.""" + residual = cache["postresidual"] + logits = F.linear(model.ln_final(residual), model.token.weight) + entity_logits = logits[..., ENTITY_OFFSET : ENTITY_OFFSET + entities] + probabilities = logits.softmax(-1) + entity_probabilities = entity_logits.softmax(-1) + embedding = F.normalize(model.token.weight[ENTITY_OFFSET : ENTITY_OFFSET + entities], dim=-1) + cosine = F.normalize(cache["mlp_delta"], dim=-1) @ embedding.T + arrays = {} + for name, token_ids in targets.items(): + ids = torch.as_tensor(token_ids, device=residual.device) + full_ids = ids[None, :, None, None].expand(*residual.shape[:-1], 1) + entity_ids = full_ids - ENTITY_OFFSET + gold_logit = entity_logits.gather(-1, entity_ids).squeeze(-1) + gold_cosine = cosine.gather(-1, entity_ids).squeeze(-1) + arrays[name + "_residual_entity_rank"] = 1 + (entity_logits > gold_logit[..., None]).sum(-1) + arrays[name + "_residual_vocab_probability"] = probabilities.gather(-1, full_ids).squeeze( + -1 + ) + arrays[name + "_residual_entity_probability"] = entity_probabilities.gather( + -1, entity_ids + ).squeeze(-1) + arrays[name + "_mlp_embedding_cosine"] = gold_cosine + arrays[name + "_mlp_embedding_cosine_rank"] = 1 + (cosine > gold_cosine[..., None]).sum(-1) + return {name: value.cpu().numpy() for name, value in arrays.items()} + + +@torch.no_grad() +def _patched_generation(model, tokens, patch): + logits, _ = traced_forward(model, tokens, patch) + probability = logits[:, -1].softmax(-1) + answer = probability.argmax(-1) + # Reapply the same intervention while freely generating the EOS token. + extended = torch.cat((tokens, answer[:, None]), dim=1) + eos_logits, _ = traced_forward(model, extended, patch) + eos = eos_logits[:, -1].argmax(-1) + return torch.stack((answer, eos), 1).cpu().numpy(), probability.cpu().numpy() + + +def trace_analysis(model, world, out, device, max_queries=128): + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + model.eval() + started = time.perf_counter() + raw, baseline = {}, {} + for split in ("atomic", "familiar_2", "strict_2"): + metrics, prediction = generate(model, world[split], world, device) + baseline[split] = metrics + raw.update({f"baseline_{split}_{key}": value for key, value in prediction.items()}) + indices = np.arange(min(max_queries, len(world["familiar_2"]))) + rows = world["familiar_2"][indices] + nodes, edges = truth_path_details(world, rows) + tokens = torch.as_tensor(prompt_rows(rows, _separator(world)), device=device) + with torch.no_grad(): + reference = model(tokens) + actual, cache = traced_forward(model, tokens) + difference = float((actual - reference).abs().max()) + torch.testing.assert_close(actual, reference, rtol=1e-5, atol=2e-6) + if not torch.equal(actual.argmax(-1), reference.argmax(-1)): + raise ValueError("Traced forward changes full-vocabulary argmax") + raw.update( + { + "query_indices": indices, + "query_rows": rows, + "truth_nodes": nodes, + "truth_atomic_indices": edges, + } + ) + raw.update({"cache_" + key: value.cpu().numpy() for key, value in cache.items()}) + raw.update( + entity_readouts( + model, + cache, + {"bridge": nodes[:, 1], "tail": nodes[:, -1]}, + world["metadata"]["entities"], + ) + ) + donors = select_donors(world, rows) + raw.update(donors) + atom_predictions = raw["baseline_atomic_predictions"] + atoms = world["atomic"] + atom_correct = (atom_predictions[:, 0] == atoms[:, -1]) & (atom_predictions[:, 1] == EOS) + atomic_key_indices = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)} + raw["original_constituent_atoms_correct"] = atom_correct[edges].all(1) + records = [] + for style in ("self", "same_bridge", "different_bridge"): + donor_ids = edges[:, 0] if style == "self" else donors[style + "_atomic_indices"] + valid = donor_ids >= 0 + selected = np.flatnonzero(valid) + if not len(selected): + continue + donor_rows = world["atomic"][donor_ids[valid]] + donor_tokens = torch.as_tensor(prompt_rows(donor_rows, _separator(world)), device=device) + with torch.no_grad(): + _, donor_cache = traced_forward(model, donor_tokens) + expected = ( + donors["different_bridge_tail"][valid] + if style == "different_bridge" + else rows[valid, -1] + ) + new_second_indices = np.asarray( + [ + atomic_key_indices[(int(donor[2]), int(query[2]))] + for donor, query in zip(donor_rows, rows[valid], strict=True) + ] + ) + premises = ( + atom_correct[edges[valid]].all(1) + & atom_correct[donor_ids[valid]] + & atom_correct[new_second_indices] + ) + raw[style + "_premises_correct"] = premises + for layer in range(model.effective_depth): + for component in ("mlp_delta", "postresidual"): + for position in (2, 1): + key = f"{style}_layer{layer}_{component}_pos{position}" + patch = { + (layer, component, position): donor_cache[component][layer, :, position] + } + prediction, probability = _patched_generation(model, tokens[valid], patch) + raw[key + "_selected_query_indices"] = selected + raw[key + "_predictions"] = prediction + raw[key + "_answer_probabilities"] = probability + following = prediction[:, 0] == expected + correct = prediction[:, 0] == rows[valid, -1] + base_pred = raw["baseline_familiar_2_predictions"][indices[valid]] + base_correct = (base_pred[:, 0] == rows[valid, -1]) & (base_pred[:, 1] == EOS) + if style == "self" and not np.array_equal(prediction, base_pred): + raise ValueError("Pure-first-hop self patch changes generation") + record = { + "donor": style, + "execution": layer, + "component": component, + "position": position, + "n": len(selected), + "selected_query_coverage": len(selected) / len(rows), + "full_pool_coverage": len(selected) / len(world["familiar_2"]), + "new_route_answer_accuracy": _mean(following), + "new_route_accuracy": _mean(following & (prediction[:, 1] == EOS)), + "original_accuracy": _mean(correct & (prediction[:, 1] == EOS)), + "baseline_correct_coverage": _mean(base_correct), + "all_required_atomic_correct_coverage": _mean(premises), + "new_route_conditional_on_required_atomics": _mean( + (following & (prediction[:, 1] == EOS))[premises] + ), + "new_route_conditional_on_baseline_correct": _mean( + (following & (prediction[:, 1] == EOS))[base_correct] + ), + } + records.append(record) + with torch.no_grad(): + entity_embedding = model.token.weight[ + ENTITY_OFFSET : ENTITY_OFFSET + world["metadata"]["entities"] + ] + normalized = F.normalize(entity_embedding, dim=-1) + raw["entity_embedding_cosine_matrix"] = (normalized @ normalized.T).cpu().numpy() + raw["entity_embedding_singular_values"] = ( + torch.linalg.svdvals(entity_embedding).cpu().numpy() + ) + np.savez_compressed(out / "trace-raw.npz", **raw) + report = { + "phase": "development", + "created_utc": utc(), + "baseline": baseline, + "query_selection": ( + "First 128 familiar_2 rows in frozen data order, independent of predictions" + ), + "selected_queries": len(rows), + "full_pool_queries": len(world["familiar_2"]), + "selection_coverage": len(rows) / len(world["familiar_2"]), + "forward_max_absolute_difference": difference, + "forward_all_argmax_identical": True, + "donor_information": ( + "Only BOS, head, first relation, SEP; no second relation or final answer" + ), + "patch_position_roles": {"1": "head control", "2": "first relation"}, + "interventions": records, + "wall_seconds": time.perf_counter() - started, + "limits": [ + "Unfitted final-norm tied readout and raw cosine are descriptive", + "Attention maps are descriptive; patch tests entire state or MLP contribution", + "Layers, positions and queries are dependent measurements in one world", + ], + } + write_json(out / "trace-summary.json", report) + return report + + +def edit_cases(world, n_facts=8, replay_n=32): + """Choose graph-based first-hop edits before observing any model behavior.""" + atoms = world["atomic"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + candidate_first = {(int(row[0]), int(row[1])) for row in world["familiar_2"]} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + cases = [] + for index in order: + h, relation, old_bridge = map(int, atoms[index]) + if (h, relation) not in candidate_first: + continue + first_rows = world["familiar_2"][ + (world["familiar_2"][:, 0] == h) & (world["familiar_2"][:, 1] == relation) + ] + bridges = sorted({int(t) for _, _, t in atoms}) + new_bridge = next( + ( + b + for b in bridges + if b != old_bridge + and all( + (b, int(row[2])) in lookup and lookup[(b, int(row[2]))] != int(row[-1]) + for row in first_rows + ) + ), + None, + ) + if new_bridge is None: + continue + replay_indices = np.asarray([i for i in order if i != index][:replay_n]) + if len(replay_indices) != replay_n: + raise ValueError("Insufficient nonedited replay atoms") + new_fact = np.asarray([[h, relation, new_bridge]], dtype=np.int64) + old_fact = atoms[index : index + 1].copy() + edited_lookup = {**lookup, (h, relation): new_bridge} + tasks = {"E_new": new_fact, "E_old": old_fact, "R_atomic": atoms[replay_indices].copy()} + original_d_rows = {} + unreplayed = [i for i in range(len(atoms)) if i != index and i not in replay_indices] + tasks["U_atomic"] = atoms[unreplayed].copy() + successor_keys = set() + for split in ("familiar_2", "strict_2"): + rows = world[split] + nodes, path_indices = truth_path_details(world, rows) + first = path_indices[:, 0] == index + second = (path_indices[:, 1] == index) & ~first + unaffected = ~(first | second) + for role, mask in (("first", first), ("second", second)): + changed = rows[mask].copy() + for i, row in enumerate(changed): + bridge = edited_lookup[(int(row[0]), int(row[1]))] + changed[i, -1] = edited_lookup[(bridge, int(row[2]))] + if role == "first" and (bridge, int(row[2])) != (h, relation): + successor_keys.add((bridge, int(row[2]))) + tasks[f"D_{role}_{split}"] = changed + original_d_rows[f"D_{role}_{split}"] = rows[mask].copy() + tasks["U_" + split] = rows[unaffected].copy() + # All facts occurring as either hop in U retain their graph labels. + if index in path_indices[unaffected]: + raise ValueError("Edited fact leaked into the unaffected holdout") + del nodes + successor_indices = [i for i, row in enumerate(atoms) if tuple(row[:2]) in successor_keys] + tasks["necessary_successor_atomic"] = atoms[successor_indices].copy() + cases.append( + { + "atomic_index": index, + "old_fact": old_fact[0].tolist(), + "new_fact": new_fact[0].tolist(), + "replay_indices": replay_indices.tolist(), + "tasks": tasks, + "original_d_rows": original_d_rows, + "propagation_scope": { + name: { + "n": len(old_rows), + "changed_answer_n": int( + np.count_nonzero(tasks[name][:, -1] != old_rows[:, -1]) + ), + "source_pool_n": len(world[name.split("_", 2)[2]]), + } + for name, old_rows in original_d_rows.items() + }, + } + ) + if len(cases) == n_facts: + break + if len(cases) != n_facts: + raise ValueError("Fewer graph-valid fixed edit cases than requested") + return cases + + +def _atomic_loss(model, rows, world, device): + tokens, labels = pack_rows(rows, separator=_separator(world)) + tokens = torch.as_tensor(tokens, device=device) + labels = torch.as_tensor(labels, device=device) + logits = model(tokens) + return F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + + +def edit_one(model, case, world, device, arm, nodes=(0, 20, 100, 200), lr=0.01): + """Independently edit one checkpoint; only unique block-0 MLP down changes.""" + if arm not in {"edit", "review"}: + raise ValueError("Arm must be edit or review") + if tuple(nodes) != tuple(sorted(set(nodes))) or nodes[0] != 0: + raise ValueError("Nodes must be increasing with initial measurement") + edited = copy.deepcopy(model).eval() + target_name = "blocks.0.mlp.down.weight" + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == target_name) + parameter.grad = None + before = {name: value.detach().clone() for name, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[target_name] + optimizer = torch.optim.Adam([parameter], lr=lr) + objective_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) + history, raw = [], {} + for name, old_rows in case["original_d_rows"].items(): + raw[name + "_original_rows"] = old_rows + raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] + step = 0 + final_loss = None + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + loss = 0.5 * _atomic_loss(edited, objective_rows, world, device) + loss = loss + 0.5 * _atomic_loss(edited, case["tasks"]["R_atomic"], world, device) + loss.backward() + optimizer.step() + step += 1 + final_loss = float(loss.detach()) + measures = {} + for name, rows in case["tasks"].items(): + metrics, prediction = generate(edited, rows, world, device) + if name in case["original_d_rows"]: + old_rows = case["original_d_rows"][name] + changed_mask = rows[:, -1] != old_rows[:, -1] + predicted = prediction["predictions"] + correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) + old_correct = (predicted[:, 0] == old_rows[:, -1]) & (predicted[:, 1] == EOS) + metrics.update( + { + "changed_answer_n": int(changed_mask.sum()), + "changed_answer_coverage": _mean(changed_mask), + "changed_answer_accuracy": _mean(correct[changed_mask]), + "old_answer_accuracy": _mean(old_correct), + } + ) + measures[name] = metrics + raw.update({f"step{step}_{name}_{key}": value for key, value in prediction.items()}) + history.append({"step": step, "loss": final_loss, "metrics": measures}) + changed = [ + name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) + ] + if set(changed) - {target_name}: + raise ValueError("Parameters outside the frozen MLP projection changed") + delta = parameter.detach() - before[target_name] + raw["mlp_down_weight_delta"] = delta.cpu().numpy() + return { + "arm": arm, + "atomic_index": case["atomic_index"], + "old_fact": case["old_fact"], + "new_fact": case["new_fact"], + "replay_indices": case["replay_indices"], + "propagation_scope": case["propagation_scope"], + "updated_parameter": target_name, + "changed_state_tensors": changed, + "weight_delta_l2": float(delta.norm()), + "history": history, + }, raw + + +def edit_analysis(model, world, out, device, n_facts=8, nodes=(0, 20, 100, 200), lr=0.01): + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + started = time.perf_counter() + cases = edit_cases(world, n_facts=n_facts) + serializable_cases = [ + {key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"}} + | {"task_sizes": {key: len(rows) for key, rows in case["tasks"].items()}} + for case in cases + ] + # This is written before evaluating or updating any case. + write_json(out / "data-selected-edit-cases.json", serializable_cases) + records = [] + for number, case in enumerate(cases): + for arm in ("edit", "review"): + record, raw = edit_one(model, case, world, device, arm, nodes=nodes, lr=lr) + np.savez_compressed(out / f"case{number:02d}-{arm}-raw.npz", **raw) + write_json(out / f"case{number:02d}-{arm}.json", record) + records.append(record) + report = { + "phase": "development", + "created_utc": utc(), + "n_facts": n_facts, + "nodes": list(nodes), + "lr": lr, + "optimizer": "Adam, no weight decay", + "objective": "0.5 target atomic full-token CE + 0.5 fixed 32-atomic replay full-token CE", + "trained_compositions": 0, + "unique_block_edited": 0, + "executions_affected_by_shared_edit": model.repeats, + "independent_layers": len(model.blocks), + "execution_depth": model.effective_depth, + "scope_difference": ( + "Loop block-0 update applies at every repeat; ordinary block-0 applies once" + ), + "records": records, + "wall_seconds": time.perf_counter() - started, + "limits": [ + "Edits use the same fixed budget; failed target changes remain in results", + "MLP-only parameter fine-tuning is not a constrained-preservation theorem", + "Each case independently starts from the same checkpoint", + "A single development world is not independent confirmation", + ], + } + write_json(out / "edit-summary.json", report) + return report + + +def load_run(run_dir, checkpoint, device): + run_dir, checkpoint = Path(run_dir), Path(checkpoint) + saved = torch.load(checkpoint, map_location=device, weights_only=False) + model = construct(saved["spec"], device).eval() + model.load_state_dict(saved["model"], strict=True) + arrays = np.load(run_dir / "world.npz", allow_pickle=False) + world = {key: arrays[key] for key in arrays.files} + world["metadata"] = json.loads((run_dir / "world-metadata.json").read_text()) + from .depth_step import audit_world + + audit = audit_world(world) + if audit["dataset_sha256"] != saved["spec"].get("frozen_data_sha256", audit["dataset_sha256"]): + raise ValueError("Checkpoint and archived data digest disagree") + return ( + model, + world, + { + "checkpoint": str(checkpoint), + "checkpoint_sha256": file_hash(checkpoint), + "step": saved["step"], + "spec": saved["spec"], + "dataset_sha256": audit["dataset_sha256"], + }, + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/experiment_tracking.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/experiment_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..167c8e1a359008fa8b7c89642273e85c9699643e --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/experiment_tracking.py @@ -0,0 +1,298 @@ +"""W&B sidecar for future experiments; reads trainer artifacts without changing training.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import importlib +import json +import math +import os +import subprocess +import sys +import time +from pathlib import Path + +DEFAULTS = Path(__file__).resolve().parents[2] / "configs/experiment-tracking-defaults.json" +PRIVATE_KEYS = { + "api_key", + "wandb_api_key", + "access_token", + "auth_token", + "password", + "credentials", + "secret", +} + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temp.replace(path) + + +def public_config(value): + if isinstance(value, dict): + return {k: public_config(v) for k, v in value.items() if k.lower() not in PRIVATE_KEYS} + if isinstance(value, list): + return [public_config(v) for v in value] + return value + + +def numeric_fields(value, prefix): + result = {} + for key, item in value.items(): + name = f"{prefix}/{key}" + if isinstance(item, dict): + result.update(numeric_fields(item, name)) + elif isinstance(item, int | float) and not isinstance(item, bool) and math.isfinite(item): + result[name] = item + return result + + +def learning_metrics(record, previous=None): + """Keep the actual optimizer step and task denominators; derive interval throughput.""" + result = {"training/step": int(record["step"])} + result.update(numeric_fields(record.get("metrics", {}), "eval")) + groups = { + "training_seconds": "perf/training_seconds", + "wall_seconds": "perf/wall_seconds", + "examples": "exposure/examples", + "supervised_tokens": "exposure/supervised_tokens", + "executed_input_tokens": "compute/executed_input_tokens", + "estimated_matmul_training_flops": "compute/estimated_matmul_training_flops", + "atomic_epochs": "exposure/atomic_epochs", + "composition_epochs": "exposure/composition_epochs", + } + for key, value in record.items(): + if key in {"step", "metrics"}: + continue + if isinstance(value, int | float) and not isinstance(value, bool) and math.isfinite(value): + result[groups.get(key, f"training/{key}")] = value + if previous is not None and record["step"] > previous["step"]: + steps = record["step"] - previous["step"] + if "training_seconds" in record and "training_seconds" in previous: + seconds = record["training_seconds"] - previous["training_seconds"] + if seconds > 0: + result["perf/training_ms_per_update"] = 1000 * seconds / steps + result["perf/updates_per_second"] = steps / seconds + if "examples" in record and "examples" in previous: + result["perf/examples_per_second"] = ( + record["examples"] - previous["examples"] + ) / seconds + return result + + +class ArtifactRunTracker: + def __init__(self, sdk, batch, path, settings): + self.path = Path(path) + self.state_path = Path(batch) / "tracking-wandb" / self.path.name / "state.json" + self.metadata = read_json(self.path / "run.json") + self.settings = settings + identity = { + "batch": Path(batch).name, + "name": self.path.name, + "spec": public_config(self.metadata.get("spec", {})), + "world_sha256": self.metadata.get("world_sha256"), + "initial_model_sha256": self.metadata.get("initial_model_sha256"), + } + fingerprint = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest() + saved = read_json(self.state_path) if self.state_path.exists() else {} + if saved: + assert saved["fingerprint"] == fingerprint, "Source trajectory identity changed" + assert saved["entity"] == settings["entity"] and saved["project"] == settings["project"] + self.state = { + "run_id": fingerprint[:16], + "fingerprint": fingerprint, + "entity": settings["entity"], + "project": settings["project"], + "last_logged_step": -1, + **saved, + } + options = {"disable_git": True} + if not settings["system_metrics"]: + options["x_disable_stats"] = True + else: + if "gpu" in self.metadata: + options["x_stats_gpu_device_ids"] = (self.metadata["gpu"],) + if "pid" in self.metadata: + options["x_stats_pid"] = self.metadata["pid"] + mode = settings["mode"] + run_id = self.state["run_id"] + if mode == "offline" and saved: + segment = saved.get("offline_segment", 0) + 1 + self.state["offline_segment"] = segment + run_id = f"{run_id[:12]}{segment:04x}" + self.state_path.parent.mkdir(parents=True, exist_ok=True) + config = { + **identity, + "scientific_run_id": self.state["run_id"], + **{ + k: self.metadata[k] + for k in [ + "model", + "phase", + "evaluation_nodes", + "execution_lock_sha256", + "parameters", + "vocab_size", + "atomic_examples", + "composition_examples", + "dtype", + "gpu_name", + ] + if k in self.metadata + }, + } + self.run = sdk.init( + entity=settings["entity"], + project=settings["project"], + group=self.metadata.get("tracking_group", Path(batch).name), + name=self.path.name, + id=run_id, + config=config, + mode=mode, + resume="allow" if mode == "online" else None, + job_type=self.metadata.get("job_type", "training"), + tags=self.metadata.get("tags", []), + dir=str(self.state_path.parent), + save_code=False, + reinit="create_new", + settings=sdk.Settings(**options), + ) + self.run.define_metric("training/step") + self.run.define_metric("*", step_metric="training/step") + if mode == "online": + # The public history is authoritative: an SDK restart can briefly report step 0, + # and a local cursor can include points queued before a network interruption. + remote = sdk.Api(timeout=30).run(f"{settings['entity']}/{settings['project']}/{run_id}") + self.cursor = remote.lastHistoryStep + else: + self.cursor = self.state["last_logged_step"] + self.state.update(url=self.run.url, mode=mode, wandb_run_id=run_id) + write_json(self.state_path, self.state) + + def poll(self): + history = read_json(self.path / "learning.json") + previous = None + for record in history: + step = int(record["step"]) + if step > self.cursor: + self.run.log(learning_metrics(record, previous), step=step) + self.cursor = step + self.state["last_logged_step"] = step + write_json(self.state_path, self.state) + previous = record + status_path = self.path / "status.json" + if status_path.exists(): + status = read_json(status_path) + self.run.summary["training_state"] = status.get("state", "unknown") + complete = (self.path / "complete.json").exists() + failure_record = (self.path / "failure.json").exists() or ( + self.path / "failure-detail.json" + ).exists() + failed = failure_record and not complete + self.run.summary["has_failure_record"] = failure_record + self.run.summary["independently_reloaded"] = (self.path / "audit.json").exists() + if complete or failed: + self.run.summary["scientific_final_step"] = self.cursor + self.run.finish(exit_code=1 if failed else 0) + return True + return False + + def close(self): + self.run.finish() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--runs-dir", type=Path) + parser.add_argument("--defaults", type=Path, default=DEFAULTS) + parser.add_argument("--entity") + parser.add_argument("--project") + parser.add_argument("--mode", choices=["online", "offline"]) + parser.add_argument("--once", action="store_true") + parser.add_argument("--detach", action="store_true") + args = parser.parse_args() + settings = read_json(args.defaults) + for name in ["entity", "project", "mode"]: + settings[name] = ( + getattr(args, name) or os.environ.get(f"WANDB_{name.upper()}") or settings[name] + ) + if not settings["enabled"]: + raise SystemExit("Experiment tracking is disabled in the selected defaults") + local = args.root / "tracking-wandb" + local.mkdir(parents=True, exist_ok=True) + if args.detach: + metadata_path = local / "process.json" + if metadata_path.exists(): + pid = read_json(metadata_path)["pid"] + try: + os.kill(pid, 0) + except ProcessLookupError: + pass + else: + raise SystemExit(f"Tracking process already running: {pid}") + arguments = [a for a in sys.argv[1:] if a != "--detach"] + command = [ + sys.executable, + "-u", + "-m", + "llm_memory_editability.experiment_tracking", + *arguments, + ] + with (local / "tracker.log").open("a") as log: + process = subprocess.Popen( + command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True + ) + write_json(metadata_path, {"pid": process.pid, "command": command}) + print(json.dumps({"tracker_pid": process.pid, "log": str(local / "tracker.log")})) + return + try: + sdk = importlib.import_module("wandb") + except ImportError as error: + raise SystemExit("Install the tracking extra, or use .venv-wandb/bin/python") from error + with (local / "tracker.lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + active, finished = {}, set() + runs_dir = args.runs_dir or args.root / "development" + try: + while True: + for path in sorted(runs_dir.glob("*")): + if path in active or path in finished: + continue + if not (path / "run.json").exists() or not (path / "learning.json").exists(): + continue + active[path] = ArtifactRunTracker(sdk, args.root, path, settings) + print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True) + for path, tracker in list(active.items()): + current = read_json(path / "run.json") + if current.get("pid") != tracker.metadata.get("pid"): + tracker.close() + tracker = ArtifactRunTracker(sdk, args.root, path, settings) + active[path] = tracker + if tracker.poll(): + finished.add(path) + del active[path] + if args.once: + break + manifest = args.root / "controller-state.json" + if manifest.exists() and not active: + if read_json(manifest).get("state") in {"complete", "finished_with_failures"}: + break + time.sleep(settings["poll_seconds"]) + finally: + for tracker in active.values(): + tracker.close() + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/experiments.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/experiments.py new file mode 100644 index 0000000000000000000000000000000000000000..21513c79efc2f2e137213ca20f5444209e6d313d --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/experiments.py @@ -0,0 +1,39 @@ +"""Deterministic analytical illustration from the supplied research memo.""" + +import platform +from typing import Any + +import numpy as np + +from .low_rank import evaluate_update + + +def run_minimal_example(rank: int = 1, atol: float = 1e-10) -> dict[str, Any]: + """Compare a shared-rule update with a one-entry exception. + + At rank budget one, both changes have rank-one deltas but only the rule's + target is representable. At budget two, both targets are representable. + This is a classical matrix fact, not evidence of LLM editing difficulty. + """ + original = np.ones((2, 2), dtype=float) + cases = { + "original": evaluate_update(original, original, rank, atol), + "rule": evaluate_update(original, 2 * original, rank, atol), + "exception": evaluate_update(original, [[2, 1], [1, 1]], rank, atol), + } + return { + "experiment": "minimal_low_rank", + "scope": ( + "Analytical SVD illustration for fully observed real matrices with a " + "fixed total rank budget and unweighted Frobenius error. No training, " + "optimization path, or Transformer editing is evaluated. Numerical " + "rank counts singular values greater than an absolute tolerance; " + "this example does not validate the broader research hypothesis." + ), + "parameters": { + "rank_budget": cases["original"]["rank_budget"], + "atol": cases["original"]["atol"], + }, + "versions": {"python": platform.python_version(), "numpy": np.__version__}, + "cases": cases, + } diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_depth.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb93ea353cb12f972942a3cf658bc6593f81bb7 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_depth.py @@ -0,0 +1,431 @@ +"""Small GPT-2 composition learning, adapted from Wang et al. (NeurIPS 2024). + +Data/target conventions follow GrokkedTransformer commit 734ca654ec7a71dd6737d640407fac14491d538c. +The compact vocabulary, widths and data sizes are explicit experimental adaptations. +CUDA Graph capture is an execution optimization, not a change to the training objective. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import math +import time +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import CausalLM, ModelConfig, matmul_flops + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + tmp.replace(path) + + +class SmallGPT(CausalLM): + """GPT-2 pre-LN, tied output, learned positions, GELU, standard dropout.""" + + def __init__(self, config, dropout=0.1): + super().__init__(config) + self.dropout = dropout + + def forward(self, tokens, positions=None): + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + for block in self.blocks: + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + +def pack_rows(rows): + """Right-pad; supervise tail and EOS only. No BOS or answer delimiter.""" + rows = np.asarray(rows, dtype=np.int64) + x = np.zeros((len(rows), 4), dtype=np.int64) + x[:, : rows.shape[1]] = rows + positions = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) + labels = np.c_[rows[:, -1], np.ones(len(rows), dtype=np.int64)] + return x, positions, labels + + +def make_optimizer(model, lr, weight_decay): + decay = [p for p in model.parameters() if p.ndim >= 2] + no_decay = [p for p in model.parameters() if p.ndim < 2] + return torch.optim.AdamW( + [ + {"params": decay, "weight_decay": weight_decay}, + {"params": no_decay, "weight_decay": 0.0}, + ], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + fused=True, + capturable=True, + ) + + +class GraphStep: + """Capture complete AdamW step and undo warmup without rebinding state tensors.""" + + def __init__(self, model, optimizer, table, batch_size, clip=1.0): + self.index = torch.zeros(batch_size, dtype=torch.long, device=table[0].device) + self.model, self.optimizer, self.table, self.clip = model, optimizer, table, clip + weights = {k: v.detach().clone() for k, v in model.state_dict().items()} + state = { + p: { + k: v.detach().clone() if torch.is_tensor(v) else copy.deepcopy(v) + for k, v in s.items() + } + for p, s in optimizer.state.items() + } + cpu_rng = torch.get_rng_state() + cuda_rng = torch.cuda.get_rng_state(table[0].device) + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(3): + self.eager() + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + self.graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(self.graph): + self.loss, self.grad_norm = self.eager() + torch.cuda.synchronize() + with torch.no_grad(): + for k, v in model.state_dict().items(): + v.copy_(weights[k]) + for param, values in optimizer.state.items(): + before = state.get(param, {}) + for k, v in values.items(): + if torch.is_tensor(v): + if k in before: + v.copy_(before[k]) + else: + v.zero_() + for p in model.parameters(): + if p.grad is not None: + p.grad.zero_() + torch.set_rng_state(cpu_rng) + torch.cuda.set_rng_state(cuda_rng, table[0].device) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, pos, labels = (t[self.index] for t in self.table) + logits = self.model(x, positions=pos) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten()) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + def __call__(self, indices): + self.index.copy_(indices) + self.graph.replay() + return self.loss + + +class EpochStream: + """Uniform shuffled epochs of the combined atomic/composite training set.""" + + def __init__(self, size, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def take(self, n): + parts = [] + while n: + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(n, len(self.remaining)) + parts.append(self.remaining[:count]) + self.remaining = self.remaining[count:] + n -= count + return np.concatenate(parts) + + def state_dict(self): + return { + "size": self.size, + "rng": self.rng.bit_generator.state, + "remaining": self.remaining.copy(), + } + + def load_state_dict(self, state): + assert state["size"] == self.size + self.rng.bit_generator.state = state["rng"] + self.remaining = state["remaining"].copy() + + +@torch.no_grad() +def evaluate_rows(model, rows, device, batch_size=1024): + model.eval() + packed = pack_rows(rows) + answers, stops, losses = [], [], [] + for start in range(0, len(rows), batch_size): + x, pos, labels = ( + torch.as_tensor(t[start : start + batch_size], device=device) for t in packed + ) + logits = model(x, pos) + losses.append( + F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + .view(-1, 2) + .cpu() + .numpy() + ) + answer = logits[:, 0].argmax(-1) + # Actual generated answer is fed back when producing EOS. + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + stop = model(x, pos)[:, 1].argmax(-1) + answers.append(answer.cpu().numpy()) + stops.append(stop.cpu().numpy()) + model.train() + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}, {} + answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) + correct = answer == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": float(correct.mean()), + "accuracy": float((correct & (stop == 1)).mean()), + "nll": float(nll.mean()), + }, {"answer": answer, "stop": stop, "nll": nll, "target": rows[:, -1]} + + +@torch.no_grad() +def two_calls(model, rows, device): + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None} + first = np.c_[rows[:, :2], np.zeros(len(rows), dtype=np.int64)] + _, first_pred = evaluate_rows(model, first, device) + second = np.c_[first_pred["answer"], rows[:, 2], rows[:, 3]] + result, second_pred = evaluate_rows(model, second, device) + result["accuracy"] = float( + ( + (second_pred["answer"] == rows[:, -1]) + & (second_pred["stop"] == 1) + & (first_pred["stop"] == 1) + ).mean() + ) + return result + + +def source_hash(paths): + return {str(p): hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths} + + +def run(spec, world, out, device="cuda:0", resume=False): + """Run a fixed scientific budget. Intermediate evaluations never change training.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + device = torch.device(device) + torch.cuda.set_device(device) + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = SmallGPT(cfg, spec["dropout"]).to(device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + atoms, comps = pack_rows(world["atomic"]), pack_rows(world["train_composite"]) + table = tuple( + torch.as_tensor(np.concatenate([a, c]), device=device) + for a, c in zip(atoms, comps, strict=True) + ) + stream = EpochStream(len(table[0]), spec["stream_seed"]) + counts = {"atomic": 0, "composite": 0} + elapsed_training, elapsed_eval = 0.0, 0.0 + start_step = 0 + checkpoint = out / "latest.pt" + if resume: + state = torch.load(checkpoint, map_location=device, weights_only=False) + assert state["spec"] == spec + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + # load_state_dict replaces the LR tensor; retain the optimizer's live tensor. + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + counts = state["counts"] + elapsed_training = state["elapsed_training"] + elapsed_eval = state["elapsed_eval"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + started = time.perf_counter() + graph = GraphStep(model, opt, table, spec["batch_size"]) + capture_seconds = time.perf_counter() - started + names = ("atomic", "train_composite", "test_composite", "ood_composite") + nparams = sum(p.numel() for p in model.parameters()) + flop_step = matmul_flops(cfg, spec["batch_size"], sequence=4, output_positions=2) + rows_log = [] + if (out / "learning.json").exists(): + rows_log = json.loads((out / "learning.json").read_text()) + if resume: + # A crash can leave a log newer than the atomically replaced checkpoint. + rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) + rows_log.sort(key=lambda r: r["step"]) + if start_step == spec["steps"]: + endpoint = rows_log[-1] + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": endpoint, + "completion_recovered_from_final_checkpoint": True, + }, + ) + write_json( + out / "status.json", + { + "state": "complete", + "step": start_step, + "budget": spec["steps"], + "updated_utc": utc(), + "atomic": endpoint["atomic"]["accuracy"], + "train": endpoint["train_composite"]["accuracy"], + "test": endpoint["test_composite"]["accuracy"], + }, + ) + return rows_log[-1] + + def measure(step, last_loss=None): + nonlocal elapsed_eval + torch.cuda.synchronize() + t0 = time.perf_counter() + row = { + "step": step, + "utc": utc(), + "parameters": nparams, + "training_seconds": elapsed_training, + "capture_seconds": capture_seconds, + "examples": step * spec["batch_size"], + "counts": counts.copy(), + "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * 4, + "supervised_tokens": step * spec["batch_size"] * 2, + "estimated_training_flops": step * flop_step, + "last_batch_loss": last_loss, + } + predictions = {} + for name in names: + row[name], pred = evaluate_rows(model, world[name], device) + predictions.update({name + "_" + k: v for k, v in pred.items()}) + row["two_calls"] = two_calls(model, world["test_composite"], device) + torch.cuda.synchronize() + elapsed_eval += time.perf_counter() - t0 + row["evaluation_seconds"] = elapsed_eval + rows_log.append(row) + write_json(out / "learning.json", rows_log) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + state = { + "step": step, + "spec": spec, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "elapsed_training": elapsed_training, + "elapsed_eval": elapsed_eval, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(checkpoint) + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "complete" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "updated_utc": utc(), + "atomic": row["atomic"]["accuracy"], + "train": row["train_composite"]["accuracy"], + "test": row["test_composite"]["accuracy"], + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + nodes = [s for s in spec["nodes"] if s > start_step] + for end in nodes: + last_loss = None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + ix = stream.take(n * spec["batch_size"]).reshape(n, spec["batch_size"]) + atom_count = int((ix < len(world["atomic"])).sum()) + counts["atomic"] += atom_count + counts["composite"] += ix.size - atom_count + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + last_loss = graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + elapsed_training += time.perf_counter() - t0 + loss_value = float(last_loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at step {end}") + row = measure(end, loss_value) + start_step = end + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": row, + }, + ) + return row diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_depth_bridge.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_depth_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..ca05be9fcd170cee34075ae1aa2fa0c2bcca1e2c --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_depth_bridge.py @@ -0,0 +1,631 @@ +"""Prefix-only causal interventions on frozen grok-depth-v1 checkpoints. + +Donors are selected from world facts before any model is loaded. The only donor +input is its two-token atomic query; second relations and answers never enter the +forward pass that supplies the post-first-block residual state. +""" + +from __future__ import annotations + +import hashlib +import importlib +import json +import platform +import sys +import time +import types +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +CONDITIONS = ( + "baseline", + "identity_r1", + "different_bridge_r1", + "same_bridge_r1", + "different_bridge_h", + "different_bridge_h_r1", + "counterfactual_input", +) +DATA_FIELDS = ("entities", "relations", "degree", "phi", "id_fraction", "id_test_fraction") + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temporary.replace(path) + + +def require(condition, message): + if not condition: + raise AssertionError(message) + + +def _frozen_modules(source_dir, metadata): + """Verify all historical copies, then import exclusively from that snapshot.""" + snapshot = source_dir / "source" + copied = {p.relative_to(snapshot).as_posix(): p for p in snapshot.rglob("*") if p.is_file()} + verified = {} + for original, expected in metadata["files"].items(): + matches = [ + p for rel, p in copied.items() if original == rel or original.endswith("/" + rel) + ] + require(len(matches) == 1, f"missing or ambiguous historical copy: {original}") + path = matches[0] + actual = digest(path) + require(actual == expected, f"historical source hash mismatch: {path}") + verified[path.relative_to(snapshot).as_posix()] = actual + configs = [snapshot / p for p in verified if p.startswith("configs/")] + require(len(configs) == 1, "expected exactly one frozen configuration") + frozen = read_json(configs[0]) + require( + {**frozen["base"], **frozen["runs"][source_dir.name]} == metadata["spec"], + "historical metadata differs from its frozen configuration", + ) + package = "_grok_bridge_source_" + hashlib.sha256(str(source_dir).encode()).hexdigest()[:16] + namespace = types.ModuleType(package) + namespace.__path__ = [str(snapshot / "src/llm_memory_editability")] + sys.modules[package] = namespace + training = importlib.import_module(package + ".grok_depth") + data = importlib.import_module(package + ".grok_depth_data") + return training, data, verified + + +def load_source_run(source_dir, step, device="cuda:0"): + """Return a frozen model/world after source, world and checkpoint consistency checks.""" + source_dir = Path(source_dir).resolve() + metadata = read_json(source_dir / "metadata.json") + spec = metadata["spec"] + require(spec["phase"] == source_dir.parent.name, "historical phase/path mismatch") + training, data, verified = _frozen_modules(source_dir, metadata) + require(step in spec["weight_nodes"], f"unregistered historical weight node {step}") + checkpoint_path = source_dir / f"weights-{step:07d}.pt" + checkpoint_hash = digest(checkpoint_path) + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + require( + checkpoint["spec"] == spec and checkpoint["step"] == step, "checkpoint identity mismatch" + ) + require(digest(checkpoint_path) == checkpoint_hash, "checkpoint changed while loading") + if step == spec["steps"]: + latest = torch.load(source_dir / "latest.pt", map_location="cpu", weights_only=False) + require( + latest["step"] == step and latest["spec"] == spec, "latest checkpoint identity mismatch" + ) + require( + checkpoint["model"].keys() == latest["model"].keys() + and all(torch.equal(v, latest["model"][k]) for k, v in checkpoint["model"].items()), + "endpoint weights differ from latest checkpoint", + ) + del latest + world_path = source_dir / "world.npz" + world_hash = digest(world_path) + with np.load(world_path, allow_pickle=False) as stored: + world = {key: stored[key].copy() for key in stored.files} + world["metadata"] = read_json(source_dir / "world-metadata.json") + require(digest(world_path) == world_hash, "world changed while loading") + audit = data.audit_world(world) + require(audit == read_json(source_dir / "data-audit.json"), "historical world audit mismatch") + require( + audit["dataset_sha256"] == world["metadata"]["dataset_sha256"], + "world content hash mismatch", + ) + rebuilt = data.build_world(spec["world_seed"], **{key: spec[key] for key in DATA_FIELDS}) + require(rebuilt["metadata"] == world["metadata"], "regenerated world metadata mismatch") + for key, array in world.items(): + if key != "metadata": + require(np.array_equal(array, rebuilt[key]), f"regenerated world mismatch: {key}") + cfg = training.ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = training.SmallGPT(cfg, spec["dropout"]).to(device) + model.load_state_dict(checkpoint["model"], strict=True) + model.eval() + for parameter in model.parameters(): + parameter.requires_grad_(False) + provenance = { + "source_dir": str(source_dir), + "source_hashes": verified, + "checkpoint_sha256": checkpoint_hash, + "world_file_sha256": world_hash, + "dataset_sha256": audit["dataset_sha256"], + "world_audit": audit, + "source_metadata_sha256": digest(source_dir / "metadata.json"), + "source_predictions_sha256": digest(source_dir / f"predictions-{step:07d}.npz"), + "world_regenerated_identically": True, + } + return model, world, spec, provenance + + +def _choose(candidates, world_hash, seed, row, kind): + """Content-based uniform deterministic selection; no model input is accepted.""" + if not candidates: + return None + material = json.dumps([world_hash, int(seed), list(map(int, row)), kind], separators=(",", ":")) + rng = np.random.default_rng( + int.from_bytes(hashlib.sha256(material.encode()).digest()[:16], "big") + ) + return sorted(candidates)[int(rng.integers(len(candidates)))] + + +def select_donors(world, seed): + """Select once per test row; preserve all rows, masks and rejection counts. + + Different-bridge candidates share r1, change h/b/t, have ID second facts, + and yield a reserved-test or unused counterfactual. Same-bridge candidates + may change r1; only their bridge, query distinctness and h != original t + matter. No candidate is selected using model behavior. + """ + rows = world["test_composite"] + n = len(rows) + atoms = {tuple(map(int, row)) for row in world["id_atomic"]} + lookup = {(h, r): t for h, r, t in atoms} + held_out = { + tuple(map(int, row)) + for name in ("test_composite", "unused_composite") + for row in world[name] + } + training = {tuple(map(int, row)) for row in world["train_composite"]} + world_hash = world["metadata"]["dataset_sha256"] + out = { + "original_rows": rows.copy(), + "original_bridge": np.full(n, -1, dtype=np.int64), + "different_donor": np.full((n, 3), -1, dtype=np.int64), + "same_donor": np.full((n, 3), -1, dtype=np.int64), + "counterfactual_rows": np.full((n, 4), -1, dtype=np.int64), + "different_valid": np.zeros(n, dtype=bool), + "same_valid": np.zeros(n, dtype=bool), + "different_reason": np.full(n, "", dtype="U64"), + "same_reason": np.full(n, "", dtype="U64"), + "different_candidate_count": np.zeros(n, dtype=np.int64), + "same_candidate_count": np.zeros(n, dtype=np.int64), + "same_relation_control": np.full(n, "missing", dtype="U24"), + "different_nondegenerate": np.zeros(n, dtype=bool), + } + rejection_names = ( + "same_head", + "same_bridge", + "missing_id_second_fact", + "same_tail", + "head_is_answer", + "counterfactual_in_train", + "counterfactual_not_held_out", + ) + for reason in rejection_names: + out["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) + for index, row in enumerate(rows): + h, r1, r2, tail = map(int, row) + bridge = lookup[h, r1] + require(lookup.get((bridge, r2)) == tail, "recipient is not an ID-ID chain") + out["original_bridge"][index] = bridge + candidates = [] + for dh, dr, db in sorted(atoms): + if dr != r1: + continue + dt = lookup.get((db, r2)) + cf = (dh, r1, r2, dt) + reason = ( + "same_head" + if dh == h + else "same_bridge" + if db == bridge + else "missing_id_second_fact" + if dt is None + else "same_tail" + if dt == tail + else "head_is_answer" + if dh in (tail, dt) + else "counterfactual_in_train" + if cf in training + else "counterfactual_not_held_out" + if cf not in held_out + else None + ) + if reason: + out["different_rejected_" + reason][index] += 1 + else: + candidates.append((dh, dr, db, dt)) + donor = _choose(candidates, world_hash, seed, row, "different") + out["different_candidate_count"][index] = len(candidates) + if donor is None: + out["different_reason"][index] = "no_candidate_after_registered_exclusions" + else: + dh, dr, db, dt = donor + out["different_donor"][index] = dh, dr, db + out["counterfactual_rows"][index] = dh, r1, r2, dt + out["different_valid"][index] = True + out["different_reason"][index] = "eligible" + out["different_nondegenerate"][index] = db != dt and db != tail + candidates = [ + (dh, dr, db) + for dh, dr, db in atoms + if db == bridge and (dh, dr) != (h, r1) and dh != tail + ] + same_relation = [candidate for candidate in candidates if candidate[1] == r1] + donor = _choose(same_relation or candidates, world_hash, seed, row[:2], "same") + out["same_candidate_count"][index] = len(candidates) + if donor is None: + out["same_reason"][index] = "no_distinct_id_prefix_with_same_bridge_and_head_not_answer" + else: + out["same_donor"][index] = donor + out["same_valid"][index] = True + out["same_reason"][index] = "eligible" + out["same_relation_control"][index] = "same_r1" if donor[1] == r1 else "different_r1" + return out + + +@torch.no_grad() +def traced_forward( + model, + tokens, + positions=None, + donor_state=None, + patch_positions=(), + identity=False, + return_state=False, +): + """Frozen SmallGPT eval forward, replacing residuals after complete block 0. + + Both attention and MLP in the first block run before replacement. There is + no patch in another block, and final LN/output projection remain untouched. + """ + require(not model.training, "interventions require model.eval()") + require( + donor_state is None or not identity, "identity and donor patches are mutually exclusive" + ) + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + first_state = None + for index, block in enumerate(model.blocks): + z = block.ln1(x) + batch, length, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, length, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=0.0 + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + y + x = x + block.mlp(block.ln2(x)) + if index == 0: + if return_state: + first_state = x.clone() + if donor_state is not None or identity: + x = x.clone() + replacement = x.clone() if identity else donor_state + for position in patch_positions: + x[:, position, :] = replacement[:, position, :] + x = model.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, model.token.weight) + return (logits, first_state) if return_state else logits + + +@torch.no_grad() +def prefix_state(model, prefixes): + """Two informative tokens, padded to the historical four-position shape. + + Both suffix tokens are the fixed PAD token, never a relation or answer. + Causality makes the retained two states independent of these suffixes. + Matching the matrix shapes avoids TF32 kernel-dependent rounding changes. + """ + require(prefixes.ndim == 2 and prefixes.shape[1] == 2, "expected h/r1 prefixes") + padded = F.pad(prefixes, (0, 2), value=0) + _, state = traced_forward(model, padded, return_state=True) + return state[:, :2] + + +@torch.no_grad() +def evaluate_condition( + model, + rows, + device, + batch_size=1024, + donor_prefixes=None, + patch_positions=(), + identity=False, + verify_trace=False, +): + """Answer generation followed by EOS with the generated answer fed back. + + The exact same prefix state is reapplied on the second forward pass. Arrays + are local to the supplied rows; the caller scatters them to the full test set. + """ + n = len(rows) + answers, stops, original_logits = [], [], [] + trace_max_delta, trace_disagreements = 0.0, 0 + prefix_max_delta = 0.0 + for start in range(0, n, batch_size): + selected = rows[start : start + batch_size] + arity = rows.shape[1] + require(arity in (3, 4), "expected atomic or composite rows") + packed = np.zeros((len(selected), 4), dtype=np.int64) + packed[:, :arity] = selected + x = torch.as_tensor(packed, device=device) + pos = torch.as_tensor(np.tile([arity - 2, arity - 1], (len(x), 1)), device=device) + donor_state = None + if donor_prefixes is not None: + prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) + require(prefixes.shape == (len(x), 2), "donor model may receive only h and r1") + donor_state = prefix_state(model, prefixes) + logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) + if verify_trace: + reference = model(x, pos) + trace_max_delta = max(trace_max_delta, float((reference - logits).abs().max())) + trace_disagreements += int((reference.argmax(-1) != logits.argmax(-1)).sum()) + prefix = prefix_state(model, x[:, :2]) + _, whole = traced_forward(model, x, return_state=True) + prefix_max_delta = max(prefix_max_delta, float((prefix - whole[:, :2]).abs().max())) + require( + torch.allclose(prefix, whole[:, :2], atol=1e-4, rtol=1e-4), + "pure-prefix state does not match causal full-input prefix", + ) + answer = logits[:, 0].argmax(-1) + original_logits.append(logits[:, 0].cpu().numpy()) + x[:, arity - 1] = answer + generated_logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) + if verify_trace: + reference = model(x, pos) + trace_max_delta = max( + trace_max_delta, float((reference - generated_logits).abs().max()) + ) + trace_disagreements += int((reference.argmax(-1) != generated_logits.argmax(-1)).sum()) + answers.append(answer.cpu().numpy()) + stops.append(generated_logits[:, 1].argmax(-1).cpu().numpy()) + require(trace_disagreements == 0, "traced forward changes standard-forward discrete outputs") + require(trace_max_delta <= 1e-5, f"traced forward mismatch: {trace_max_delta}") + return { + "answer": np.concatenate(answers) if n else np.empty(0, dtype=np.int64), + "stop": np.concatenate(stops) if n else np.empty(0, dtype=np.int64), + "answer_logits": np.concatenate(original_logits) + if n + else np.empty((0, model.token.num_embeddings), dtype=np.float32), + }, { + "standard_forward_max_logit_delta": trace_max_delta, + "standard_forward_argmax_disagreements": trace_disagreements, + "prefix_vs_full_first_block_max_delta": prefix_max_delta, + "trace_comparison_performed": verify_trace, + } + + +def _metrics(answer, stop, original, cf, selected, cf_valid, total, baseline_answer): + count = int(selected.sum()) + counterfactual = selected & cf_valid + ncf = int(counterfactual.sum()) + correct = answer == original + cf_correct = answer == cf + return { + "n": count, + "total_test_n": total, + "coverage": count / total if total else None, + "original_answer_accuracy": float(correct[selected].mean()) if count else None, + "original_complete_accuracy": float((correct & (stop == 1))[selected].mean()) + if count + else None, + "eos_accuracy": float((stop[selected] == 1).mean()) if count else None, + "answer_change_rate": float((answer[selected] != baseline_answer[selected]).mean()) + if count + else None, + "cf_target_n": ncf, + "cf_answer_accuracy": float(cf_correct[counterfactual].mean()) if ncf else None, + "cf_complete_accuracy": float((cf_correct & (stop == 1))[counterfactual].mean()) + if ncf + else None, + } + + +def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): + """Evaluate all fixed conditions, then expose full and prerequisite subgroups.""" + started = time.perf_counter() + rows = world["test_composite"] + n = len(rows) + different, same = donors["different_valid"], donors["same_valid"] + arrays = {key: value.copy() for key, value in donors.items()} + audits = {} + for condition in CONDITIONS: + mask = ( + same + if condition == "same_bridge_r1" + else different + if condition.startswith("different_") or condition == "counterfactual_input" + else np.ones(n, dtype=bool) + ) + eval_rows = ( + donors["counterfactual_rows"][mask] + if condition == "counterfactual_input" + else rows[mask] + ) + donor_key = "same_donor" if condition == "same_bridge_r1" else "different_donor" + donor_prefix = donors[donor_key][mask, :2] if "bridge_" in condition else None + positions = ( + (0, 1) + if condition == "different_bridge_h_r1" + else (0,) + if condition == "different_bridge_h" + else (1,) + ) + result, audit = evaluate_condition( + model, + eval_rows, + device, + batch_size, + donor_prefix, + positions, + condition == "identity_r1", + condition == "baseline", + ) + audits[condition] = audit + answer = np.full(n, -1, dtype=np.int64) + stop = np.full(n, -1, dtype=np.int64) + answer[mask], stop[mask] = result["answer"], result["stop"] + arrays[condition + "_answer"], arrays[condition + "_stop"] = answer, stop + arrays[condition + "_valid"] = mask + original_logit = result["answer_logits"][np.arange(mask.sum()), rows[mask, -1]] + cf_logit = np.full(n, np.nan, dtype=np.float32) + cf_local = different[mask] + cf_logit[mask.nonzero()[0][cf_local]] = ( + result["answer_logits"][ + np.flatnonzero(cf_local), donors["counterfactual_rows"][mask][cf_local, -1] + ] + - original_logit[cf_local] + ) + arrays[condition + "_cf_minus_original_logit"] = cf_logit + for column in ("answer", "stop"): + require( + np.array_equal(arrays["baseline_" + column], arrays["identity_r1_" + column]), + f"identity patch changed {column}", + ) + if len(model.blocks) == 1: + for condition in ( + "different_bridge_r1", + "same_bridge_r1", + "different_bridge_h", + "different_bridge_h_r1", + ): + valid = arrays[condition + "_valid"] + require( + np.array_equal( + arrays["baseline_" + column][valid], arrays[condition + "_" + column][valid] + ), + f"one-layer structural negative control changed {condition}.{column}", + ) + baseline_correct = (arrays["baseline_answer"] == rows[:, -1]) & (arrays["baseline_stop"] == 1) + cf_correct = ( + different + & (arrays["counterfactual_input_answer"] == donors["counterfactual_rows"][:, -1]) + & (arrays["counterfactual_input_stop"] == 1) + ) + atomic_rows = { + "different_first": (donors["different_donor"], different), + "counterfactual_second": ( + np.c_[ + donors["different_donor"][:, 2], rows[:, 2], donors["counterfactual_rows"][:, -1] + ], + different, + ), + "same_first": (donors["same_donor"], same), + } + atomic_scores = {} + atomic_correct = {} + for name, (facts, mask) in atomic_rows.items(): + prediction, _ = evaluate_condition(model, facts[mask], device, batch_size) + answer = np.full(n, -1, dtype=np.int64) + stop = np.full(n, -1, dtype=np.int64) + answer[mask], stop[mask] = prediction["answer"], prediction["stop"] + arrays["atomic_" + name + "_rows"] = facts.copy() + arrays["atomic_" + name + "_answer"] = answer + arrays["atomic_" + name + "_stop"] = stop + arrays["atomic_" + name + "_valid"] = mask.copy() + correct = mask & (answer == facts[:, -1]) + atomic_correct[name] = correct & (stop == 1) + count = int(mask.sum()) + atomic_scores[name] = { + "n": count, + "total_test_n": n, + "coverage": count / n if n else None, + "answer_accuracy": float(correct[mask].mean()) if count else None, + "complete_accuracy": float(atomic_correct[name][mask].mean()) if count else None, + "eos_accuracy": float((stop[mask] == 1).mean()) if count else None, + } + groups = { + "all_test": np.ones(n, dtype=bool), + "different_donor_available": different, + "same_donor_available": same, + "baseline_and_counterfactual_complete_correct": baseline_correct & cf_correct, + "different_bridge_nondegenerate": donors["different_nondegenerate"], + "same_bridge_same_r1": same & (donors["same_relation_control"] == "same_r1"), + "same_bridge_different_r1": same & (donors["same_relation_control"] == "different_r1"), + "both_counterfactual_atomic_facts_complete_correct": atomic_correct["different_first"] + & atomic_correct["counterfactual_second"], + } + for group, mask in groups.items(): + arrays["subset_" + group] = mask + scores = { + group: { + "subset_n": int(mask.sum()), + "total_test_n": n, + "coverage": float(mask.mean()) if n else None, + "conditions": { + condition: _metrics( + arrays[condition + "_answer"], + arrays[condition + "_stop"], + rows[:, -1], + donors["counterfactual_rows"][:, -1], + mask & arrays[condition + "_valid"], + different, + n, + arrays["baseline_answer"], + ) + for condition in CONDITIONS + }, + } + for group, mask in groups.items() + } + summary = { + "conditions": list(CONDITIONS), + "scores": scores, + "atomic_preconditions": atomic_scores, + "donor_coverage": { + "total_test_n": n, + "different_n": int(different.sum()), + "same_n": int(same.sum()), + "different_reasons": dict(Counter(donors["different_reason"].tolist())), + "same_reasons": dict(Counter(donors["same_reason"].tolist())), + "same_relation_control": dict(Counter(donors["same_relation_control"].tolist())), + }, + "engineering_checks": { + "identity_predictions_equal": True, + "one_layer_all_early_position_patch_predictions_equal": True + if len(model.blocks) == 1 + else None, + "trace": audits["baseline"], + "eos_uses_generated_answer_and_reapplies_patch": True, + "donor_nonpadding_input_tokens": 2, + "donor_forward_sequence_length": 4, + "donor_pad_token": 0, + }, + "evaluation_seconds": time.perf_counter() - started, + } + return summary, arrays + + +def environment(device): + return { + "python": platform.python_version(), + "platform": platform.platform(), + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "device": str(device), + "gpu": torch.cuda.get_device_name(torch.device(device)) + if str(device).startswith("cuda") + else None, + "cuda_matmul_tf32": torch.backends.cuda.matmul.allow_tf32, + "cudnn_tf32": torch.backends.cudnn.allow_tf32, + "precision": "FP32 parameters and evaluation; TF32 flags recorded explicitly", + } diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_depth_data.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_depth_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8696c3ffe204466f57619157a3f47739f899c6c4 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_depth_data.py @@ -0,0 +1,281 @@ +"""Symbolic composition worlds adapted from GrokkedTransformer/composition.ipynb. + +Source: https://github.com/OSU-NLP-Group/GrokkedTransformer +Revision: 734ca654ec7a71dd6737d640407fac14491d538c (MIT). + +The graph, atomic ID/OOD split, reserved ID test chains, and phi downsampling +follow the authors' construction. Differences: integer tokens replace text; +randomness is local and seeded; atomic ordering is stable; graph size and the +reserved ID-test fraction are configurable. Unselected ID chains are returned +for audit only. No graph is regenerated to improve OOD counts or model results. + +Adapted source license: +MIT License +Copyright (c) 2024 OSU Natural Language Processing + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +PAD_TOKEN = 0 +EOS_TOKEN = 1 +ENTITY_OFFSET = 2 +SOURCE_URL = "https://github.com/OSU-NLP-Group/GrokkedTransformer" +SOURCE_COMMIT = "734ca654ec7a71dd6737d640407fac14491d538c" +ATOMIC_SPLITS = ("atomic", "id_atomic", "ood_atomic") +COMPOSITE_SPLITS = ( + "train_composite", + "test_composite", + "ood_composite", + "unused_composite", +) + + +def _array(rows: list, columns: int) -> np.ndarray: + return np.asarray(rows, dtype=np.int64).reshape(-1, columns) + + +def build_world( + seed: int, + entities: int = 128, + relations: int = 16, + degree: int = 8, + phi: float = 8.0, + id_fraction: float = 0.95, + id_test_fraction: float = 0.005, +) -> dict: + """Return atomic ``[h,r,t]`` and composite ``[h,r1,r2,t]`` int64 arrays. + + All atomics belong in training, including those labelled OOD. OOD refers + to *composition experience*: neither constituent of an OOD composite is + allowed in composite training. Mixed ID/OOD chains are excluded. The + test set is reserved before phi downsampling; unused ID chains are never + automatically reassigned to test. ``phi`` is relative to ID atomics, as in + the source. Requests larger than the available training pool are capped + and explicitly recorded. Empty test sets are retained and reported. + + Query tokens are every column except the last; the last is the entity + answer. EOS supervision, padding, and loss masks belong to the trainer. + """ + for name, value in (("entities", entities), ("relations", relations), ("degree", degree)): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 1: + raise ValueError(f"{name} must be a positive integer") + if degree > relations: + raise ValueError("degree cannot exceed relations") + if not math.isfinite(phi) or phi < 0: + raise ValueError("phi must be finite and nonnegative") + if not math.isfinite(id_fraction) or not 0 <= id_fraction <= 1: + raise ValueError("id_fraction must be in [0, 1]") + if not math.isfinite(id_test_fraction) or not 0 <= id_test_fraction <= 1: + raise ValueError("id_test_fraction must be in [0, 1]") + + # RandomState keeps the source's NumPy draw family, without global RNG use. + rng = np.random.RandomState(seed) + relation_offset = ENTITY_OFFSET + entities + rows = [] + outgoing = [[] for _ in range(entities)] + for head_index in range(entities): + selected = rng.choice(relations, size=degree, replace=False) + for relation_index in selected: + tail_index = int(rng.randint(entities)) + edge = ( + head_index + ENTITY_OFFSET, + int(relation_index) + relation_offset, + tail_index + ENTITY_OFFSET, + ) + outgoing[head_index].append(len(rows)) + rows.append(edge) + atomic = _array(rows, 3) + ood_count = round(len(atomic) * (1 - id_fraction)) + ood_mask = np.zeros(len(atomic), dtype=bool) + ood_mask[rng.choice(len(atomic), size=ood_count, replace=False)] = True + + eligible, test, ood = [], [], [] + mixed_count = 0 + for first_index, (head, relation1, bridge) in enumerate(atomic): + for second_index in outgoing[int(bridge) - ENTITY_OFFSET]: + _, relation2, tail = atomic[second_index] + row = (head, relation1, relation2, tail) + first_ood, second_ood = ood_mask[first_index], ood_mask[second_index] + if first_ood and second_ood: + ood.append(row) + elif first_ood or second_ood: + mixed_count += 1 + elif rng.uniform() > id_test_fraction: + eligible.append(row) + else: + test.append(row) + + requested_count = round(phi * int((~ood_mask).sum())) + train_count = min(requested_count, len(eligible)) + # Source choose() returns the full pool unchanged when it is saturated. + indices = ( + np.arange(len(eligible)) + if train_count == len(eligible) + else rng.choice(len(eligible), size=train_count, replace=False) + ) + eligible_array = _array(eligible, 4) + selected_mask = np.zeros(len(eligible), dtype=bool) + selected_mask[indices] = True + world = { + "atomic": atomic, + "id_atomic": atomic[~ood_mask], + "ood_atomic": atomic[ood_mask], + "train_composite": eligible_array[indices], + "test_composite": _array(test, 4), + "ood_composite": _array(ood, 4), + "unused_composite": eligible_array[~selected_mask], + "metadata": { + "seed": int(seed), + "entities": int(entities), + "relations": int(relations), + "degree": int(degree), + "phi_requested": float(phi), + "id_fraction": float(id_fraction), + "id_test_fraction": float(id_test_fraction), + "pad_token": PAD_TOKEN, + "eos_token": EOS_TOKEN, + "entity_offset": ENTITY_OFFSET, + "relation_offset": int(relation_offset), + "vocab_size": int(relation_offset + relations), + "train_composite_requested": int(requested_count), + "train_composite_capped": requested_count > len(eligible), + "phi_actual": train_count / max(int((~ood_mask).sum()), 1), + "mixed_composite_excluded": mixed_count, + "source_url": SOURCE_URL, + "source_commit": SOURCE_COMMIT, + "source_file": "composition.ipynb", + "source_license": "MIT", + "construction_differences": [ + "integer tokens and local seeded RNG", + "stable atomic ordering instead of Python set iteration", + "configurable graph size and ID-test reserve fraction", + "all evaluation rows retained instead of sampling at most 3000", + ], + }, + } + audit = audit_world(world) + world["metadata"]["counts"] = audit["counts"] + world["metadata"]["dataset_sha256"] = audit["dataset_sha256"] + world["metadata"]["warnings"] = audit["warnings"] + return world + + +def audit_world(world: dict) -> dict: + """Validate token ranges, graph truth, exhaustive partitions and no leakage. + + Raises ValueError on a broken contract; zero-sized test sets and capped + training pools are valid and surfaced as warnings, never resampled. + """ + metadata = world["metadata"] + entities, relations, degree = (int(metadata[x]) for x in ("entities", "relations", "degree")) + relation_offset = entities + ENTITY_OFFSET + digest = hashlib.sha256() + counts = {} + tuples = {} + for name in ATOMIC_SPLITS + COMPOSITE_SPLITS: + array = world[name] + columns = 3 if name in ATOMIC_SPLITS else 4 + if not isinstance(array, np.ndarray) or array.dtype != np.int64: + raise ValueError(f"{name} must be an int64 numpy array") + if array.ndim != 2 or array.shape[1] != columns: + raise ValueError(f"{name} must have {columns} columns") + for column in (0, columns - 1): + if np.any(array[:, column] < ENTITY_OFFSET) or np.any( + array[:, column] >= relation_offset + ): + raise ValueError(f"{name} has an invalid entity token") + if np.any(array[:, 1:-1] < relation_offset) or np.any( + array[:, 1:-1] >= relation_offset + relations + ): + raise ValueError(f"{name} has an invalid relation token") + rows = {tuple(map(int, row)) for row in array} + if len(rows) != len(array) or len({row[:-1] for row in rows}) != len(rows): + raise ValueError(f"{name} has duplicate or conflicting queries") + tuples[name] = rows + counts[name] = len(array) + digest.update(name.encode()) + digest.update(np.asarray(array.shape, dtype="= threshold for row in triple): + row = triple[0] + result.update( + reached=True, + step=row["step"], + confirmed_at_step=triple[-1]["step"], + previous_evaluation_step=rows[i - 1]["step"] if i else None, + examples=row["examples"], + atomic_exposures=row["counts"]["atomic"] / counts["atomic"], + composite_exposures=row["counts"]["composite"] / counts["train_composite"], + dataset_passes=row["examples"] / (counts["atomic"] + counts["train_composite"]), + estimated_training_flops=row["estimated_training_flops"], + effective_input_tokens=row["effective_input_tokens"], + supervised_tokens=row["supervised_tokens"], + ) + break + return result + + +def verify_files(root, expected): + for relative, sha in expected.items(): + assert digest(root / relative) == sha, f"Frozen input changed: {relative}" diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_data.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..18cae2dbd6dfdd997883935619a80811eede27d0 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_data.py @@ -0,0 +1,346 @@ +"""Audited data and fixed atomic/composite exposure for loop-depth comparisons. + +The graph, truth, complete-query holdout and phi sampling are inherited from +``grok_multihop_data``. Changing the atomic ID fraction is an explicit design +choice; no graph is regenerated in response to diagnostics or model scores. +""" + +from __future__ import annotations + +import copy +from collections.abc import Mapping + +import numpy as np + +from . import grok_multihop_data as multihop + +SPLITS = multihop.SPLITS +DATA_DEFAULTS = { + "hops": 2, + "entities": 128, + "relations": 16, + "degree": 8, + "phi": 6.0, + "id_fraction": 0.95, + "id_test_fraction": 0.1, + "evaluation_size": 1024, +} + + +def build_world(spec: Mapping) -> dict: + """Adapt a flat run specification while retaining the historical world API. + + ``world_seed`` (or ``seed``) is required. Unrelated model/training keys are + ignored. The default atomic ID/OOD fraction remains 95/5; use an explicit + ``id_fraction=0.75`` for the new composition-experience comparison. + + ``relevant_atomic_indices[split][i, j]`` identifies query i's true hop-j + fact in ``world['atomic']``. These truth indices are evaluation artifacts; + training must only use the original atomic and train-composite rows. + """ + if "world_seed" not in spec and "seed" not in spec: + raise ValueError("spec must contain world_seed or seed") + seed = spec.get("world_seed", spec.get("seed")) + fields = {key: spec.get(key, default) for key, default in DATA_DEFAULTS.items()} + world = multihop.build_world(seed, **fields) + world["relevant_atomic_indices"] = { + name: query_atomic_indices(world, world[name]) for name in SPLITS + } + world["metadata"]["loop_data_diagnostics"] = data_diagnostics(world) + world["metadata"]["loop_data_contract"] = { + "constructor": "grok_multihop_data.build_world", + "world_selection": "fixed supplied seed; no diagnostic or model-based selection", + "all_atomic_rows_are_training_facts": True, + "ood_definition": "all constituent facts absent from composite training by split", + "query_fact_indices": "evaluation truth only; no intermediate-entity supervision", + "suffix_statistics": "within-split descriptive counts; not fitted or held-out predictors", + } + audit_world(world) + return world + + +def query_atomic_indices(world: dict, rows: np.ndarray) -> np.ndarray: + """Return true constituent fact indices, including [N, 1] for atomics.""" + meta = world["metadata"] + _, edges = multihop.path_details( + rows, world["atomic"], int(meta["entities"]), int(meta["relations"]) + ) + return edges + + +def audit_world(world: dict) -> dict: + """Independently verify truth, ID/OOD partitions and recorded fact indices. + + The reused auditor checks truth by graph traversal and counts all-ID and + all-OOD paths by dynamic programming, independently of path construction. + Neither correct-looking diagnostics nor a saved metadata hash substitutes + for those checks. + """ + result = multihop.audit_world(world) + recorded = world.get("relevant_atomic_indices") + if recorded is not None: + if set(recorded) != set(SPLITS): + raise ValueError("Relevant atomic indices must cover every data split") + for name in SPLITS: + expected = query_atomic_indices(world, world[name]) + if ( + not isinstance(recorded[name], np.ndarray) + or recorded[name].dtype != np.int64 + or not np.array_equal(recorded[name], expected) + ): + raise ValueError(f"Incorrect relevant atomic indices: {name}") + if result["dataset_sha256"] != world["metadata"].get("dataset_sha256"): + raise ValueError("Recorded dataset hash disagrees with actual data") + return {**result, "relevant_atomic_indices_checked": recorded is not None} + + +def suffix_target_diagnostics(rows: np.ndarray) -> list[dict]: + """Describe target concentration after omitting the head and prefix relations. + + The empirical modal fraction sums each suffix group's largest target count + and divides by query count. It uses the same rows to count and summarize; + singleton suffixes score one automatically. It is not a model-independent + generalization bound, a learned baseline, or proof that heads are unnecessary. + """ + results = [] + n = len(rows) + for length in range(1, rows.shape[1] - 1): + suffix = rows[:, -(length + 1) : -1] + if not n: + results.append( + { + "suffix_relation_count": length, + "groups": 0, + "empirical_modal_target_fraction": None, + "single_target_group_query_fraction": None, + "singleton_group_query_fraction": None, + "multi_query_groups": 0, + "multi_query_coverage_fraction": None, + "multi_query_empirical_modal_target_fraction": None, + "multi_target_groups": 0, + "same_suffix_different_target_example": None, + } + ) + continue + _, groups, totals = np.unique(suffix, axis=0, return_inverse=True, return_counts=True) + pairs, pair_counts = np.unique(np.c_[groups, rows[:, -1]], axis=0, return_counts=True) + maxima = np.zeros(len(totals), dtype=np.int64) + np.maximum.at(maxima, pairs[:, 0], pair_counts) + multi = totals > 1 + multi_n = int(totals[multi].sum()) + multi_target = maxima != totals + example = None + if multi_target.any(): + # Deterministic first lexicographic suffix with incompatible targets. + group = int(np.flatnonzero(multi_target)[0]) + members = np.flatnonzero(groups == group) + first = members[0] + second = members[np.flatnonzero(rows[members, -1] != rows[first, -1])[0]] + example = [rows[first].tolist(), rows[second].tolist()] + results.append( + { + "suffix_relation_count": length, + "groups": len(totals), + "empirical_modal_target_fraction": float(maxima.sum() / n), + "single_target_group_query_fraction": float(totals[maxima == totals].sum() / n), + "singleton_group_query_fraction": float((totals == 1).sum() / n), + "multi_query_groups": int(multi.sum()), + "multi_query_coverage_fraction": float(multi_n / n), + "multi_query_empirical_modal_target_fraction": ( + float(maxima[multi].sum() / multi_n) if multi_n else None + ), + "multi_target_groups": int(multi_target.sum()), + "same_suffix_different_target_example": example, + } + ) + return results + + +def majority_tail_diagnostics(rows: np.ndarray) -> dict: + """Report the empirical within-split majority target, without fitting a model.""" + if not len(rows): + return {"target_token": None, "count": 0, "fraction": None, "distinct_targets": 0} + targets, counts = np.unique(rows[:, -1], return_counts=True) + index = int(counts.argmax()) + return { + "target_token": int(targets[index]), + "count": int(counts[index]), + "fraction": float(counts[index] / len(rows)), + "distinct_targets": len(targets), + } + + +def data_diagnostics(world: dict) -> dict: + """Pure data coverage and target distributions; never evaluate a predictor.""" + atomic_n = len(world["atomic"]) + indices = world.get("relevant_atomic_indices") + if indices is None: + indices = {name: query_atomic_indices(world, world[name]) for name in SPLITS} + training_counts = np.bincount(indices["train_composite"].ravel(), minlength=atomic_n) + id_facts = np.zeros(atomic_n, dtype=bool) + id_facts[indices["id_atomic"].ravel()] = True + training_majority = majority_tail_diagnostics(world["train_composite"]) + per_split = {} + for name in SPLITS: + rows, edges = world[name], indices[name] + distinct = np.unique(edges) + trained = training_counts[edges] > 0 + all_id, all_ood = id_facts[edges].all(axis=1), (~id_facts[edges]).all(axis=1) + per_split[name] = { + "n": len(rows), + "unique_relevant_atomic_facts": len(distinct), + "relevant_atomic_fact_coverage_of_graph": len(distinct) / atomic_n, + "all_relevant_facts_in_atomic_training_fraction": 1.0 if len(rows) else None, + "all_relevant_facts_in_composite_training_n": int(trained.all(axis=1).sum()), + "any_relevant_fact_in_composite_training_n": int(trained.any(axis=1).sum()), + "relevant_fact_occurrences_seen_in_composite_training_fraction": ( + float(trained.mean()) if edges.size else None + ), + "all_id_queries": int(all_id.sum()), + "all_ood_queries": int(all_ood.sum()), + "mixed_queries": int((~all_id & ~all_ood).sum()), + "unique_relevant_facts_by_hop": [ + len(np.unique(edges[:, j])) for j in range(edges.shape[1]) + ], + "within_split_majority_tail": majority_tail_diagnostics(rows), + "train_composite_majority_tail_fraction": ( + float((rows[:, -1] == training_majority["target_token"]).mean()) + if len(rows) and training_majority["target_token"] is not None + else None + ), + "suffix_without_head": suffix_target_diagnostics(rows), + } + return { + "interpretation": { + "atomic_coverage": "data availability only; does not establish model mastery", + "ood": "all facts are atomic training facts; none has composite-training experience", + "suffix": ( + "empirical within-split target concentration; singleton suffixes score 1; " + "not a predictor, generalization bound, or evidence that the model ignores head" + ), + "majority": "within-split descriptive ceiling plus fixed training-majority fraction", + }, + "atomic_facts": atomic_n, + "id_facts": int(id_facts.sum()), + "ood_facts": int((~id_facts).sum()), + "id_facts_seen_in_composite_training": int((training_counts[id_facts] > 0).sum()), + "ood_facts_seen_in_composite_training": int((training_counts[~id_facts] > 0).sum()), + "train_composite_fact_occurrence_counts": training_counts.tolist(), + "splits": per_split, + } + + +class _EpochStream: + """NumPy-only shuffled epochs, with the existing EpochStream draw convention.""" + + def __init__(self, size: int, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def take(self, n: int) -> np.ndarray: + if not n: + return np.empty(0, dtype=np.int64) + parts = [] + while n: + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(n, len(self.remaining)) + parts.append(self.remaining[:count]) + self.remaining = self.remaining[count:] + n -= count + return np.concatenate(parts) + + def state_dict(self) -> dict: + return { + "size": self.size, + "rng": copy.deepcopy(self.rng.bit_generator.state), + "remaining": self.remaining.copy(), + } + + def load_state_dict(self, state: dict): + if state["size"] != self.size: + raise ValueError("Epoch size mismatch") + remaining = np.asarray(state["remaining"]) + if ( + remaining.ndim != 1 + or remaining.dtype != np.int64 + or np.any((remaining < 0) | (remaining >= self.size)) + or len(np.unique(remaining)) != len(remaining) + ): + raise ValueError("Invalid remaining epoch indices") + self.rng.bit_generator.state = copy.deepcopy(state["rng"]) + self.remaining = remaining.copy() + + +class StratifiedStream: + """Fixed composition per batch over the table [atomics; train_composites]. + + Atomic, composite and interleaving draws use independent RNGs. Thus changing + phi or the composite pool cannot change the atomic sequence or its batch + positions. Individual strata use shuffled epochs and may cross an epoch + boundary within one batch. No evaluation data enters either stream. + """ + + def __init__( + self, atomic_size: int, composite_size: int, batch_size: int, n_atomic: int, seed: int + ): + fields = { + "atomic_size": atomic_size, + "composite_size": composite_size, + "batch_size": batch_size, + "n_atomic": n_atomic, + } + for name, value in fields.items(): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 0: + raise ValueError(f"{name} must be a nonnegative integer") + if batch_size < 1 or n_atomic > batch_size: + raise ValueError("Require batch_size > 0 and 0 <= n_atomic <= batch_size") + if (n_atomic and not atomic_size) or (batch_size > n_atomic and not composite_size): + raise ValueError("A sampled stratum cannot be empty") + self.atomic_size, self.composite_size = int(atomic_size), int(composite_size) + self.batch_size, self.n_atomic = int(batch_size), int(n_atomic) + self.atomic = _EpochStream(atomic_size, np.random.SeedSequence([int(seed), 145101])) + self.composite = _EpochStream(composite_size, np.random.SeedSequence([int(seed), 145102])) + self.interleave = np.random.default_rng(np.random.SeedSequence([int(seed), 145103])) + self.batches = 0 + + def take(self, n: int | None = None) -> np.ndarray: + if n is not None and n != self.batch_size: + raise ValueError("StratifiedStream only emits its configured batch_size") + indices = np.r_[ + self.atomic.take(self.n_atomic), + self.composite.take(self.batch_size - self.n_atomic) + self.atomic_size, + ] + self.batches += 1 + return indices[self.interleave.permutation(self.batch_size)] + + def state_dict(self) -> dict: + return { + "version": 1, + "atomic_size": self.atomic_size, + "composite_size": self.composite_size, + "batch_size": self.batch_size, + "n_atomic": self.n_atomic, + "atomic": self.atomic.state_dict(), + "composite": self.composite.state_dict(), + "interleave_rng": copy.deepcopy(self.interleave.bit_generator.state), + "batches": self.batches, + } + + def load_state_dict(self, state: dict): + if state.get("version") != 1: + raise ValueError("Unsupported StratifiedStream state version") + for name in ("atomic_size", "composite_size", "batch_size", "n_atomic"): + if state[name] != getattr(self, name): + raise ValueError(f"StratifiedStream {name} mismatch") + atomic, composite = copy.deepcopy(self.atomic), copy.deepcopy(self.composite) + interleave = copy.deepcopy(self.interleave) + atomic.load_state_dict(state["atomic"]) + composite.load_state_dict(state["composite"]) + interleave.bit_generator.state = copy.deepcopy(state["interleave_rng"]) + batches = state["batches"] + if not isinstance(batches, int) or batches < 0: + raise ValueError("Invalid completed batch count") + self.atomic, self.composite, self.interleave = atomic, composite, interleave + self.batches = batches diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_mechanism.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd1ad614952efa432b820d8f26f1e282657a947 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_mechanism.py @@ -0,0 +1,549 @@ +"""Prefix-only component interventions at every executed Transformer block. + +The recipient block runs normally before mixing cached attention and MLP +increments at r1. The current block's MLP is never recomputed after mixing. +Only later blocks consume the intervention. Donors are graph-selected before +evaluating the model and receive only [head, r1] followed by fixed PAD tokens. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections import Counter, defaultdict +from numbers import Integral + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_multihop import pack_rows + +COMPONENTS = ("attention", "mlp", "both", "full") +SPLITS = ("test_composite", "test_full_composite", "ood_composite") +TRACE_FIELDS = ("input", "attention", "mlp", "residual") + + +def _choose(candidates, world_hash, seed, row, family): + if not candidates: + return None + material = json.dumps([world_hash, int(seed), list(map(int, row)), family]) + index = int.from_bytes(hashlib.sha256(material.encode()).digest(), "big") % len(candidates) + return sorted(candidates)[index] + + +def _path(head, relations, graph): + edges = [] + for relation in relations: + fact = graph.get((int(head), int(relation))) + if fact is None: + return None + head, index = fact + edges.append(index) + return int(head), tuple(edges) + + +def select_donors(world, seed, split="test_composite"): + """Select same-r1 donors using only truth and split membership. + + ID recipients and every donor-path fact are restricted to ID facts. OOD + recipients and donor paths analogously use only OOD facts. Different-bridge + paths must change the target and their complete queries must be untrained. + Same-bridge paths may be trained; their split is saved for separate scoring. + Rows without donors remain present with explicit masks and reasons. + """ + if split not in SPLITS: + raise ValueError(f"split must be one of {SPLITS}") + rows = world[split] + n, hops = len(rows), rows.shape[1] - 2 + if not 2 <= hops <= 4: + raise ValueError("Interventions require two-, three- or four-hop rows") + atom_index = {tuple(map(int, row)): i for i, row in enumerate(world["atomic"])} + atomic_split = "ood_atomic" if split == "ood_composite" else "id_atomic" + graph = { + (int(h), int(r)): (int(t), atom_index[int(h), int(r), int(t)]) + for h, r, t in world[atomic_split] + } + by_relation = defaultdict(list) + for (head, relation), (tail, _) in graph.items(): + by_relation[relation].append((head, relation, tail)) + training = {tuple(map(int, row[:-1])) for row in world["train_composite"]} + reserved = {tuple(map(int, row[:-1])) for row in world["test_full_composite"]} + result = { + "split": np.asarray(split), + "atomic_split": np.asarray(atomic_split), + "original_rows": rows.copy(), + "original_bridge": np.full(n, -1, dtype=np.int64), + "original_atomic_indices": np.full((n, hops), -1, dtype=np.int64), + } + for family in ("different", "same"): + result.update( + { + family + "_donor": np.full((n, 3), -1, dtype=np.int64), + family + "_counterfactual_rows": np.full_like(rows, -1), + family + "_atomic_indices": np.full((n, hops), -1, dtype=np.int64), + family + "_valid": np.zeros(n, dtype=bool), + family + "_candidate_count": np.zeros(n, dtype=np.int64), + family + "_reason": np.full(n, "no_eligible_same_relation_path", dtype="U64"), + family + "_counterfactual_split": np.full(n, "missing", dtype="U16"), + } + ) + reasons = ( + "same_head", + "same_bridge", + "missing_successor", + "same_target", + "head_is_answer", + "trained_counterfactual", + ) + for reason in reasons: + result["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) + for i, row in enumerate(rows): + head, r1, target = int(row[0]), int(row[1]), int(row[-1]) + original = _path(head, row[1:-1], graph) + if original is None or original[0] != target: + raise ValueError(f"Recipient is not a true all-{atomic_split} path") + bridge = graph[head, r1][0] + result["original_bridge"][i] = bridge + result["original_atomic_indices"][i] = original[1] + candidates = {"different": [], "same": []} + for dh, dr, db in by_relation[r1]: + continuation = _path(dh, row[1:-1], graph) + if continuation is None: + reason = "missing_successor" + else: + dt, edges = continuation + query = (dh, *map(int, row[1:-1])) + if dh != head and db == bridge and dh != target: + candidates["same"].append((dh, dr, db, dt, edges)) + reason = ( + "same_head" + if dh == head + else "same_bridge" + if db == bridge + else "same_target" + if dt == target + else "head_is_answer" + if dh in (target, dt) + else "trained_counterfactual" + if query in training + else None + ) + if reason is None: + candidates["different"].append((dh, dr, db, dt, edges)) + if reason: + result["different_rejected_" + reason][i] += 1 + for family in ("different", "same"): + choices = candidates[family] + result[family + "_candidate_count"][i] = len(choices) + donor = _choose(choices, world["metadata"]["dataset_sha256"], seed, row, family) + if donor is None: + continue + dh, dr, db, dt, edges = donor + cf = (dh, *map(int, row[1:-1]), dt) + result[family + "_donor"][i] = dh, dr, db + result[family + "_counterfactual_rows"][i] = cf + result[family + "_atomic_indices"][i] = edges + result[family + "_valid"][i] = True + result[family + "_reason"][i] = "eligible" + result[family + "_counterfactual_split"][i] = ( + "ood" + if split == "ood_composite" + else "train" + if cf[:-1] in training + else "reserved_test" + if cf[:-1] in reserved + else "unused" + ) + return result + + +def executed_blocks(model): + return list(model.iter_blocks()) if hasattr(model, "iter_blocks") else list(model.blocks) + + +@torch.no_grad() +def traced_forward( + model, + tokens, + positions=None, + *, + patch_layer=None, + component="both", + donor_trace=None, + identity=False, + return_trace=False, +): + """Run eval forward, optionally mixing one executed layer's r1 state. + + Trace fields contain only position r1, with shape [batch, width]. For a + component patch the output is (recipient input + mixed A) + mixed M. Full + replacement also changes the incoming residual, so it equals replacing A + and M only at execution layer zero for same-r1 donors, not at later layers. + """ + if model.training: + raise ValueError("Interventions require model.eval()") + blocks = executed_blocks(model) + if component not in COMPONENTS: + raise ValueError(f"component must be one of {COMPONENTS}") + if patch_layer is not None and ( + isinstance(patch_layer, bool) + or not isinstance(patch_layer, Integral) + or not 0 <= patch_layer < len(blocks) + ): + raise ValueError("patch_layer must index an executed block") + if identity and donor_trace is not None: + raise ValueError("Identity and donor patches are mutually exclusive") + if (donor_trace is not None or identity) != (patch_layer is not None): + raise ValueError("A patch layer requires exactly one donor or identity patch") + if donor_trace is not None and len(donor_trace) != len(blocks): + raise ValueError("Donor trace must cover every executed layer") + if tokens.shape[1] < 2: + raise ValueError("The r1 position requires at least two tokens") + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + trace = [] + for layer, block in enumerate(blocks): + z = block.ln1(x) + batch, length, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, length, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + a = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=0.0, + ) + a = attention.proj(a.transpose(1, 2).reshape(batch, length, width)) + m = block.mlp(block.ln2(x + a)) + residual = (x + a) + m + current = { + "input": x[:, 1].clone(), + "attention": a[:, 1].clone(), + "mlp": m[:, 1].clone(), + "residual": residual[:, 1].clone(), + } + if return_trace: + trace.append(current) + if layer == patch_layer: + donor = current if identity else donor_trace[layer] + if any(donor[key].shape != current[key].shape for key in TRACE_FIELDS): + raise ValueError("Donor trace has incompatible batch or width") + if component == "full": + replacement = donor["residual"] + else: + mixed_a = donor["attention"] if component in ("attention", "both") else a[:, 1] + mixed_m = donor["mlp"] if component in ("mlp", "both") else m[:, 1] + replacement = (x[:, 1] + mixed_a) + mixed_m + residual = residual.clone() + residual[:, 1] = replacement + x = residual + x = model.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, model.token.weight) + return (logits, trace) if return_trace else logits + + +@torch.no_grad() +def prefix_trace(model, prefixes, padded_length): + """Evaluate only two supplied tokens and a fixed zero suffix; never a target.""" + if prefixes.ndim != 2 or prefixes.shape[1] != 2 or padded_length < 4: + raise ValueError("Need two-token prefixes and the fixed hops+2 sequence length") + tokens = torch.zeros((len(prefixes), padded_length), dtype=torch.long, device=prefixes.device) + tokens[:, :2] = prefixes + positions = torch.ones((len(prefixes), 1), dtype=torch.long, device=prefixes.device) + return traced_forward(model, tokens, positions, return_trace=True)[1] + + +@torch.no_grad() +def evaluate_condition( + model, + rows, + device, + padded_length, + *, + donor_prefixes=None, + patch_layer=None, + component="both", + identity=False, + batch_size=1024, + verify_trace=False, +): + """Generate answer then EOS, reapplying exactly the same donor intervention.""" + if donor_prefixes is not None and donor_prefixes.shape != (len(rows), 2): + raise ValueError("Donor prefixes must align one-to-one with recipient rows") + answers, stops, logits_saved = [], [], [] + max_delta = prefix_delta = 0.0 + packed = pack_rows(rows, padded_length) + for start in range(0, len(rows), batch_size): + x, pos, _ = (torch.as_tensor(a[start : start + batch_size], device=device) for a in packed) + x = x.clone() + donor = None + if donor_prefixes is not None: + prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) + donor = prefix_trace(model, prefixes, padded_length) + arguments = dict( + patch_layer=patch_layer, + component=component, + donor_trace=donor, + identity=identity, + ) + logits, trace = traced_forward(model, x, pos, return_trace=True, **arguments) + if verify_trace: + if patch_layer is not None: + raise ValueError("Native-forward verification applies to baseline only") + reference = model(x, pos) + max_delta = max(max_delta, float((reference - logits).abs().max())) + if not torch.equal(reference.argmax(-1), logits.argmax(-1)): + raise AssertionError("Traced forward changes native argmax") + prefix = prefix_trace(model, x[:, :2], padded_length) + for full, truncated in zip(trace, prefix, strict=True): + for field in TRACE_FIELDS: + prefix_delta = max( + prefix_delta, float((full[field] - truncated[field]).abs().max()) + ) + answer = logits[:, 0].argmax(-1) + logits_saved.append(logits[:, 0].cpu().numpy()) + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + continuation = traced_forward(model, x, pos, **arguments) + if verify_trace: + reference = model(x, pos) + max_delta = max(max_delta, float((reference - continuation).abs().max())) + if not torch.equal(reference.argmax(-1), continuation.argmax(-1)): + raise AssertionError("Generated-answer trace changes native argmax") + answers.append(answer.cpu().numpy()) + stops.append(continuation[:, 1].argmax(-1).cpu().numpy()) + if max_delta > 1e-5 or prefix_delta > 1e-5: + raise AssertionError(f"Native/prefix trace disagreement: {max_delta}, {prefix_delta}") + return { + "answer": np.concatenate(answers) if answers else np.empty(0, dtype=np.int64), + "stop": np.concatenate(stops) if stops else np.empty(0, dtype=np.int64), + "answer_logits": np.concatenate(logits_saved) + if logits_saved + else np.empty((0, model.token.num_embeddings), dtype=np.float32), + }, { + "native_comparison_performed": verify_trace, + "native_max_logit_delta": max_delta, + "prefix_only_vs_full_all_layers_max_delta": prefix_delta, + } + + +def _metrics(arrays, condition, selected, original, target, baseline): + mask = selected & arrays[condition + "_valid"] + n, total = int(mask.sum()), len(mask) + answer, stop = arrays[condition + "_answer"], arrays[condition + "_stop"] + + def mean(value): + return float(value[mask].mean()) if n else None + + return { + "n": n, + "total_n": total, + "coverage": n / total if total else None, + "target_answer_accuracy": mean(answer == target), + "target_complete_accuracy": mean((answer == target) & (stop == 1)), + "original_answer_accuracy": mean(answer == original), + "original_complete_accuracy": mean((answer == original) & (stop == 1)), + "other_answer_rate": mean((answer != target) & (answer != original)), + "eos_accuracy": mean(stop == 1), + "answer_change_rate": mean(answer != baseline), + } + + +def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): + """Evaluate every executed layer, preserving all rows and prerequisite masks.""" + started = time.perf_counter() + model.eval() + split = str(donors["split"].item()) + rows = world[split] + if not np.array_equal(rows, donors["original_rows"]): + raise ValueError("Donor rows differ from the registered evaluation split") + n, padded_length = len(rows), int(world["metadata"]["hops"]) + 2 + arrays = {key: value.copy() for key, value in donors.items()} + all_rows = np.ones(n, dtype=bool) + conditions, audits = {}, {} + + def evaluate(name, mask, inputs, *, family=None, **kwargs): + result, audit = evaluate_condition( + model, inputs[mask], device, padded_length, batch_size=batch_size, **kwargs + ) + for key in ("answer", "stop"): + values = np.full(n, -1, dtype=np.int64) + values[mask] = result[key] + arrays[name + "_" + key] = values + arrays[name + "_valid"] = mask.copy() + targets = rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] + for suffix, labels in (("original_logit", rows[:, -1]), ("target_logit", targets)): + values = np.full(n, np.nan, dtype=np.float32) + values[mask] = result["answer_logits"][np.arange(mask.sum()), labels[mask]] + arrays[name + "_" + suffix] = values + conditions[name] = { + "family": family, + **{k: v for k, v in kwargs.items() if k in ("patch_layer", "component", "identity")}, + } + audits[name] = audit + + evaluate("baseline", all_rows, rows, verify_trace=True) + for family in ("different", "same"): + valid = donors[family + "_valid"] + # Match batch shape as well as sequence shape for floating-point controls. + evaluate(family + "_matched_baseline", valid, rows, family=family) + evaluate( + family + "_counterfactual_input", + valid, + donors[family + "_counterfactual_rows"], + family=family, + ) + blocks = executed_blocks(model) + for layer in range(len(blocks)): + for component in COMPONENTS: + identity_name = f"e{layer:03d}_identity_{component}" + evaluate( + identity_name, all_rows, rows, patch_layer=layer, component=component, identity=True + ) + for key in ("answer", "stop", "original_logit", "target_logit"): + if not np.array_equal(arrays[identity_name + "_" + key], arrays["baseline_" + key]): + raise AssertionError(f"Identity patch changes {identity_name}.{key}") + for family in ("different", "same"): + valid = donors[family + "_valid"] + name = f"e{layer:03d}_{family}_{component}" + evaluate( + name, + valid, + rows, + family=family, + patch_layer=layer, + component=component, + donor_prefixes=donors[family + "_donor"][valid, :2], + ) + if layer == len(blocks) - 1: + for key in ("answer", "stop", "original_logit"): + if not np.array_equal( + arrays[name + "_" + key][valid], + arrays[family + "_matched_baseline_" + key][valid], + ): + raise AssertionError("Last-block r1 patch changes later answer/EOS") + if layer == 0: + for family in ("different", "same"): + valid = donors[family + "_valid"] + for key in ("answer", "stop", "original_logit", "target_logit"): + left = arrays[f"e000_{family}_both_{key}"][valid] + right = arrays[f"e000_{family}_full_{key}"][valid] + if not np.array_equal(left, right): + raise AssertionError("First-layer same-r1 both/full differ") + atomics, _ = evaluate_condition( + model, world["atomic"], device, padded_length, batch_size=batch_size + ) + atom_correct = (atomics["answer"] == world["atomic"][:, -1]) & (atomics["stop"] == 1) + arrays["atomic_rows"] = world["atomic"].copy() + arrays["atomic_answer"], arrays["atomic_stop"] = atomics["answer"], atomics["stop"] + groups = {"all_rows": all_rows} + prerequisites = {} + for family in ("original", "different", "same"): + valid = all_rows if family == "original" else donors[family + "_valid"] + indices = donors[family + "_atomic_indices"] + correct = np.zeros_like(indices, dtype=bool) + correct[valid] = atom_correct[indices[valid]] + arrays[family + "_atomic_complete_correct"] = correct + complete = valid & correct.all(axis=1) + groups[family + "_all_atomic_correct"] = complete + prerequisites[family] = { + "n": int(valid.sum()), + "total_n": n, + "coverage": float(valid.mean()) if n else None, + "all_hops_complete_accuracy": float(complete[valid].mean()) if valid.any() else None, + "per_hop_complete_accuracy": correct[valid].mean(axis=0).tolist() + if valid.any() + else None, + } + for family in ("different", "same"): + valid = donors[family + "_valid"] + baseline_correct = (arrays[family + "_matched_baseline_answer"] == rows[:, -1]) & ( + arrays[family + "_matched_baseline_stop"] == 1 + ) + groups[family + "_donor_available"] = valid + groups[family + "_donor_missing"] = ~valid + cf = family + "_counterfactual_input" + cf_correct = valid & ( + arrays[cf + "_answer"] == donors[family + "_counterfactual_rows"][:, -1] + ) + cf_correct &= arrays[cf + "_stop"] == 1 + groups[family + "_native_original_and_counterfactual_correct"] = ( + baseline_correct & cf_correct + ) + for category in ("train", "reserved_test", "unused", "ood"): + groups[family + "_counterfactual_" + category] = valid & ( + donors[family + "_counterfactual_split"] == category + ) + scores = {} + for group, mask in groups.items(): + arrays["subset_" + group] = mask.copy() + scored = {} + for condition, description in conditions.items(): + family = description["family"] + target = ( + rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] + ) + scored[condition] = _metrics( + arrays, + condition, + mask, + rows[:, -1], + target, + arrays[(family + "_matched_baseline" if family else "baseline") + "_answer"], + ) + scores[group] = { + "n": int(mask.sum()), + "total_n": n, + "coverage": float(mask.mean()) if n else None, + "conditions": scored, + } + return { + "split": split, + "atomic_split": str(donors["atomic_split"].item()), + "sample_rule": "training-independent fixed probe" + if split == "test_composite" + else "full split", + "hops": padded_length - 2, + "executed_depth": len(blocks), + "unique_layers": len(model.blocks), + "repeats": getattr(model, "repeats", 1), + "patch_position": 1, + "conditions": conditions, + "scores": scores, + "atomic_preconditions": prerequisites, + "donor_coverage": { + family: { + "n": int(donors[family + "_valid"].sum()), + "total_n": n, + "reasons": dict(Counter(donors[family + "_reason"].tolist())), + "counterfactual_split": dict( + Counter(donors[family + "_counterfactual_split"].tolist()) + ), + } + for family in ("different", "same") + }, + "engineering_checks": { + "native_trace": audits["baseline"], + "identity_all_layers_components": True, + "first_layer_same_r1_both_equals_full": True, + "last_layer_r1_patch_cannot_change_later_answer_or_eos": True, + "donor_nonpadding_tokens": 2, + "donor_padded_length": padded_length, + "mlp_recomputed_after_mixing": False, + "eos_uses_generated_answer_and_reapplies_same_patch": True, + }, + "interpretation": ( + "End-to-end prefix-state interventions, not proof that facts reside only in MLP. " + "Component mixtures retain recipient incoming residual. Both/full are equivalent " + "only at first execution layer with same r1; later differences are expected. " + "Facts and queries within one world are not independent experimental worlds." + ), + "evaluation_seconds": time.perf_counter() - started, + }, arrays diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_model.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed46483cb7277c172f8848cefb9e2d085d67c0b --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_model.py @@ -0,0 +1,108 @@ +"""Depth-shared GPT blocks for controlled composition-learning comparisons. + +This keeps the existing SmallGPT tokenization, causal attention, dropout and tied +readout. ``config.layers`` counts independently parameterized blocks; each loop +executes this whole block group. Positions and token embeddings are added once. +""" + +from __future__ import annotations + +import math +from dataclasses import replace +from numbers import Integral + +import torch +from torch.nn import functional as F + +from .bios_model import matmul_flops +from .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, + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f3cac329831b303c1dc9ca05c270837de0614eec --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py @@ -0,0 +1,342 @@ +"""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 fed +to the model. ID donors must have actually occurred at the first position of +composite training. OOD donors have zero composite exposure at either position. +All eligible donors and ID x OOD pairs are retained. A pair is a repeated +measurement of its recipient, not an independent query or world. +""" + +from __future__ import annotations + +import hashlib +import json +from collections import defaultdict +from collections.abc import Mapping +from 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 result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..48fa45f53e08b7da9c17a92df8eb5ba4efd8a229 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py @@ -0,0 +1,353 @@ +"""Same-bridge prefix interventions, with query-balanced donor summaries. + +The donor selector never sees model scores. This evaluator reuses the audited +first-block component mixer; it does not retrain models or recompute the current +MLP after mixing. All candidate donors are evaluated, then averaged within the +recipient query before any world-level aggregation. +""" + +from __future__ import annotations + +import hashlib +import time + +import numpy as np +import 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", + } diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_supervision.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_supervision.py new file mode 100644 index 0000000000000000000000000000000000000000..104364e93299229e1a8216acabb046e5fae1dde4 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_supervision.py @@ -0,0 +1,349 @@ +"""Paired continuation: terminal versus distributed answer supervision. + +Historical model/trainer files remain unchanged. All heads branch off the same +trajectory; their LayerNorm outputs never replace the recurrent residual state. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_data import StratifiedStream +from .grok_loop_model import LoopGPT, flops +from .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, + }, + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_train.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_train.py new file mode 100644 index 0000000000000000000000000000000000000000..ffee809fcc7335c7b68e3321427ffcc0342c3086 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_loop_train.py @@ -0,0 +1,214 @@ +"""Frozen loop comparison trainer with stratified exposure and executed-depth FLOPs.""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_data import StratifiedStream +from .grok_loop_model import LoopGPT, flops +from .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] diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_multihop.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_multihop.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0824b5e038658e91c3cbc5e521a316861f20a4 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_multihop.py @@ -0,0 +1,278 @@ +"""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 json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_json +from .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] diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_multihop_data.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_multihop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d857233765485dc4bf1a210fda171628a20d9817 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_multihop_data.py @@ -0,0 +1,245 @@ +"""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 and +one 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 hashlib +import math + +import numpy as np + +from .grok_depth_data import ENTITY_OFFSET +from .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="= 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, + } diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_usage_data.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_usage_data.py new file mode 100644 index 0000000000000000000000000000000000000000..04e5650b0bdea1e25cfde235045efc9b14e0c769 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_usage_data.py @@ -0,0 +1,397 @@ +"""Paired fact-use assignments and constituent-occurrence repetition controls. + +The same random graph and held-out queries are used in every arm. A/B change +which random fact cohort may occur in composition training. repA/repB replace +each 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 copy +import hashlib +from collections.abc import Mapping + +import numpy as np + +from .grok_depth_data import build_world as build_graph_world +from .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=" 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"] diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_usage_train.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_usage_train.py new file mode 100644 index 0000000000000000000000000000000000000000..8460dcf149ad8f229cc4c16783e8e7429acd0610 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grok_usage_train.py @@ -0,0 +1,261 @@ +"""Paired training of composition experience versus constituent-fact repetition.""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .grok_multihop import autonomous_calls, evaluate_rows, pack_rows +from .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(), + }, + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..9530969731263b69c576f12989a3610ead6036f5 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py @@ -0,0 +1,421 @@ +"""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 copy +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step_mechanism import traced_forward +from .grok_depth import write_json +from .latent_scaling import model_digest +from .storage_composition import generate_rows, pack_sentences +from .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 result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grokking_reproduction.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grokking_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f7ba958ea469d5edea6e98c9941dcc49427a6f --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/grokking_reproduction.py @@ -0,0 +1,563 @@ +"""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 initialization +are retained. SDPA, selecting supervised logits, CUDA graphs and bf16 AMP are +explicit execution/numerical adaptations, checked against Hugging Face GPT-2. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F +from transformers import GPT2Config, GPT2LMHeadModel, GPT2TokenizerFast + +from .bios_model import ModelConfig, matmul_flops +from .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"" for i in range(2000)] + [f"" for i in range(200)] + vocab += ["", "", "", "", "", ""] + 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(""), + "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 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) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_data.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_data.py new file mode 100644 index 0000000000000000000000000000000000000000..b67eee718fd00d44c1de51a2821e24aa7251196b --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_data.py @@ -0,0 +1,396 @@ +"""CounterFact true-label data, explicit audit decisions and indivisible subject pools.""" + +from __future__ import annotations + +import hashlib +import re +import unicodedata +from 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"(? 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 coverage diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_followup.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..89afed17153ba18880997b4089ddadb1b997f80b --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_followup.py @@ -0,0 +1,103 @@ +"""Fixed-content worlds and conservative full-entity answer parsing.""" + +from __future__ import annotations + +import hashlib +import re +import unicodedata +from 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}")) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_future.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_future.py new file mode 100644 index 0000000000000000000000000000000000000000..24171d0e5bc0c31f7cc4ac32af06d86dd8ec15f4 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_future.py @@ -0,0 +1,148 @@ +"""Exploratory kernel prediction and balanced multi-hop worlds, September 2026.""" + +from __future__ import annotations + +import hashlib +import json +from 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])] diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_interface.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..0135ee958b76df5e2df2aa4ea0c2c57c40f2b24a --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_interface.py @@ -0,0 +1,566 @@ +"""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 hashlib +import importlib.metadata +import json +import platform +import sys +import time +from dataclasses import asdict +from pathlib import Path + +import numpy as np +import torch +import 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 summary diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_learning.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..78155602739f614f369304edc920dbb75b590bea --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_learning.py @@ -0,0 +1,187 @@ +"""Prospective Hebbian study: numerical calibration and auditable common primitives.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import math +import os +from datetime import datetime, timezone +from 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()) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_model.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_model.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8e5da864f18f673c829d8b68db641d728ca437 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_model.py @@ -0,0 +1,339 @@ +"""FP32 Qwen adapter. All CE/KL reductions preserve per-sequence weighting.""" + +from __future__ import annotations + +import copy +import hashlib +import os +import time + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import AutoModelForCausalLM, AutoTokenizer, StoppingCriteria, StoppingCriteriaList + +from .hebbian_data import TEMPLATE, score_answer +from .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}, + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_statistics.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..52bcc965886f86bf20041ec40ce6aa95b96a725f --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_statistics.py @@ -0,0 +1,168 @@ +"""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 None diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_train.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_train.py new file mode 100644 index 0000000000000000000000000000000000000000..f70905fa1648aeba1d7bad8aca55a77bbcadd72f --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/hebbian_train.py @@ -0,0 +1,811 @@ +"""Paired formation/adaptation, prospective diagnostics and exact state resumption.""" + +from __future__ import annotations + +import itertools +import json +import random +import time + +import numpy as np +import torch +import 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", + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/interface_editing.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/interface_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..7065e910e82f4aa54e312af63f4f99925c4e1269 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/interface_editing.py @@ -0,0 +1,759 @@ +"""Local factual updates and downstream composition in existing aligned GPTs. + +Cases are selected from the graph alone, before loading any model predictions. +Every edit has a same-budget old-fact sham, fresh optimizer, and frozen parent +replay reference. No composition labels or intermediate-state targets enter +optimization. Finite replay KL is a regularizer, not exact preservation. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import build_world, model_digest +from .representation_alignment import new_model +from .storage_composition import data_digest, file_hash, generate_rows, pack_sentences + +ROLES = ("first", "second") +STRATA = ("familiar", "strict") +DEFAULT_NODES = (0, 32, 128, 512) + + +def _rows(values, width): + return np.asarray(values, dtype=np.int64).reshape(-1, width) + + +def _unique(values, width): + return _rows(sorted(set(map(tuple, _rows(values, width)))), width) + + +def _hash_json(value): + return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() + + +def _batch_hash(batch): + digest = hashlib.sha256() + for tensor in batch: + array = tensor.detach().cpu().numpy() + digest.update(str(array.dtype).encode()) + digest.update(str(array.shape).encode()) + digest.update(array.tobytes()) + return digest.hexdigest() + + +def learned_atoms(world): + """Only atomics actually supervised in the representation parent.""" + return _unique(np.concatenate([world["common_atomic"], world["anchor_atomic"]]), 3) + + +def composition_pools(world): + """All legal untrained queries, plus the original holdout and training sets.""" + trained = set(map(tuple, world["train_composite"])) + full = _unique(np.concatenate([world["available_composite"], world["familiar_test"]]), 5) + familiar = _rows([r for r in full if tuple(r) not in trained], 5) + return { + "familiar": familiar, + "strict": world["strict_test"].copy(), + "registered_familiar": world["familiar_test"].copy(), + "train": world["train_composite"].copy(), + } + + +def affected(rows, fact, role): + """Whether a query uses this factual address, independently of its answer.""" + columns = (0, 1) if role == "first" else (2, 3) + return (rows[:, columns[0]] == fact[0]) & (rows[:, columns[1]] == fact[1]) + + +def rewrite(rows, old_fact, new_fact, role, lookup): + result = rows.copy() + mask = affected(rows, old_fact, role) + if role == "first": + result[mask, 2] = new_fact[2] + for index in np.flatnonzero(mask): + result[index, 4] = lookup[int(new_fact[2]), int(rows[index, 3])] + else: + result[mask, 4] = new_fact[2] + return result + + +def graph_cases(parent_spec, *, seed=780011, per_cell=2, replay_n=32): + """Return JSON-compatible selected cases and graph-only eligibility counts. + + Each distinct atomic address receives at most one counterfactual per role. + First-hop replacements stay in the original familiar/strict bridge group and + change at least one affected untrained composition answer. Strict cases never + borrow a bridge with composition experience from the familiar group. + """ + if per_cell < 1 or replay_n < 1: + raise ValueError("Positive case and replay counts are required") + world = build_world(parent_spec) + atoms = learned_atoms(world) + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + pools = composition_pools(world) + rng = np.random.default_rng(seed + int(parent_spec["world"])) + candidates, qualification = [], {} + for role in ROLES: + for stratum in STRATA: + rows = pools[stratum] + addresses = _unique(rows[:, [0, 1, 2] if role == "first" else [2, 3, 4]], 3) + bridges = np.unique(rows[:, 2]) + # Include all trained bridges in that group, even if the holdout + # happens not to visit them (strict rows enumerate all chains). + group = world["background_atomic"] if stratum == "familiar" else world["common_atomic"] + group_bridges = np.unique(group[group[:, 1] >= 17, 0]) + if stratum == "strict": + familiar_bridges = world["background_atomic"] + familiar_bridges = familiar_bridges[familiar_bridges[:, 1] >= 17, 0] + group_bridges = np.setdiff1d(group_bridges, familiar_bridges) + bridges = np.union1d(bridges, group_bridges) + tails = np.unique(atoms[atoms[:, 1] >= 17, 2]) + eligible, replacement_count = [], 0 + for old in addresses: + impacted = rows[affected(rows, old, role)] + choices = [] + for value in bridges if role == "first" else tails: + if value == old[2]: + continue + new = [int(old[0]), int(old[1]), int(value)] + updated = rewrite(impacted, old, new, role, lookup) + if np.any(updated[:, -1] != impacted[:, -1]): + choices.append(new) + replacement_count += len(choices) + if choices: + eligible.append((old.tolist(), choices)) + key = f"{role}_{stratum}" + qualification[key] = { + "candidate_addresses": len(addresses), + "eligible_addresses": len(eligible), + "eligible_replacements": replacement_count, + "untrained_queries": len(rows), + } + if len(eligible) < per_cell: + raise ValueError(f"Insufficient graph-qualified {key} cases: {qualification[key]}") + order = rng.permutation(len(eligible))[:per_cell] + for serial, index in enumerate(order): + old, choices = eligible[index] + new = choices[int(rng.integers(len(choices)))] + candidates.append( + { + "case_id": f"{key}-{serial:02d}", + "role": role, + "stratum": stratum, + "old_fact": old, + "new_fact": new, + } + ) + for case in candidates: + tasks, originals = case_tasks(world, case, replay_indices=None) + necessary = set(map(tuple, tasks["necessary_atomic"])) + allowed = [ + i + for i, row in enumerate(atoms) + if tuple(row) != tuple(case["old_fact"]) and tuple(row) not in necessary + ] + if len(allowed) < replay_n: + raise ValueError("Insufficient independent replay atomics") + case["replay_indices"] = sorted(map(int, rng.choice(allowed, replay_n, replace=False))) + case["affected_untrained_n"] = {name: len(rows) for name, rows in originals.items()} + return candidates, qualification + + +def case_tasks(world, case, replay_indices=None): + """Construct E/R/U/D with address-based exclusions and recomputed truth.""" + atoms = learned_atoms(world) + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + old, new, role = case["old_fact"], case["new_fact"], case["role"] + if lookup[tuple(old[:2])] != old[2] or old[:2] != new[:2] or old[2] == new[2]: + raise ValueError("An edit must replace one existing factual value") + tasks = {"E_old": _rows([old], 3), "E_new": _rows([new], 3)} + originals, necessary = {}, [] + for stratum, rows in composition_pools(world).items(): + mask = affected(rows, old, role) + tasks[f"U_{stratum}"] = rows[~mask].copy() + old_rows = rows[mask].copy() + new_rows = rewrite(old_rows, old, new, role, lookup) + changed = old_rows[:, -1] != new_rows[:, -1] + if stratum == "train": + # Training-query transfer is reported separately from held-out D. + name = f"T_{role}_train" + originals[name] = old_rows + tasks[name] = new_rows + else: + name = f"D_{role}_{stratum}" + originals[name] = old_rows[changed] + tasks[name] = new_rows[changed] + same = f"S_same_answer_{role}_{stratum}" + originals[same] = old_rows[~changed] + tasks[same] = new_rows[~changed] + if stratum in STRATA: + for h, r1, b, r2, t in tasks[name]: + prerequisite = (b, r2, t) if role == "first" else (h, r1, b) + necessary.append(prerequisite) + tasks["necessary_atomic"] = _unique(necessary, 3) + replay = case.get("replay_indices", []) if replay_indices is None else replay_indices + if len(set(replay)) != len(replay): + raise ValueError("Replay indices must be unique") + target = np.flatnonzero(np.all(atoms == np.asarray(old), axis=1)) + if len(target) != 1 or int(target[0]) in replay: + raise ValueError("Replay cannot contain the edited address") + tasks["R_atomic"] = atoms[replay].copy() + tasks["U_atomic"] = np.delete(atoms, [int(target[0]), *replay], axis=0) + return tasks, originals + + +def answer_batch(rows, device): + """Only answer, punctuation and EOS labels; no prefix or bridge labels.""" + tokens, labels = pack_sentences(_rows(rows, 3)) + positions = np.tile([4, 5, 6], (len(rows), 1)) + targets = labels[np.arange(len(rows))[:, None], positions] + expected = np.column_stack([np.asarray(rows)[:, 2], np.full(len(rows), 5), np.ones(len(rows))]) + np.testing.assert_array_equal(targets, expected) + return tuple(torch.as_tensor(x, device=device) for x in (tokens, positions, targets)) + + +def edit_objective(model, target_batch, replay_batch, parent_log, replay_weight=1.0): + target = model(target_batch[0], positions=target_batch[1]) + ce = F.cross_entropy(target.flatten(0, 1), target_batch[2].flatten()) + replay = model(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + if parent_log.requires_grad: + raise ValueError("Replay reference must be detached") + kl = F.kl_div(replay, parent_log, log_target=True, reduction="none").sum(-1).mean() + return ce + replay_weight * kl, ce, kl + + +def _generate(model, rows, device, batch_size): + if len(rows): + return generate_rows(model, rows, device, batch_size=batch_size) + return ( + {"n": 0, "accuracy": None, "answer_accuracy": None, "answer_nll": None}, + { + "generated": np.empty((0, 3), dtype=np.int64), + "correct": np.empty(0, dtype=bool), + "answer_nll": np.empty(0), + }, + ) + + +def evaluate_case(model, tasks, originals, parent_correct, role, device, batch_size=512): + """Full-pool scores and separately labelled prerequisite/parent subsets.""" + metrics, raw = {}, {} + for name, rows in tasks.items(): + values, predictions = _generate(model, rows, device, batch_size) + raw.update({f"{name}__{k}": v for k, v in predictions.items()}) + if name in originals: + old = originals[name] + generated = predictions["generated"] + changed = old[:, -1] != rows[:, -1] + old_correct = (generated[:, 0] == old[:, -1]) & np.all( + generated[:, 1:] == [5, 1], axis=1 + ) + prerequisite = rows[:, [2, 3, 4] if role == "first" else [0, 1, 2]] + _m, needed = _generate(model, prerequisite, device, batch_size) + edited_ok = metrics["E_new"]["accuracy"] == 1.0 + covered = needed["correct"] & edited_ok + baseline = parent_correct[name] + valid_parent = baseline & changed + correct = predictions["correct"] + values.update( + { + "changed_answer_n": int(changed.sum()), + "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None, + "parent_correct_n": int(baseline.sum()), + "parent_correct_coverage": float(baseline.mean()) if len(rows) else None, + "new_following_parent_correct": float(correct[valid_parent].mean()) + if valid_parent.any() + else None, + "old_retained_parent_correct": float(old_correct[valid_parent].mean()) + if valid_parent.any() + else None, + "direct_edit_success": edited_ok, + "necessary_atomic_correct_n": int(needed["correct"].sum()), + "operation_correct_n": int(covered.sum()), + "operation_correct_coverage": float(covered.mean()) if len(rows) else None, + "new_following_operation_correct": float(correct[covered].mean()) + if covered.any() + else None, + } + ) + raw[f"{name}__parent_correct"] = baseline + raw[f"{name}__operation_correct"] = covered + raw[f"{name}__old_correct"] = old_correct + raw[f"{name}__necessary_generated"] = needed["generated"] + raw[f"{name}__new_rows"] = rows + raw[f"{name}__old_rows"] = old + metrics[name] = values + return metrics, raw + + +def editable_parameters(model, scope="mlp", block_index=0): + prefix = f"blocks.{block_index}.mlp." + selected = [ + name + for name, _ in model.named_parameters() + if name.startswith(prefix) and (scope == "mlp" or name == prefix + "down.weight") + ] + if scope not in {"mlp", "down"} or not selected: + raise ValueError("Unknown or empty local parameter scope") + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name in selected) + parameter.grad = None + return selected + + +def _configure(device): + device = torch.device(device) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + return device + + +def _load_parent(parent_dir, device): + path = Path(parent_dir) / "model.pt" + payload = torch.load(path, map_location="cpu", weights_only=False) + model = new_model(payload["spec"], device).eval() + model.load_state_dict(payload["model"]) + world = build_world(payload["spec"]) + if (Path(parent_dir) / "world.npz").exists(): + with np.load(Path(parent_dir) / "world.npz") as saved: + for name, rows in world.items(): + np.testing.assert_array_equal(rows, saved[name]) + return model, world, payload["spec"] + + +def _parent_masks(parent, originals, device, batch_size): + return { + name: _generate(parent, rows, device, batch_size)[1]["correct"] + for name, rows in originals.items() + } + + +def run(spec, out, device="cuda:0"): + """Execute one parent, a graph-selected case set and optional development lr grid. + + The caller owns source freezing, resource allocation and W&B startup. Each + branch has run/learning/complete artifacts. Root ``step`` is a strictly + increasing evaluation index, including every branch's unchanged node zero; + ``optimizer_updates`` separately records cumulative optimization work. + Target labels and replay KL positions have separate exposure counters. + ``status.json`` retains completed-branch progress, explicitly labelled in + the manifest; it does not define the tracking series' step axis. + """ + device = _configure(device) + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite an existing attempt: {out}") + nodes = spec.get("nodes", list(DEFAULT_NODES)) + if not nodes or nodes[0] != 0 or nodes != sorted(set(nodes)) or nodes[-1] <= 0: + raise ValueError("Nodes must increase from zero to a positive fixed endpoint") + rates = spec.get("learning_rates", [spec.get("lr", 1e-4)]) + if not rates or any(lr <= 0 for lr in rates) or len(set(rates)) != len(rates): + raise ValueError("Learning rates must be positive and unique") + if spec.get("phase") not in {"development", "engineering"} and len(rates) > 1: + raise ValueError("Learning-rate grids are development-only") + arms = spec.get("arms", ["edit", "sham"]) + if sorted(arms) != ["edit", "sham"]: + raise ValueError("Every case requires paired edit and sham branches") + parent, world, parent_spec = _load_parent(spec["parent_dir"], device) + parent_hash = model_digest(parent) + cases, qualification = graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + if "case_ids" in spec: + requested = set(spec["case_ids"]) + if not requested or not requested <= {c["case_id"] for c in cases}: + raise ValueError("Unknown/empty fixed graph-selected case subset") + cases = [c for c in cases if c["case_id"] in requested] + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "cases": cases, + "qualification": qualification, + "case_sha256": _hash_json(cases), + "parent_file_sha256": file_hash(Path(spec["parent_dir"]) / "model.pt"), + "parent_model_sha256": parent_hash, + "world_sha256": data_digest(world), + "created_utc": utc(), + "dtype": "float32", + "allow_tf32": True, + "pid": os.getpid(), + "gpu": device.index if device.type == "cuda" else None, + "branches": len(cases) * len(rates) * len(arms), + "planned_updates": len(cases) * len(rates) * len(arms) * nodes[-1], + "planned_evaluations": len(cases) * len(rates) * len(arms) * len(nodes), + "learning_step_unit": "evaluation_index", + "status_step_unit": "completed_branches", + "scope_warning": "The selected MLP is shared across all repeated executions", + } + write_json(out / "run.json", manifest) + write_json(out / "cases.json", cases) + np.savez_compressed(out / "world.npz", **world) + root_learning, branch_summaries, completed_steps = [], [], 0 + started = time.perf_counter() + training_seconds = 0.0 + batch_size = spec.get("eval_batch_size", 512) + for case in cases: + tasks, originals = case_tasks(world, case) + parent_correct = _parent_masks(parent, originals, device, batch_size) + parent_metrics, parent_predictions = evaluate_case( + parent, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + case_out = out / case["case_id"] + case_out.mkdir() + np.savez_compressed(case_out / "parent-predictions.npz", **parent_predictions) + write_json(case_out / "parent-metrics.json", parent_metrics) + np.savez_compressed(case_out / "tasks.npz", **tasks) + replay_batch = answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + parent_log = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1).detach() + for lr in rates: + for arm in arms: + branch_name = f"lr{lr:.8g}-{arm}" + branch_out = case_out / branch_name + branch_out.mkdir() + model = copy.deepcopy(parent).eval() + selected = editable_parameters( + model, + spec.get("parameter_scope", "mlp"), + spec.get("block_index", 0), + ) + parameters = dict(model.named_parameters()) + optimizer = torch.optim.Adam([parameters[n] for n in selected], lr=lr) + target = tasks["E_new" if arm == "edit" else "E_old"] + target_batch = answer_batch(target, device) + write_json( + branch_out / "run.json", + { + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + "parent_model_sha256": parent_hash, + "editable_parameters": selected, + "optimizer": "Adam, fresh state, zero weight decay", + "sampling": "same fixed full replay batch on every update; no dropout", + "old_fact_sha256": _hash_json(case["old_fact"]), + "new_fact_sha256": _hash_json(case["new_fact"]), + "target_batch_sha256": _batch_hash(target_batch), + "replay_batch_sha256": _batch_hash(replay_batch), + "parent_reference_sha256": _batch_hash((parent_log,)), + "nodes": nodes, + }, + ) + np.savez_compressed( + branch_out / "replay-reference.npz", log_probabilities=parent_log.cpu().numpy() + ) + step, losses, history = 0, [], [] + for node in nodes: + if device.type == "cuda": + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, ce, kl = edit_objective( + model, + target_batch, + replay_batch, + parent_log, + spec.get("replay_weight", 1.0), + ) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite edit loss at {step}") + loss.backward() + gradient_norm = torch.nn.utils.clip_grad_norm_( + [parameters[n] for n in selected], + spec.get("clip_norm", 1.0), + ) + optimizer.step() + step += 1 + losses.append( + { + "step": step, + "loss": float(loss.detach()), + "target_ce": float(ce.detach()), + "replay_kl": float(kl.detach()), + "gradient_norm": float(gradient_norm), + } + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + metrics, predictions = evaluate_case( + model, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + current_hash = model_digest(model) + record = { + "step": step, + "metrics": metrics, + "model_sha256": current_hash, + "target_success": metrics["E_new" if arm == "edit" else "E_old"]["accuracy"] + == 1, + "U_atomic_at_least_95": metrics["U_atomic"]["accuracy"] >= 0.95, + "loss": losses[-1] if losses else None, + } + history.append(record) + write_json(branch_out / "learning.json", history) + write_json(branch_out / "losses.json", losses) + np.savez_compressed(branch_out / f"predictions-{step:06d}.npz", **predictions) + torch.save( + { + "edited_tensors": { + n: parameters[n].detach().cpu().clone() for n in selected + }, + "model_sha256": current_hash, + "step": step, + }, + branch_out / f"tensors-{step:06d}.pt", + ) + root_learning.append( + { + "step": len(root_learning), + "branch_step": step, + "completed_branches": len(branch_summaries) + int(step == nodes[-1]), + "optimizer_updates": completed_steps + step, + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + "metrics": metrics, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": (completed_steps + step) * (1 + len(tasks["R_atomic"])), + "target_supervised_tokens": (completed_steps + step) * 3, + "replay_distillation_positions": (completed_steps + step) + * len(tasks["R_atomic"]) + * 3, + } + ) + write_json(out / "learning.json", root_learning) + write_json( + out / "status.json", + { + "state": "running", + "step": len(branch_summaries), + "optimizer_updates": completed_steps + step, + "budget": manifest["branches"], + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + }, + ) + changed = [ + n + for n, t in model.state_dict().items() + if not torch.equal(t, parent.state_dict()[n]) + ] + if set(changed) - set(selected) or model_digest(parent) != parent_hash: + raise AssertionError("A frozen parameter or the parent changed") + complete = { + "case_id": case["case_id"], + "role": case["role"], + "stratum": case["stratum"], + "lr": lr, + "arm": arm, + "path": str(branch_out.relative_to(out)), + "metrics": metrics, + "steps": step, + "changed_tensors": changed, + "parent_model_sha256": parent_hash, + "final_model_sha256": current_hash, + "delta_l2": float( + torch.sqrt( + sum( + (parameters[n] - dict(parent.named_parameters())[n]).square().sum() + for n in selected + ) + ).detach() + ), + "tensor_file_sha256": file_hash(branch_out / f"tensors-{step:06d}.pt"), + } + write_json(branch_out / "complete.json", complete) + branch_summaries.append(complete) + completed_steps += step + result = { + "status": "complete", + "branches": branch_summaries, + "updates": completed_steps, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "finished_utc": utc(), + "case_sha256": manifest["case_sha256"], + } + write_json(out / "complete.json", result) + write_json( + out / "status.json", + { + "state": "complete", + "step": len(branch_summaries), + "optimizer_updates": completed_steps, + "budget": manifest["branches"], + }, + ) + return result + + +def audit(out, device="cuda:0"): + """Reload every saved node from parent plus exact tensors and re-score it.""" + device, out = _configure(device), Path(out) + manifest = json.loads((out / "run.json").read_text()) + spec = manifest["spec"] + if file_hash(Path(spec["parent_dir"]) / "model.pt") != manifest["parent_file_sha256"]: + raise AssertionError("Parent checkpoint hash changed") + parent, world, parent_spec = _load_parent(spec["parent_dir"], device) + if model_digest(parent) != manifest["parent_model_sha256"]: + raise AssertionError("Parent model digest changed") + cases, qualification = graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + if "case_ids" in spec: + cases = [c for c in cases if c["case_id"] in spec["case_ids"]] + if cases != manifest["cases"] or _hash_json(cases) != manifest["case_sha256"]: + raise AssertionError("Graph-selected cases changed") + if qualification != manifest["qualification"] or data_digest(world) != manifest["world_sha256"]: + raise AssertionError("World qualification changed") + summary = json.loads((out / "complete.json").read_text()) + rates = spec.get("learning_rates", [spec.get("lr", 1e-4)]) + expected_branches = { + (c["case_id"], lr, arm) for c in cases for lr in rates for arm in ("edit", "sham") + } + actual_branches = [(b["case_id"], b["lr"], b["arm"]) for b in summary["branches"]] + if len(actual_branches) != len(expected_branches) or set(actual_branches) != expected_branches: + raise AssertionError("The fixed paired branch matrix is incomplete") + root_learning = json.loads((out / "learning.json").read_text()) + nodes = spec.get("nodes", list(DEFAULT_NODES)) + expected_evaluations = len(actual_branches) * len(nodes) + if len(root_learning) != expected_evaluations or [row["step"] for row in root_learning] != list( + range(expected_evaluations) + ): + raise AssertionError("Root learning evaluation indices are incomplete or repeated") + for index, row in enumerate(root_learning): + branch_index, node_index = divmod(index, len(nodes)) + updates = branch_index * nodes[-1] + nodes[node_index] + if ( + (row["case_id"], row["lr"], row["arm"]) != actual_branches[branch_index] + or row["branch_step"] != nodes[node_index] + or row["optimizer_updates"] != updates + or row["target_supervised_tokens"] != updates * 3 + or row["replay_distillation_positions"] != updates * spec.get("replay_n", 32) * 3 + or "supervised_tokens" in row + ): + raise AssertionError("Root learning optimizer or exposure accounting changed") + batch_size = spec.get("eval_batch_size", 512) + checked_nodes, checked_predictions, max_error = 0, 0, 0.0 + for case in cases: + tasks, originals = case_tasks(world, case) + parent_correct = _parent_masks(parent, originals, device, batch_size) + for branch in summary["branches"]: + if branch["case_id"] != case["case_id"]: + continue + directory = out / branch["path"] + branch_spec = json.loads((directory / "run.json").read_text()) + target = tasks["E_new" if branch["arm"] == "edit" else "E_old"] + target_batch = answer_batch(target, device) + replay_batch = answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + reference = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + expected_hashes = { + "old_fact_sha256": _hash_json(case["old_fact"]), + "new_fact_sha256": _hash_json(case["new_fact"]), + "target_batch_sha256": _batch_hash(target_batch), + "replay_batch_sha256": _batch_hash(replay_batch), + "parent_reference_sha256": _batch_hash((reference,)), + } + if any(branch_spec[key] != value for key, value in expected_hashes.items()): + raise AssertionError("Target or paired replay provenance changed") + history = json.loads((directory / "learning.json").read_text()) + if [record["step"] for record in history] != spec.get("nodes", list(DEFAULT_NODES)): + raise AssertionError("Saved edit node matrix is incomplete") + if ( + file_hash(directory / f"tensors-{history[-1]['step']:06d}.pt") + != branch["tensor_file_sha256"] + ): + raise AssertionError("Final exact tensor file hash changed") + for record in history: + state = torch.load( + directory / f"tensors-{record['step']:06d}.pt", + map_location="cpu", + weights_only=True, + ) + model = copy.deepcopy(parent).eval() + selected = editable_parameters( + model, spec.get("parameter_scope", "mlp"), spec.get("block_index", 0) + ) + if set(state["edited_tensors"]) != set(selected): + raise AssertionError("Unexpected edited tensor scope") + merged = model.state_dict() + merged.update(state["edited_tensors"]) + model.load_state_dict(merged) + if model_digest(model) != record["model_sha256"]: + raise AssertionError("Exact saved tensors did not reconstruct the model") + metrics, predictions = evaluate_case( + model, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + with np.load(directory / f"predictions-{record['step']:06d}.npz") as saved: + if set(saved.files) != set(predictions): + raise AssertionError("Prediction keys changed") + for name, actual in predictions.items(): + if name.endswith("answer_nll"): + np.testing.assert_allclose(actual, saved[name], rtol=1e-5, atol=1e-5) + if len(actual): + max_error = max( + max_error, float(np.max(np.abs(actual - saved[name]))) + ) + else: + np.testing.assert_array_equal(actual, saved[name]) + checked_predictions += actual.size + for name, values in metrics.items(): + for key, value in values.items(): + expected = record["metrics"][name][key] + if key == "answer_nll" and value is not None: + np.testing.assert_allclose(value, expected, rtol=1e-5, atol=1e-5) + elif value != expected: + raise AssertionError(f"Re-scoring mismatch: {name}/{key}") + checked_nodes += 1 + result = { + "passed": True, + "nodes": checked_nodes, + "array_elements": checked_predictions, + "max_nll_error": max_error, + "case_sha256": manifest["case_sha256"], + "finished_utc": utc(), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/interface_tracking.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/interface_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..16c66de277e2f35fd69f931dc2b4b21b70ec3df4 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/interface_tracking.py @@ -0,0 +1,199 @@ +"""Use the existing W&B sidecar, finishing only after the independent audit.""" + +import argparse +import fcntl +import importlib +import json +import os +import time +from pathlib import Path + +from . import experiment_tracking as tracking + + +class ContainerSDK: + def __init__(self, sdk, runtime): + self.sdk, self.runtime = sdk, runtime + + def __getattr__(self, name): + return getattr(self.sdk, name) + + def Settings(self, **options): + options.pop("x_stats_pid", None) + if self.runtime: + options["x_stats_pid"] = self.runtime["host_pid"] + options["x_stats_gpu_device_ids"] = (self.runtime["physical_gpu"],) + return self.sdk.Settings(**options) + + +class AuditedRunTracker(tracking.ArtifactRunTracker): + def __init__(self, sdk, batch, path, settings): + runtime_path = path / "container-runtime.json" + runtime = tracking.read_json(runtime_path) + super().__init__(ContainerSDK(sdk, runtime), batch, path, settings) + self.run.config.update( + { + key: self.metadata[key] + for key in ( + "parent_spec", + "cases", + "learning_step_unit", + "status_step_unit", + ) + if key in self.metadata + } + ) + if runtime: + self.run.config.update({"container_runtime": runtime}) + + def poll(self): + history = tracking.read_json(self.path / "learning.json") + previous = None + for record in history: + step = int(record["step"]) + if step > self.cursor: + metrics = tracking.learning_metrics(record, previous) + for key in ("case", "case_id", "condition", "variant", "arm"): + if key in record: + metrics["condition/" + key] = record[key] + if "optimizer_updates" in record: + metrics["evaluation/index"] = step + metrics["condition/step_unit"] = "evaluation_index" + metrics.pop("perf/updates_per_second", None) + metrics.pop("perf/training_ms_per_update", None) + if previous is not None: + seconds = record.get("wall_seconds", 0) - previous.get("wall_seconds", 0) + updates = record["optimizer_updates"] - previous.get("optimizer_updates", 0) + if seconds > 0: + metrics["perf/updates_per_second"] = updates / seconds + self.run.log(metrics, step=step) + self.cursor = step + self.state["last_logged_step"] = step + tracking.write_json(self.state_path, self.state) + previous = record + status_path = self.path / "status.json" + if status_path.exists(): + self.run.summary["training_state"] = tracking.read_json(status_path).get("state") + failed = (self.path / "failure.json").exists() + audit_path = self.path / "audit.json" + audit = tracking.read_json(audit_path) if audit_path.exists() else {} + audited = audit.get("passed") is True + complete = (self.path / "complete.json").exists() and audited + self.run.summary["has_failure_record"] = failed + self.run.summary["independently_reloaded"] = audited + if complete or failed: + self.run.summary["scientific_final_step"] = self.cursor + self.run.finish(exit_code=1 if failed else 0) + # Preserve the authoritative resume cursor even when every point + # was already on the server and this process logged no new points. + self.state["last_logged_step"] = self.cursor + tracking.write_json(self.state_path, self.state) + return True + return False + + +def discover_runs(runs_dir): + return { + path + for path in Path(runs_dir).glob("*") + if (path / "run.json").exists() and (path / "learning.json").exists() + } + + +def final_step(path): + history = tracking.read_json(path / "learning.json") + return max((int(record["step"]) for record in history), default=-1) + + +def drain_runs(sdk, root, runs_dir, settings, *, once=False, tracker_factory=None): + """Drain late-created runs and late final nodes before terminal exit. + + SDK initialization and uploads may take longer than an entire scientific + run. Consequently, a scan made before those calls is never an exit proof. + Finished runs stay in this process's cursor map and are reopened only if + their saved learning trajectory acquired an unlogged final node. + """ + root, runs_dir = Path(root), Path(runs_dir) + tracker_factory = tracker_factory or AuditedRunTracker + active, finished = {}, {} + try: + while True: + for path in sorted(discover_runs(runs_dir)): + if path in active or path in finished: + continue + active[path] = tracker_factory(sdk, root, path, settings) + print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True) + for path, tracker in list(active.items()): + current = tracking.read_json(path / "run.json") + if current.get("pid") != tracker.metadata.get("pid"): + tracker.close() + tracker = tracker_factory(sdk, root, path, settings) + active[path] = tracker + if tracker.poll(): + finished[path] = tracker.cursor + del active[path] + if once: + return {str(path): cursor for path, cursor in finished.items()} + manifest = root / "controller-state.json" + state = tracking.read_json(manifest) if manifest.exists() else {} + terminal = state.get("state") in {"complete", "finished_with_failures"} + # Rescan AFTER all SDK calls and after reading the controller's + # terminal state, so runs born during initialization cannot vanish. + fresh = discover_runs(runs_dir) + stale = {path for path, cursor in finished.items() if final_step(path) > cursor} + for path in stale: + del finished[path] + if terminal and not active: + expected = {runs_dir / name for name in state.get("completed", [])} + if missing := expected - fresh: + raise RuntimeError(f"Completed runs lack logging artifacts: {sorted(missing)}") + if fresh <= finished.keys(): + result = { + "passed": True, + "registered_runs": len(finished), + "runs": { + path.name: { + "last_logged_step": finished[path], + "final_step": final_step(path), + } + for path in sorted(fresh) + }, + } + tracking.write_json(root / "tracking-completion.json", result) + return result + if fresh - (active.keys() | finished.keys()): + continue + time.sleep(settings["poll_seconds"]) + finally: + for tracker in active.values(): + tracker.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--runs-dir", type=Path) + parser.add_argument("--defaults", type=Path, default=tracking.DEFAULTS) + parser.add_argument("--entity") + parser.add_argument("--project") + parser.add_argument("--mode", choices=("online", "offline")) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + settings = tracking.read_json(args.defaults) + for key in ("entity", "project", "mode"): + settings[key] = ( + getattr(args, key) or os.environ.get(f"WANDB_{key.upper()}") or settings[key] + ) + if not settings["enabled"]: + raise SystemExit("Experiment tracking is disabled in the selected defaults") + local = args.root / "tracking-wandb" + local.mkdir(parents=True, exist_ok=True) + sdk = importlib.import_module("wandb") + with (local / "tracker.lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + tracking.write_json(args.root / "tracking-ready.json", {"sdk_version": sdk.__version__}) + drain_runs(sdk, args.root, args.runs_dir or args.root / "runs", settings, once=args.once) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/latent_scaling.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/latent_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..7abd21f4255e3f7de35ecee337ed09d32da707ff --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/latent_scaling.py @@ -0,0 +1,311 @@ +"""Scaling knowledge use in ordinary GPT blocks with fixed facts and tests. + +Independent composition examples and optimization time are separate axes. All +blocks retain learned embeddings, causal attention, residuals and 4x GELU MLPs. +Historical experiments and their frozen implementations are left untouched. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .storage_composition import FullTokenStep, data_digest, evaluate, file_hash, pack_sentences +from .storage_composition import build_world as historical_world +from .storage_frontier import SOURCE_FILES as STABILITY_SOURCES +from .storage_frontier import learning_rate +from .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 checked diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/latent_support.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/latent_support.py new file mode 100644 index 0000000000000000000000000000000000000000..4b307c09f7a1fe633c634ae39b3a83e964675355 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/latent_support.py @@ -0,0 +1,363 @@ +"""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 so +historical sources retain their frozen hashes. Architecture, optimizer, sentence +packing, evaluation and streams are reused; only build_world selects support. +""" + +from __future__ import annotations + +import json +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .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 checked diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/low_rank.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/low_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..3a58bee0d460cb3ae042e17d22b7132b2035bd4b --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/low_rank.py @@ -0,0 +1,138 @@ +"""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, Real +from 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 report diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/memory_reuse.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/memory_reuse.py new file mode 100644 index 0000000000000000000000000000000000000000..89520ed7649557ad7e4cfc2611ac85b8d9db8396 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/memory_reuse.py @@ -0,0 +1,469 @@ +"""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 used +by its optimizer, and all evaluation uses continuous intermediate states. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from 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 result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/multihop_scaling.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/multihop_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..64b5a3d67ef6bab20c60904e626e811876d72279 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/multihop_scaling.py @@ -0,0 +1,518 @@ +"""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 copy +import hashlib +import json +import time +from functools import lru_cache +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import depth_step +from .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_json +from .grok_loop_model import flops +from .latent_scaling import model_digest +from .storage_composition import FullTokenStep, file_hash +from .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=" 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 checked diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/natural_composition_confirmation.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/natural_composition_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9608e59339683c91de69b2f1f392b93b8f0171 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/natural_composition_confirmation.py @@ -0,0 +1,687 @@ +"""Full-Qwen, nested compositional support with matched atomic supervision.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import platform +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +import transformers +from 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) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e949ff27eac75a758644d6a7ffd81f2a9477ea --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py @@ -0,0 +1,687 @@ +"""Full-Qwen, nested compositional support with matched atomic supervision.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import platform +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +import transformers +from 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) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/neural.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/neural.py new file mode 100644 index 0000000000000000000000000000000000000000..ce1f02e8195f4e583817b3781b044f021a41fbfb --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/neural.py @@ -0,0 +1,328 @@ +"""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 argparse +import copy +import json +import math +import platform +import statistics +import subprocess +import time +from dataclasses import asdict, dataclass +from pathlib import Path + +import numpy as np + +try: + import torch + from torch import nn + from torch.nn import functional as F +except ModuleNotFoundError as exc: + raise SystemExit("Neural experiments require PyTorch: pip install '.[neural]'") from exc + +from .neural_data import make_world +from .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()) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/neural_data.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/neural_data.py new file mode 100644 index 0000000000000000000000000000000000000000..555b2a06a7db0805d441a3f8f89bc2100deaa72a --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/neural_data.py @@ -0,0 +1,147 @@ +"""Balanced fact-table interventions, defined independently of model training.""" + +from dataclasses import dataclass +from 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, + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/neural_models.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/neural_models.py new file mode 100644 index 0000000000000000000000000000000000000000..448b3499cdce6fac7d4bcac1e60883f4c383df82 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/neural_models.py @@ -0,0 +1,157 @@ +"""Trainable nonlinear fact models; importing this module requires PyTorch.""" + +import torch +from 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 selected diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/parametric_architecture.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/parametric_architecture.py new file mode 100644 index 0000000000000000000000000000000000000000..a254bf6f90931d21d80c57972a6770ad6665c13a --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/parametric_architecture.py @@ -0,0 +1,443 @@ +"""Paired GPT-2 architecture extensions for the closed-book memory experiment. + +Dense execution delegates to the historical ReproductionGPT without changing +its numerical path. New modules use an independent, checkpointed initialization +seed; the eight-block reference is always constructed before taking a prefix. +The mHC residual convention is ``output[n] = sum_m H_res[m,n] * input[m]``. +""" + +from __future__ import annotations + +import hashlib +import math +from collections.abc import Sequence + +import torch +from torch import nn +from torch.nn import functional as F +from transformers import GPT2Config +from transformers.models.gpt2.modeling_gpt2 import GPT2MLP + +from .grokking_reproduction import ReproductionGPT + +ARMS = { + "D4": (4, 1, "dense"), + "D8": (8, 1, "dense"), + "L4R2": (4, 2, "dense"), + "M8": (8, 1, "moe"), + "W8": (8, 1, "wide"), + "IHC8": (8, 1, "identity_mhc"), + "HC8": (8, 1, "mhc"), + "M4": (4, 1, "moe"), + "LM4R2": (4, 2, "moe"), +} + + +def sinkhorn(logits: torch.Tensor, iterations: int = 20, eps: float = 1e-6): + """Accepted mHC A.6: initial row softmax, then 20 column normalizations. + + There are 19 intervening row normalizations. This is a finite-iteration + approximation, not an exact doubly stochastic projection. + """ + if iterations < 1: + raise ValueError("Sinkhorn requires at least one iteration") + with torch.autocast(logits.device.type, enabled=False): + matrix = logits.float().softmax(dim=-1) + eps + matrix = matrix / (matrix.sum(dim=-2, keepdim=True) + eps) + for _ in range(iterations - 1): + matrix = matrix / (matrix.sum(dim=-1, keepdim=True) + eps) + matrix = matrix / (matrix.sum(dim=-2, keepdim=True) + eps) + return matrix + + +def residual_mix(streams, matrix): + """Rows are source streams and columns are destination streams.""" + return torch.einsum("...mn,...mc->...nc", matrix, streams) + + +class ControllerRMSNorm(nn.Module): + def __init__(self, width): + super().__init__() + self.weight = nn.Parameter(torch.ones(width)) + + def forward(self, x): + return x * torch.rsqrt(x.square().mean(dim=-1, keepdim=True) + 1e-20) * self.weight + + +class HyperConnection(nn.Module): + """Four-stream pre/post controller with optional constrained residual map.""" + + def __init__(self, width, sublayer_id, streams=4, identity=False): + super().__init__() + self.streams, self.identity = streams, identity + count = 2 * streams + (0 if identity else streams * streams) + self.norm = ControllerRMSNorm(streams * width) + self.projection = nn.Linear(streams * width, count, bias=False) + nn.init.zeros_(self.projection.weight) + self.pre_bias = nn.Parameter(torch.full((streams,), -3.0)) + with torch.no_grad(): + self.pre_bias[sublayer_id % streams] = 3.0 + self.post_bias = nn.Parameter(torch.zeros(streams)) + self.alpha_pre = nn.Parameter(torch.tensor(0.01)) + self.alpha_post = nn.Parameter(torch.tensor(0.01)) + if not identity: + self.res_bias = nn.Parameter(6 * torch.eye(streams) - 3) + self.alpha_res = nn.Parameter(torch.tensor(0.01)) + + def coefficients(self, x): + n = self.streams + with torch.autocast(x.device.type, enabled=False): + dynamic = self.projection(self.norm(x.float().flatten(-2))) + pre = torch.sigmoid(dynamic[..., :n] * self.alpha_pre + self.pre_bias) + 1e-6 + post = 2 * torch.sigmoid(dynamic[..., n : 2 * n] * self.alpha_post + self.post_bias) + res = None + if not self.identity: + logits = dynamic[..., 2 * n :].reshape(*x.shape[:-2], n, n) + res = sinkhorn(logits * self.alpha_res + self.res_bias) + return pre, post, res + + def forward(self, x, sublayer): + pre, post, res = self.coefficients(x) + with torch.autocast(x.device.type, enabled=False): + contracted = (pre[..., None] * x.float()).sum(dim=-2) + y = sublayer(contracted.to(x.dtype)) + with torch.autocast(x.device.type, enabled=False): + residual = x.float() if res is None else residual_mix(x.float(), res) + output = residual + post[..., None] * y.float().unsqueeze(-2) + return output.to(x.dtype) + + +def _initialize_mlp(mlp, initializer_range): + # Eight-block GPT-2 reference residual projection scale, also for loops. + nn.init.normal_(mlp.c_fc.weight, std=initializer_range) + nn.init.normal_(mlp.c_proj.weight, std=initializer_range / math.sqrt(2 * 8)) + nn.init.zeros_(mlp.c_fc.bias) + nn.init.zeros_(mlp.c_proj.bias) + + +class DroplessMoE(nn.Module): + """Top-2 normalized routing, one output dropout, no capacity/token drops.""" + + def __init__(self, config, experts=8, top_k=2): + super().__init__() + self.expert_count, self.top_k = experts, top_k + self.router = nn.Linear(config.n_embd, experts, bias=False) + nn.init.normal_(self.router.weight, std=config.initializer_range) + self.experts = nn.ModuleList() + for _ in range(experts): + expert = GPT2MLP(2 * config.n_embd, config) + expert.dropout = nn.Identity() + _initialize_mlp(expert, config.initializer_range) + self.experts.append(expert) + self.dropout = nn.Dropout(config.resid_pdrop) + + def forward(self, x, valid_mask=None): + flat = x.reshape(-1, x.shape[-1]) + if valid_mask is None: + selected_tokens = torch.arange(len(flat), device=x.device) + else: + selected_tokens = valid_mask.flatten().nonzero(as_tuple=True)[0] + valid = flat.index_select(0, selected_tokens) + with torch.autocast(x.device.type, enabled=False): + probabilities = F.linear(valid.float(), self.router.weight.float()).softmax(-1) + top_weights, expert_ids = probabilities.topk(self.top_k, dim=-1) + weights = top_weights / top_weights.sum(dim=-1, keepdim=True) + # Accumulate selected expert outputs in FP32 for consistent BF16 routing. + combined = torch.zeros_like(valid, dtype=torch.float32) + for expert_id, expert in enumerate(self.experts): + token_ids, slots = (expert_ids == expert_id).nonzero(as_tuple=True) + if token_ids.numel(): + values = expert(valid.index_select(0, token_ids)) + weighted = values.float() * weights[token_ids, slots, None] + combined = combined.index_add(0, token_ids, weighted) + output = torch.zeros_like(flat).index_copy(0, selected_tokens, combined.to(flat.dtype)) + counts = torch.bincount(expert_ids.flatten(), minlength=self.expert_count).detach() + n_valid = probabilities.new_tensor(len(valid)) + stats = { + "assignment_counts": counts, + "probability_sum": probabilities.sum(dim=0), + "valid_tokens": n_valid, + "top_k": self.top_k, + "processed_assignments": counts.sum(), + "dropped_assignments": counts.new_zeros(()), + "entropy_sum": -(probabilities * probabilities.clamp_min(1e-30).log()).sum().detach(), + "selected_mass_sum": top_weights.sum().detach(), + } + return self.dropout(output.view_as(x)), stats + + +def combine_router_fractions(stats_by_microbatch: Sequence[Sequence[dict]]): + """Combine detached counts before a replay that computes exact batch aux. + + Counts are per executed block (thus distinguish Loop passes). Replay must + restore dropout RNG state, so its hard routes equal the counting pass. + """ + if not stats_by_microbatch or not stats_by_microbatch[0]: + return [], 0 + layers = len(stats_by_microbatch[0]) + if any(len(stats) != layers for stats in stats_by_microbatch): + raise ValueError("All microbatches must have the same executed routing layers") + total = sum(stats[0]["valid_tokens"] for stats in stats_by_microbatch) + fractions = [] + for layer in range(layers): + counts = sum(stats[layer]["assignment_counts"] for stats in stats_by_microbatch) + fractions.append( + counts.float() / (total * stats_by_microbatch[0][layer]["top_k"]).clamp_min(1) + ) + return fractions, total + + +def router_balance_loss(stats, assignment_fractions=None, total_valid_tokens=None): + """N * sum(f * p), averaged over executed layers. + + With externally supplied whole-batch fractions and denominator, this returns + the current microbatch's additive contribution to the exact batch objective. + Assignment fractions are discrete and intentionally detached. + """ + if not stats: + return torch.tensor(0.0) + if assignment_fractions is not None and len(assignment_fractions) != len(stats): + raise ValueError("One assignment-fraction vector is required per executed layer") + losses = [] + for index, record in enumerate(stats): + count = record["valid_tokens"] + denominator = count if total_valid_tokens is None else total_valid_tokens + denominator = torch.as_tensor(denominator, device=count.device).clamp_min(1) + fractions = ( + record["assignment_counts"].float() / (count * record["top_k"]).clamp_min(1) + if assignment_fractions is None + else assignment_fractions[index].detach() + ) + probabilities = record["probability_sum"] / denominator + losses.append(probabilities.numel() * (fractions * probabilities).sum()) + return torch.stack(losses).mean() + + +class ParametricGPT(ReproductionGPT): + def __init__(self, config, architecture="D8", module_seed=0): + blocks, repeats, kind = ARMS[architecture] + # Always initialize the same independent eight blocks before slicing. + config.n_layer = 8 + super().__init__(config, repeats=repeats) + self.transformer.h = nn.ModuleList(list(self.transformer.h)[:blocks]) + self.config.n_layer = blocks + self.architecture, self.kind, self.module_seed = architecture, kind, module_seed + with torch.random.fork_rng(devices=[]): + torch.manual_seed(module_seed) + if kind in {"wide", "moe"}: + for block in self.transformer.h: + if kind == "moe": + block.mlp = DroplessMoE(config) + else: + block.mlp = GPT2MLP(16 * config.n_embd, config) + _initialize_mlp(block.mlp, config.initializer_range) + elif kind in {"mhc", "identity_mhc"}: + self.connections = nn.ModuleList( + HyperConnection(config.n_embd, index, identity=kind == "identity_mhc") + for index in range(2 * blocks) + ) + + def _attention(self, block, x): + cfg = self.config + batch, length = x.shape[:2] + q, k, v = block.attn.c_attn(block.ln_1(x)).split(cfg.n_embd, dim=2) + shape = (batch, 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(batch, length, cfg.n_embd)) + return F.dropout(y, cfg.resid_pdrop, self.training) + + def forward(self, tokens, positions=None, *, valid_mask=None, return_aux=False): + if valid_mask is not None and ( + valid_mask.shape != tokens.shape or valid_mask.dtype != torch.bool + ): + raise ValueError("valid_mask must be boolean and have the tokens' shape") + if self.kind in {"dense", "wide"}: + logits = super().forward(tokens, positions) + if return_aux: + return logits, {"balance_loss": logits.new_zeros(()), "router_stats": []} + return logits + 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) + stats = [] + if self.kind in {"mhc", "identity_mhc"}: + x = x.unsqueeze(-2).expand(-1, -1, 4, -1) + for _ in range(self.repeats): + for index, block in enumerate(t.h): + if self.kind == "moe": + x = x + self._attention(block, x) + y, layer_stats = block.mlp(block.ln_2(x), valid_mask) + x = x + y + stats.append(layer_stats) + else: + x = self.connections[2 * index](x, lambda z, b=block: self._attention(b, z)) + x = self.connections[2 * index + 1](x, lambda z, b=block: b.mlp(b.ln_2(z))) + if self.kind in {"mhc", "identity_mhc"}: + x = x.mean(dim=-2) + x = t.ln_f(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, t.wte.weight) + if return_aux: + loss = router_balance_loss(stats) if stats else logits.new_zeros(()) + return logits, {"balance_loss": loss, "router_stats": stats} + return logits + + +def construct(config, spec, device): + """Historical config/spec convention, extended by ``spec['architecture']``.""" + architecture = spec["architecture"] + if architecture not in ARMS: + raise ValueError(f"Unknown architecture: {architecture}") + torch.manual_seed(spec["initialization"]) + cfg = GPT2Config( + vocab_size=config["vocab_size"], + n_positions=config.get("positions", 1024), + n_embd=config["hidden_size"], + n_head=config.get("attention_heads", config.get("heads", 12)), + n_layer=8, + resid_pdrop=config["dropout"], + embd_pdrop=config["dropout"], + attn_pdrop=config["dropout"], + activation_function="gelu_new", + use_cache=False, + ) + # Separate reproducible new-shape RNG, explicitly recorded in the manifest. + module_seed = spec.get("module_initialization", spec["initialization"] + 1_000_003) + model = ParametricGPT(cfg, architecture, module_seed) + model.initialization_seed = spec["initialization"] + return model.to(device) + + +def optimizer_for(model, lr, decay): + groups = [{"params": [], "weight_decay": decay}, {"params": [], "weight_decay": 0.0}] + for name, parameter in model.named_parameters(): + if not parameter.requires_grad: + continue + exempt = any(part in name for part in ("bias", "ln")) + exempt |= name.startswith("connections.") and (".norm." in name or ".alpha_" in name) + groups[int(exempt)]["params"].append(parameter) + return torch.optim.AdamW( + groups, lr=lr, betas=(0.9, 0.999), eps=1e-8, fused=next(model.parameters()).is_cuda + ) + + +def parameter_ledger(model): + d, layers = model.config.n_embd, len(model.transformer.h) + total = sum(parameter.numel() for parameter in model.parameters()) + expert = sum(p.numel() for n, p in model.named_parameters() if ".experts." in n) + controller = sum(p.numel() for n, p in model.named_parameters() if n.startswith("connections.")) + router = sum(p.numel() for n, p in model.named_parameters() if ".router." in n) + fixed = (model.config.vocab_size + model.config.n_positions) * d + 2 * d + attention_and_norms = 4 * d * d + 8 * d + if model.kind == "moe": + per_block = attention_and_norms + 8 * (4 * d * d + 3 * d) + 8 * d + else: + width = (16 if model.kind == "wide" else 4) * d + per_block = attention_and_norms + 2 * d * width + width + d + expected_controller = 0 + if model.kind in {"mhc", "identity_mhc"}: + n = 4 + count = 2 * n + (n * n if model.kind == "mhc" else 0) + alphas = 3 if model.kind == "mhc" else 2 + expected_controller = 2 * layers * (n * d * count + n * d + count + alphas) + if controller != expected_controller: + raise AssertionError( + f"Controller parameter mismatch: {controller} != {expected_controller}" + ) + expected = fixed + layers * per_block + expected_controller + if total != expected: + raise AssertionError(f"Parameter ledger mismatch: {total} != {expected}") + return { + "architecture": model.architecture, + "total_parameters": total, + "trainable_parameters": sum(p.numel() for p in model.parameters() if p.requires_grad), + "expected_parameters": expected, + "expert_parameters": expert, + "router_parameters": router, + "controller_parameters": controller, + "nominal_parameters_selected_per_token": total - expert + expert // 4, + "active_parameter_convention": ( + "All nonexpert parameters (including whole embedding table) plus two of eight " + "experts; not FLOPs or touched embedding rows." + ), + "unique_blocks": layers, + "repeats": model.repeats, + "executed_blocks": layers * model.repeats, + "residual_streams": 4 if controller else 1, + "parameter_dtype": str(next(model.parameters()).dtype), + "residual_dtype_under_bf16_autocast": "torch.float32 with FP32 parameters", + "controller_dtype": "torch.float32", + } + + +def flop_ledger(model, *, executed_tokens, projected_positions, attention_pairs, valid_tokens=None): + """Leading forward matmuls with actual padding/dispatch/readout counts. + + ``attention_pairs`` is sum(B*T*T) over microbatches, before block count. + Training 3x is explicitly an approximation; Sinkhorn autograd, scalar ops, + and a counting/replay pass are not silently folded into this estimate. + """ + d, blocks = model.config.n_embd, len(model.transformer.h) * model.repeats + valid_tokens = executed_tokens if valid_tokens is None else valid_tokens + attention = blocks * (8 * executed_tokens * d * d + 4 * attention_pairs * d) + readout = 2 * projected_positions * d * model.config.vocab_size + router = controller = 0 + if model.kind == "moe": + ffn = blocks * 4 * valid_tokens * d * (2 * 2 * d) + router = blocks * 2 * valid_tokens * d * 8 + else: + inner = (16 if model.kind == "wide" else 4) * d + ffn = blocks * 4 * executed_tokens * d * inner + if model.kind in {"mhc", "identity_mhc"}: + n = 4 + count = 2 * n + (n * n if model.kind == "mhc" else 0) + controller = ( + 2 * blocks * (2 * executed_tokens * n * d * count + 2 * executed_tokens * d * count) + ) + forward = attention + readout + ffn + router + controller + return { + "forward_attention_matmul_flops": attention, + "forward_ffn_matmul_flops": ffn, + "forward_readout_matmul_flops": readout, + "forward_router_matmul_flops": router, + "forward_controller_matmul_flops": controller, + "forward_leading_matmul_flops": forward, + "estimated_matmul_training_flops": 3 * forward, + "sinkhorn_normalization_passes": 39 if model.kind == "mhc" else 0, + "sinkhorn_matrix_elements_per_forward": 2 * blocks * executed_tokens * 16 + if model.kind == "mhc" + else 0, + "selected_expert_assignments": blocks * valid_tokens * 2 if model.kind == "moe" else 0, + "executed_input_tokens": executed_tokens, + "effective_input_tokens": valid_tokens, + "projected_positions": projected_positions, + "excluded_ops": ( + "Nonlinearities, normalization, dropout, dispatch/index-add, softmax, Sinkhorn " + "scalar arithmetic/autograd, final mean, counting/replay and optimizer; " + "3x is approximate." + ), + } + + +def initialization_manifest(model): + """CPU-byte hashes of each actual initialized tensor; no sampled hash.""" + shared, introduced = {}, {} + for name, tensor in model.state_dict().items(): + is_new = name.startswith("connections.") or ( + model.kind in {"moe", "wide"} and ".mlp." in name + ) + raw = tensor.detach().cpu().contiguous().reshape(-1).view(torch.uint8).numpy().tobytes() + (introduced if is_new else shared)[name] = hashlib.sha256(raw).hexdigest() + return { + "architecture": model.architecture, + "reference_initialization": getattr(model, "initialization_seed", None), + "module_initialization": model.module_seed, + "reference_blocks_before_slicing": 8, + "shared_tensor_sha256": shared, + "introduced_tensor_sha256": introduced, + } diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/parametric_architecture_train.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/parametric_architecture_train.py new file mode 100644 index 0000000000000000000000000000000000000000..55c77a2f48a116b87a2159b90bb2ab76a6730887 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/parametric_architecture_train.py @@ -0,0 +1,626 @@ +"""Resumable, exposure-matched training for the parametric architecture study. + +The ordinary data stream, answer-plus-EOS objective and generated evaluator are +shared with the historical experiment. MoE balancing is computed over the true +effective batch using an RNG-replayed routing pass, not a sum of local products. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import random +import time +from pathlib import Path + +import numpy as np +import torch +import transformers +from transformers import GPT2TokenizerFast + +from . import realworld_composition as historical +from .grok_depth import utc +from .grokking_reproduction import model_digest +from .realworld_composition_data import sha256, write_json + + +def _architecture(): + from . import parametric_architecture + + return parametric_architecture + + +def rng_state(device): + state = { + "python": random.getstate(), + "numpy": np.random.get_state(), + "cpu": torch.get_rng_state(), + } + if torch.device(device).type == "cuda": + state["cuda"] = torch.cuda.get_rng_state(device) + return state + + +def restore_rng(state, device): + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["cpu"].cpu()) + if "cuda" in state: + torch.cuda.set_rng_state(state["cuda"].cpu(), device) + + +def pack(records, pad, device): + """EOS is a valid input token; validity comes from lengths, never token IDs.""" + tokens, positions, labels = historical.pack(records, pad, device) + lengths = torch.tensor([len(r["encoded"]["input"]) for r in records], device=device) + valid = torch.arange(tokens.shape[1], device=device)[None] < lengths[:, None] + return tokens, positions, labels, valid + + +def _synchronize(device): + if torch.device(device).type == "cuda": + torch.cuda.synchronize(device) + + +def _finite(value, name): + if not math.isfinite(float(value)): + raise FloatingPointError(f"Nonfinite {name}; this candidate must retain its failure") + + +def update(model, optimizer, records, spec, device, pad): + """One historical effective batch, with exact full-batch routing gradients. + + Hard assignment fractions have no gradient. A no-grad pass collects their + global values when there are multiple microbatches; replaying the same + dropout RNG realizes the same routing in the differentiable pass. One + microbatch already contains the full objective and needs no prepass. + """ + if not records: + raise ValueError("An update requires at least one example") + microbatch = int(spec["microbatch_size"]) + if microbatch < 1: + raise ValueError("microbatch_size must be positive") + api = _architecture() + model.train() + optimizer.zero_grad(set_to_none=True) + chunks = [records[i : i + microbatch] for i in range(0, len(records), microbatch)] + is_moe = spec["architecture"] in {"M8", "M4", "LM4R2"} + needs_prepass = is_moe and len(chunks) > 1 + coefficient = float(spec.get("balance_coefficient", 0.01)) if is_moe else 0.0 + global_fractions, total_tokens, collected = None, None, [] + if needs_prepass: + before = rng_state(device) + try: + with torch.no_grad(): + for chunk in chunks: + tokens, positions, _, valid = pack(chunk, pad, device) + with historical.autocast(device): + _, aux = model(tokens, positions, valid_mask=valid, return_aux=True) + collected.append(aux["router_stats"]) + global_fractions, total_tokens = api.combine_router_fractions(collected) + finally: + restore_rng(before, device) + answer_loss, balance_loss = 0.0, 0.0 + executed, readout, attention = 0, 0, 0 + replay_count_error = torch.zeros((), dtype=torch.int64, device=device) + for chunk_index, chunk in enumerate(chunks): + tokens, positions, labels, valid = pack(chunk, pad, device) + with historical.autocast(device): + logits, aux = model(tokens, positions, valid_mask=valid, return_aux=True) + answer = historical.example_losses(logits, labels).sum() / len(records) + balance = ( + api.router_balance_loss( + aux["router_stats"], + assignment_fractions=global_fractions, + total_valid_tokens=total_tokens, + ) + if is_moe + else answer.new_zeros(()) + ) + loss = answer + coefficient * balance + if needs_prepass: + replay_count_error += sum( + (left["assignment_counts"] - right["assignment_counts"]).abs().sum() + for left, right in zip(collected[chunk_index], aux["router_stats"], strict=True) + ) + elif is_moe: + collected = [aux["router_stats"]] + global_fractions, total_tokens = api.combine_router_fractions(collected) + _finite(loss.detach(), "objective") + loss.backward() + answer_loss += float(answer.detach()) + balance_loss += float(balance.detach()) + executed += tokens.numel() + readout += positions.numel() + attention += len(chunk) * tokens.shape[1] ** 2 + if int(replay_count_error) != 0: + raise RuntimeError("MoE RNG replay did not reproduce routing assignment counts") + norm = torch.nn.utils.clip_grad_norm_( + model.parameters(), float(spec.get("clip_grad_norm", 1.0)), error_if_nonfinite=True + ) + _finite(norm, "gradient norm") + optimizer.step() + effective = sum(len(r["encoded"]["input"]) for r in records) + result = { + "loss": answer_loss, + "answer_ce": answer_loss, + "balance_loss": balance_loss, + "balance_coefficient": coefficient, + "objective": answer_loss + coefficient * balance_loss, + "gradient_norm": float(norm), + "executed_input_tokens": executed, + "effective_input_tokens": effective, + "padding_input_tokens": executed - effective, + "readout_positions": readout, + "attention_token_pairs": attention, + "routing_prepass_executed_input_tokens": executed if needs_prepass else 0, + "routing_prepass_effective_input_tokens": effective if needs_prepass else 0, + } + result["compute"] = api.flop_ledger( + model, + executed_tokens=executed, + valid_tokens=effective, + projected_positions=readout, + attention_pairs=attention, + ) + prepass = result["compute"]["forward_leading_matmul_flops"] if needs_prepass else 0 + result["compute"]["routing_prepass_matmul_flops"] = prepass + result["estimated_matmul_training_flops"] = ( + result["compute"]["estimated_matmul_training_flops"] + prepass + ) + result["compute"]["estimated_total_training_matmul_flops"] = result[ + "estimated_matmul_training_flops" + ] + if is_moe: + layer_count = len(global_fractions) + assignments = torch.stack( + [sum(c[layer]["assignment_counts"] for c in collected) for layer in range(layer_count)] + ) + processed = torch.stack( + [ + sum(c[layer]["processed_assignments"] for c in collected) + for layer in range(layer_count) + ] + ) + dropped = sum(s["dropped_assignments"] for c in collected for s in c) + if int(dropped) != 0 or not torch.equal(processed, assignments.sum(-1)): + raise AssertionError("Dropless routing lost selected token assignments") + result["router"] = { + "assignment_fractions": torch.stack(global_fractions).detach().cpu().tolist(), + "assignment_counts": assignments.detach().cpu().tolist(), + "valid_tokens_per_layer": effective, + "selected_assignments_per_layer": assignments.sum(-1).detach().cpu().tolist(), + "processed_assignments_per_layer": processed.detach().cpu().tolist(), + "router_entropy_per_layer": torch.stack( + [ + sum(c[layer]["entropy_sum"] for c in collected) / effective + for layer in range(layer_count) + ] + ) + .detach() + .cpu() + .tolist(), + "selected_probability_mass_per_layer": torch.stack( + [ + sum(c[layer]["selected_mass_sum"] for c in collected) / effective + for layer in range(layer_count) + ] + ) + .detach() + .cpu() + .tolist(), + "dropped_assignments": int(dropped), + "replay_assignment_count_error": int(replay_count_error), + "replay_checked": needs_prepass, + "balance_scope": ( + "full_effective_batch_two_pass_rng_replay" + if needs_prepass + else "full_effective_batch_single_forward" + ), + } + return result + + +def selection_score(metrics): + """Frozen development panels only; no held-out-composition selection.""" + atomic, composition = metrics["atomic"]["nll"], metrics["train_composition"]["nll"] + if atomic is None or composition is None: + raise ValueError("Both fixed development panels need answer NLL measurements") + value = 0.5 * atomic + 0.5 * composition + _finite(value, "development selection NLL") + return value + + +def _routing_metrics(router): + """Expose numeric dictionaries to the existing W&B sidecar's flattening.""" + if not router: + return {} + return { + "dropped_assignments": router["dropped_assignments"], + "replay_assignment_count_error": router["replay_assignment_count_error"], + "layers": { + str(layer): { + "entropy": router["router_entropy_per_layer"][layer], + "selected_probability_mass": router["selected_probability_mass_per_layer"][layer], + "expert_fraction": {str(i): value for i, value in enumerate(fractions)}, + } + for layer, fractions in enumerate(router["assignment_fractions"]) + }, + } + + +def save_checkpoint(path, model, optimizer, stream, counts, step, counters, device, **extra): + path = Path(path) + temporary = path.with_suffix(".tmp") + torch.save( + { + "format_version": 1, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "step": step, + "counters": counters, + "rng": rng_state(device), + **extra, + }, + temporary, + ) + temporary.replace(path) + + +def load_checkpoint(path, model, optimizer, stream, device): + state = torch.load(path, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + stream.load_state_dict(state["stream"]) + restore_rng(state["rng"], device) + return state + + +def _identity(config, spec): + payload = { + "model": config["model"], + "spec": spec, + "data_sha256": config["data_sha256"], + "tokenizer_sha256": config.get("tokenizer_sha256", config.get("tokenizer_files", {})), + "source_files": config.get("source_files", {}), + } + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + + +def verify(config, config_path=None): + """Check the concrete execution freeze; the historical design is not mutated.""" + if config.get("launch_enabled") is False: + raise ValueError("This configuration explicitly disables execution") + if sha256(config["data_file"]) != config["data_sha256"]: + raise ValueError("Frozen data changed") + for name, expected in config.get("tokenizer_sha256", {}).items(): + path = Path(config["tokenizer"]) / name + if sha256(path) != expected: + raise ValueError(f"Frozen tokenizer changed: {path}") + for group in ("tokenizer_files", "source_files"): + for path, expected in config.get(group, {}).items(): + if sha256(path) != expected: + raise ValueError(f"Frozen {group} changed: {path}") + if config.get("source_root"): + root = Path(config["source_root"]).resolve() + for module in (Path(__file__), Path(_architecture().__file__), Path(historical.__file__)): + if not module.resolve().is_relative_to(root): + raise ValueError(f"Imported code is outside the frozen source_root: {module}") + if config_path is not None: + if not config.get("execution_lock"): + raise ValueError("CLI requires an execution_lock with the frozen config hash") + lock = json.loads(Path(config["execution_lock"]).read_text()) + if lock["config_sha256"] != sha256(config_path): + raise ValueError("Frozen configuration changed") + if "torch" in lock.get("environment", {}): + if str(torch.__version__) != lock["environment"]["torch"]: + raise ValueError("Frozen torch version changed") + if "transformers" in lock.get("environment", {}): + if transformers.__version__ != lock["environment"]["transformers"]: + raise ValueError("Frozen transformers version changed") + + +def _setup(device, config): + torch.set_num_threads(int(config.get("cpu_threads", 4))) + if torch.device(device).type == "cuda": + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.cuda.reset_peak_memory_stats(device) + + +def _resources(device): + if torch.device(device).type != "cuda": + return {"peak_gpu_memory_bytes": 0, "peak_gpu_reserved_bytes": 0} + return { + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device), + "peak_gpu_reserved_bytes": torch.cuda.max_memory_reserved(device), + } + + +def _process_identity(): + """Different containers can both run Python as PID 1; identify the namespace.""" + identity = {"pid": os.getpid()} + if Path("/proc/self/stat").exists(): + identity["pid_namespace"] = os.readlink("/proc/self/ns/pid") + identity["start_ticks"] = Path("/proc/self/stat").read_text().rsplit(")", 1)[1].split()[19] + return identity + + +def run(config, spec, out, device="cuda:0"): + """Train one frozen candidate. An independent process must subsequently audit.""" + verify(config) + _setup(device, config) + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "trained.json").exists(): + trained = json.loads((out / "trained.json").read_text()) + if trained["identity"] != _identity(config, spec): + raise ValueError("Existing output belongs to a different frozen training recipe") + return trained + api = _architecture() + data = json.loads(Path(config["data_file"]).read_text()) + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + records = data["atoms"] + data["train_compositions"] + model = api.construct(config["model"], spec, device) + optimizer = api.optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + stream = historical.BatchStream(len(records), spec["sampling_seed"]) + identity = _identity(config, spec) + counts = np.zeros(len(records), dtype=np.int64) + counters = { + "training_seconds": 0.0, + "examples": 0, + "supervised_tokens": 0, + "executed_input_tokens": 0, + "effective_input_tokens": 0, + "estimated_matmul_training_flops": 0, + "routing_prepass_executed_input_tokens": 0, + } + initial_step, wall_offset, history, last = 0, 0.0, [], {} + if (out / "latest.pt").exists(): + saved = load_checkpoint(out / "latest.pt", model, optimizer, stream, device) + if saved["identity"] != identity: + raise ValueError("Checkpoint belongs to a different frozen training recipe") + counts, initial_step, counters = saved["counts"], saved["step"], saved["counters"] + wall_offset, last = saved.get("wall_seconds", 0.0), saved.get("last_update", {}) + learning = out / "learning.json" + history = [r for r in json.loads(learning.read_text()) if r["step"] <= initial_step] + metadata = json.loads((out / "run.json").read_text()) + metadata.update(pid=os.getpid(), resumed_from_step=initial_step) + del saved + else: + torch.manual_seed(spec["dropout_seed"]) + random.seed(spec["dropout_seed"]) + np.random.seed(spec["dropout_seed"]) + metadata = { + "spec": spec, + "model": config["model"], + "phase": config.get("phase", "development"), + "evaluation_nodes": config["evaluation_nodes"], + "world_sha256": config["data_sha256"], + "initial_model_sha256": model_digest(model), + "initial_tensor_sha256": historical.tensor_digests(model), + "initialization_manifest": api.initialization_manifest(model), + "parameters": sum(p.numel() for p in model.parameters()), + "parameter_ledger": api.parameter_ledger(model), + "atomic_examples": len(data["atoms"]), + "composition_examples": len(data["train_compositions"]), + "vocab_size": len(tokenizer), + "dtype": "BF16 AMP; FP32 parameters and Adam states", + "device": str(device), + "gpu": torch.device(device).index or 0, + "gpu_name": torch.cuda.get_device_name(device) + if torch.device(device).type == "cuda" + else "cpu", + "pid": os.getpid(), + "job_type": config.get("phase", "development") + "-training", + "tracking_group": config.get("tracking", {}).get("group", config.get("experiment")), + "learning_step_unit": "optimizer_updates", + "identity": identity, + "selection": "0.5 atomic + 0.5 train-composition NLL on original fixed panels", + "selection_panel_sizes": { + key: len(data["panels"][key]) for key in ("atomic", "train_composition") + }, + "moe_balance": ( + "full-effective-batch; single forward when one microbatch, otherwise two-pass " + "RNG replay; actual prepass compute included" + ), + "learning_rate_schedule": "historical lr * min((step - 1) / warmup_steps, 1)", + } + if config.get("execution_lock"): + metadata["execution_lock_sha256"] = sha256(config["execution_lock"]) + write_json(out / "run.json", metadata) + write_json(out / "learning.json", history) + nodes = set(config["evaluation_nodes"]) | {int(spec["steps"])} + log_interval = int(config.get("log_interval", 100)) + checkpoint_interval = int(config.get("resume_checkpoint_interval", 1000)) + started = time.perf_counter() + + def checkpoint(step): + save_checkpoint( + out / "latest.pt", + model, + optimizer, + stream, + counts, + step, + counters, + device, + identity=identity, + wall_seconds=wall_offset + time.perf_counter() - started, + last_update=last, + ) + + for step in range(initial_step, spec["steps"] + 1): + if step > initial_step: + warmup = int(spec["warmup_steps"]) + lr = spec["learning_rate"] * (min((step - 1) / warmup, 1.0) if warmup else 1.0) + for group in optimizer.param_groups: + group["lr"] = lr + ids = stream.batch(spec["batch_size"]) + selected = [records[i] for i in ids] + _synchronize(device) + begin = time.perf_counter() + last = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id) + _synchronize(device) + counters["training_seconds"] += time.perf_counter() - begin + 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", + "routing_prepass_executed_input_tokens", + ): + counters[key] += last[key] + if step in nodes or step % log_interval == 0: + if not any(r["step"] == step for r in history): + metrics = {} + if step in nodes: + metrics, predictions = historical.evaluate_dataset( + model, data, tokenizer, device + ) + write_json(out / f"predictions-{step:07d}.json", predictions) + metrics["selection"] = { + "mixed_answer_nll": selection_score(metrics), + "atomic_n": metrics["atomic"]["nll_n"], + "train_composition_n": metrics["train_composition"]["nll_n"], + } + if last.get("router"): + metrics["routing"] = _routing_metrics(last["router"]) + record = { + "step": step, + "metrics": metrics, + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "loss": last.get("answer_ce"), + "answer_ce": last.get("answer_ce"), + "balance_loss": last.get("balance_loss"), + "objective": last.get("objective"), + "gradient_norm": last.get("gradient_norm"), + "learning_rate": optimizer.param_groups[0]["lr"], + "atomic_epochs": float(counts[: len(data["atoms"])].mean()), + "composition_epochs": float(counts[len(data["atoms"]) :].mean()), + "router": last.get("router", {}), + "compute_per_update": last.get("compute", {}), + **_resources(device), + "created_utc": utc(), + } + history.append(record) + write_json(out / "learning.json", history) + print( + json.dumps({"step": step, "loss": record["loss"], "metrics": metrics}), + flush=True, + ) + write_json( + out / "status.json", + { + "state": "training", + "step": step, + "target_step": spec["steps"], + "loss": last.get("answer_ce"), + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "pid": os.getpid(), + "updated_utc": utc(), + }, + ) + if step in nodes or (step > initial_step and step % checkpoint_interval == 0): + checkpoint(step) + if step in nodes: + target = out / f"checkpoint-{step:07d}.pt" + temporary = target.with_suffix(".tmp") + torch.save( + {"model": model.state_dict(), "step": step, "identity": identity}, temporary + ) + temporary.replace(target) + np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts) + metrics, predictions = historical.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(), + "process_identity": _process_identity(), + "identity": identity, + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + **counters, + "selection_mixed_answer_nll": next( + r["metrics"]["selection"]["mixed_answer_nll"] + for r in reversed(history) + if r["step"] == spec["steps"] + ), + "wall_seconds": wall_offset + time.perf_counter() - started, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + return result + + +def audit(config, spec, out, device="cuda:0"): + """Reconstruct and regenerate the full endpoint in an independent process.""" + verify(config) + _setup(device, config) + out = Path(out) + trained = json.loads((out / "trained.json").read_text()) + same_process = ( + trained["process_identity"] == _process_identity() + if "process_identity" in trained + else trained["pid"] == os.getpid() + ) + if same_process: + raise ValueError("Independent audit must run in a different process") + if trained["identity"] != _identity(config, spec): + raise ValueError("Audit recipe differs from the training freeze") + if sha256(out / "latest.pt") != trained["checkpoint_sha256"]: + raise ValueError("Training checkpoint changed") + model = _architecture().construct(config["model"], spec, device) + checkpoint = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) + if checkpoint["step"] != spec["steps"]: + raise ValueError("Final checkpoint does not contain the requested endpoint") + model.load_state_dict(checkpoint["model"]) + del checkpoint + if model_digest(model) != trained["model_sha256"]: + raise ValueError("Reloaded model does not match the trained endpoint") + data = json.loads(Path(config["data_file"]).read_text()) + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + metrics, predictions = historical.evaluate_dataset( + model, data, tokenizer, device, full=True, autonomous=True + ) + if predictions != json.loads((out / "endpoint-predictions.json").read_text()): + raise AssertionError("Independent endpoint generation or NLL failed exact reproduction") + if metrics != json.loads((out / "endpoint.json").read_text()): + raise AssertionError("Independent endpoint metric recount failed") + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "process_identity": _process_identity(), + "source_process_identity": trained.get("process_identity"), + "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, + }, + ) + return result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/qwen_constraints.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/qwen_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..6181f6dad22ab1a99443ffddb19f67c7c6ad701b --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/qwen_constraints.py @@ -0,0 +1,94 @@ +"""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) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/qwen_path_learning.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/qwen_path_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..bc113a47da9c9fc22e346812c7f48f5ae7bc8b92 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/qwen_path_learning.py @@ -0,0 +1,416 @@ +"""Position-routed down updates, complete-answer objectives, and audited data helpers.""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import time +from datetime import datetime, timezone +from pathlib import Path + +os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") +os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import AutoModelForCausalLM, AutoTokenizer + +from .hebbian_data import TEMPLATE, encode_answer, score_answer +from .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 articles diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/qwen_path_train.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/qwen_path_train.py new file mode 100644 index 0000000000000000000000000000000000000000..fabb31112396100c708fafd83993acdb8c46f918 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/qwen_path_train.py @@ -0,0 +1,627 @@ +"""Frozen-matrix execution and development-only selection for path learning.""" + +from __future__ import annotations + +import json +import os +import platform +import shutil +import time + +import numpy as np +import torch +import 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 result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/realworld_composition.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/realworld_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..a05d1c9d956093315cedab365228e2fce72b6022 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/realworld_composition.py @@ -0,0 +1,629 @@ +"""Complete GPT/Loop training on original 2Wiki questions and atomic facts.""" + +from __future__ import annotations + +import copy +import hashlib +import json +import math +import os +import time +from contextlib import nullcontext +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import GPT2Config, GPT2TokenizerFast + +from .grok_depth import utc +from .grokking_reproduction import ReproductionGPT, model_digest +from .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), + canonical_answer_globally_unambiguous=row.get( + "canonical_answer_globally_unambiguous", True + ), + 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_unambiguous_canonical_answers": lambda r: r.get( + "canonical_answer_globally_unambiguous", True + ), + "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) + 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": row["id"], + "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": bool(row.get("unambiguous_answers", [])), + "canonical_answer_globally_unambiguous": row.get( + "canonical_answer_globally_unambiguous", True + ), + "invalid_generated_bridge_length": True, + } + for row 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, wall_seconds=None): + 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, + "wall_seconds": wall_seconds, + "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) + phase = config.get("phase", "development") + out = Path(config["results_root"]) / phase / 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 = checkpoint.get("wall_seconds") + if wall_offset is None: + wall_offset = history[-1]["wall_seconds"] if history else 0.0 + metadata = json.loads((out / "run.json").read_text()) + metadata.update(pid=os.getpid(), gpu=gpu, resumed_from_step=initial_step) + write_json(out / "run.json", metadata) + del checkpoint + else: + torch.manual_seed(spec["dropout_seed"]) + metadata = { + "spec": spec, + "model": config["model"], + "phase": phase, + "evaluation_nodes": config["evaluation_nodes"], + "execution_lock_sha256": sha256(config["execution_lock"]), + "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": phase + "-training", + "tracking_group": config["tracking"]["group"], + } + 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, + "training_seconds": counters["training_seconds"], + "examples": counters["examples"], + "wall_seconds": wall_offset + time.perf_counter() - started, + "pid": os.getpid(), + "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, + wall_offset + time.perf_counter() - started, + ) + 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, + ) + elif ( + step > initial_step and step % config.get("resume_checkpoint_interval", 1000000000) == 0 + ): + save_checkpoint( + out / "latest.pt", + model, + optimizer, + stream, + counts, + step, + counters, + wall_offset + time.perf_counter() - started, + ) + 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"]) / config.get("phase", "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}, + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/realworld_composition_data.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/realworld_composition_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e907ece415c9c6e027e965818c1b8e6f82a2462e --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/realworld_composition_data.py @@ -0,0 +1,270 @@ +"""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 which +evaluation facts may be learned separately, never with evaluation chain labels. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import string +import zipfile +from collections import Counter, defaultdict +from 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]} diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/realworld_confirmation.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/realworld_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..5cfed1010e1cc6f386e54d10c69675d34f4bed4a --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/realworld_confirmation.py @@ -0,0 +1,322 @@ +"""Data-only confirmation isolation and independent endpoint recounting.""" + +from __future__ import annotations + +import ast +import copy +import json +import re +import statistics +import string +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from .realworld_composition_data import normalize_answer, order, sha256, write_json + + +def head_bridge_names(data, canonical, aliases): + names = defaultdict(set) + for row in data["train_compositions"] + data["evaluation_compositions"]: + for index in (0, 2): + identifier = row["edges"][0][index] + labels = [canonical[identifier], row["surfaces"][0][index]] + for label in labels + aliases.get(identifier, []): + normalized = normalize_answer(label) + if normalized: + names[identifier].add(normalized) + return names + + +def answer_owners(canonical, aliases): + owners = defaultdict(set) + for identifier in set(canonical) | set(aliases): + for name in [canonical.get(identifier, ""), *aliases.get(identifier, [])]: + normalized = normalize_answer(name) + if normalized: + owners[normalized].add(identifier) + return owners + + +def isolate_confirmation(candidate, development, canonical, aliases): + """Exclude every chain touching a development head/bridge name, then rebuild.""" + dev_names = set().union(*head_bridge_names(development, canonical, aliases).values()) + formal_names = head_bridge_names(candidate, canonical, aliases) + excluded_entities = {e for e, names in formal_names.items() if names & dev_names} + excluded = {} + parts = {} + for key in ("train_compositions", "evaluation_compositions"): + excluded[key] = [ + r["id"] + for r in candidate[key] + if {r["edges"][0][0], r["edges"][0][2]} & excluded_entities + ] + excluded_ids = set(excluded[key]) + parts[key] = [copy.deepcopy(r) for r in candidate[key] if r["id"] not in excluded_ids] + all_chains = parts["train_compositions"] + parts["evaluation_compositions"] + used = {a for r in all_chains for a in r["atom_ids"]} + atoms = [copy.deepcopy(r) for r in candidate["atoms"] if r["id"] in used] + first, second = ({r["atom_ids"][i] for r in parts["train_compositions"]} for i in (0, 1)) + seen = first | second + direct = {(r["edge"][0], r["edge"][2]) for r in atoms} + pairs = {(r["edges"][0][0], r["edges"][1][2]) for r in parts["train_compositions"]} + operations = {tuple(e[1] for e in r["edges"]) for r in parts["train_compositions"]} + owners = answer_owners(canonical, aliases) + for row in atoms + all_chains: + identifier = row["edge"][2] if "edge" in row else row["edges"][1][2] + row["canonical_answer_globally_unambiguous"] = owners[normalize_answer(row["answer"])] == { + identifier + } + for row in all_chains: + a, b = row["atom_ids"] + row["role"] = ("I" if a in seen else "O") + ("I" if b in seen else "O") + row["required_role"] = ("I" if a in first else "O") + ("I" if b in second else "O") + pair = row["edges"][0][0], row["edges"][1][2] + row["known_direct_shortcut"] = pair in direct + row["head_tail_seen_in_combination_training"] = pair in pairs + row["operation_seen"] = tuple(e[1] for e in row["edges"]) in operations + panels = { + "test_" + role.lower(): [ + r["id"] + for r in sorted( + [r for r in parts["evaluation_compositions"] if r["role"] == role], + key=lambda r: order(r["id"], "panel:"), + )[:64] + ] + for role in ("II", "IO", "OI", "OO") + } + panels["train_composition"] = [ + r["id"] + for r in sorted(parts["train_compositions"], key=lambda r: order(r["id"], "panel:"))[:128] + ] + selected = {i for ids in panels.values() for i in ids} + required = {a for r in all_chains if r["id"] in selected for a in r["atom_ids"]} + panels["atomic"] = sorted( + required + | {r["id"] for r in sorted(atoms, key=lambda r: order(r["id"], "atom-panel:"))[:128]} + ) + data = {"atoms": atoms, **parts, "panels": panels} + report = { + "rule": ( + "Exclude chains whose head/bridge canonical, annotated surface or official alias " + "name overlaps development head/bridge names after author normalization; " + "retain shared tails." + ), + "excluded_entities": sorted(excluded_entities), + "excluded_case_ids": excluded, + "excluded_counts": {key: len(ids) for key, ids in excluded.items()}, + "colliding_names": sorted(dev_names & set().union(*formal_names.values())), + "model_results_used": False, + } + return data, report + + +def audit_confirmation(data, development, canonical, aliases): + """Recount from the selected records rather than selection bookkeeping.""" + atoms = {r["id"]: r for r in data["atoms"]} + train, held = data["train_compositions"], data["evaluation_compositions"] + rows = train + held + dev_names = head_bridge_names(development, canonical, aliases) + formal_names = head_bridge_names(data, canonical, aliases) + assert not set(dev_names) & set(formal_names) + assert not set().union(*dev_names.values()) & set().union(*formal_names.values()) + assert len(atoms) == len(data["atoms"]) + assert len({r["id"] for r in rows}) == len(rows) + + def chain(row): + return tuple(tuple(e) for e in row["edges"]) + + assert not {chain(r) for r in train} & {chain(r) for r in held} + held_questions = {normalize_answer(r["question"]) for r in held} + assert not {normalize_answer(r["question"]) for r in train} & held_questions + assert not {normalize_answer(r["question"]) for r in atoms.values()} & held_questions + assert not {normalize_answer(r["question"]) for r in atoms.values()} & { + normalize_answer(r["question"]) for r in development["atoms"] + } + seen = {a for r in train for a in r["atom_ids"]} + first, second = ({r["atom_ids"][i] for r in train} for i in (0, 1)) + owners = answer_owners(canonical, aliases) + for row in rows: + a, b = row["atom_ids"] + assert [atoms[a]["edge"], atoms[b]["edge"]] == row["edges"] + assert row["edges"][0][2] == row["edges"][1][0] + assert row["role"] == ("I" if a in seen else "O") + ("I" if b in seen else "O") + assert row["required_role"] == ("I" if a in first else "O") + ("I" if b in second else "O") + assert not row["structural_errors"] + assert not any(r["known_prior_case"] for r in held) + for pool in (list(atoms.values()), train, held): + prompt_answers = defaultdict(set) + for row in pool: + prompt_answers[normalize_answer(row["question"])].add(normalize_answer(row["answer"])) + identifier = row["edge"][2] if "edge" in row else row["edges"][1][2] + assert row["canonical_answer_globally_unambiguous"] == ( + owners[normalize_answer(row["answer"])] == {identifier} + ) + e = row["encoded"] + assert e["target"][-1] == 50256 and len(e["target"]) <= 64 + assert e["input"] == (e["prefix"] + e["target"])[:-1] + assert len(e["prefix"]) + len(e["target"]) <= 256 + assert all(len(answers) == 1 for answers in prompt_answers.values()) + panel_ids = {i for name, ids in data["panels"].items() if name != "atomic" for i in ids} + assert {a for r in rows if r["id"] in panel_ids for a in r["atom_ids"]} <= set( + data["panels"]["atomic"] + ) + return { + "passed": True, + "atoms": len(atoms), + "train_compositions": len(train), + "evaluation_compositions": len(held), + "evaluation_roles": dict(Counter(r["role"] for r in held)), + "required_role_counts": dict(Counter(r["required_role"] for r in held)), + "canonical_unambiguous_evaluation_count": sum( + r["canonical_answer_globally_unambiguous"] for r in held + ), + "panels": {name: len(ids) for name, ids in data["panels"].items()}, + "head_bridge_id_overlap": 0, + "head_bridge_normalized_name_overlap": 0, + "necessary_atomic_coverage": 1.0, + "known_direct_shortcuts": sum(r["known_direct_shortcut"] for r in held), + "unseen_operations": sum(not r["operation_seen"] for r in held), + "max_input_tokens": max(len(r["encoded"]["input"]) for r in list(atoms.values()) + rows), + "atomic_relations": dict(Counter(r["edge"][1] for r in atoms.values())), + "train_relation_pairs": dict(Counter(" -> ".join(e[1] for e in r["edges"]) for r in train)), + } + + +def finalize_confirmation(config): + """Independently score raw outputs using the pinned author's scorer functions.""" + root, art = Path(config["results_root"]), Path(config["artifact_root"]) + data = json.loads(Path(config["data_file"]).read_text()) + scorer = Path(config["official_scorer"]) + scope = dict(re=re, string=string, Counter=Counter) + tree = ast.parse(scorer.read_text()) + functions = [ + n + for n in tree.body + if isinstance(n, ast.FunctionDef) and n.name in {"normalize_answer", "exact_match_score"} + ] + exec(compile(ast.Module(body=functions, type_ignores=[]), str(scorer), "exec"), scope) + + def score(prediction, row): + return float( + any( + scope["exact_match_score"](prediction, g) + for g in [row["answer"], *row.get("aliases", [])] + ) + ) + + held = data["evaluation_compositions"] + summary, scores, atom_scores, exposures, metadata = {}, {}, {}, {}, {} + for spec in config["runs"]: + name = spec["name"] + out = root / config["phase"] / name + complete = json.loads((out / "complete.json").read_text()) + assert complete["step"] == spec["steps"] and complete["independently_reloaded"] + raw = json.loads((out / "endpoint-predictions.json").read_text()) + metrics = json.loads((out / "endpoint.json").read_text()) + for group, records in [ + ("atomic", data["atoms"]), + ("train_composition", data["train_compositions"]), + ("test_all", held), + ]: + by_id = {p["id"]: p for p in raw[group]} + assert len(by_id) == len(records) == len(raw[group]) + assert set(by_id) == {r["id"] for r in records} + recomputed = {r["id"]: score(by_id[r["id"]]["prediction"], r) for r in records} + assert all(recomputed[i] == by_id[i]["alias_em"] for i in recomputed) + assert abs(sum(recomputed.values()) / len(records) - metrics[group]["alias_em"]) < 1e-12 + if group == "test_all": + scores[name] = recomputed + for role in ("II", "IO", "OI", "OO"): + selected = [r for r in held if r["role"] == role] + assert ( + abs( + sum(recomputed[r["id"]] for r in selected) / len(selected) + - metrics["test_" + role.lower()]["alias_em"] + ) + < 1e-12 + ) + if group == "atomic": + atom_scores[name] = recomputed + summary[name] = metrics + exposures[name] = { + step: np.load(out / f"exposure-{step:07d}.npz")["counts"] + for step in config["evaluation_nodes"] + } + metadata[name] = json.loads((out / "run.json").read_text()) + assert complete["checkpoint_sha256"] == sha256(out / "latest.pt") + comparisons = [] + for seed in sorted({s["initialization"] for s in config["runs"]}): + specs = {s["architecture"]: s for s in config["runs"] if s["initialization"] == seed} + assert set(specs) == {"standard8", "loop4x2", "standard4"} + names = [s["name"] for s in specs.values()] + assert len({metadata[n]["common_four_block_initial_sha256"] for n in names}) == 1 + for step in config["evaluation_nodes"]: + assert all( + np.array_equal(exposures[names[0]][step], exposures[n][step]) for n in names[1:] + ) + for baseline in ("standard8", "standard4"): + loop, base = specs["loop4x2"]["name"], specs[baseline]["name"] + for role in ("all", "OO"): + selected = held if role == "all" else [r for r in held if r["role"] == role] + common = [ + r + for r in selected + if all(atom_scores[n][a] for n in (loop, base) for a in r["atom_ids"]) + ] + comparisons.append( + { + "initialization": seed, + "baseline": baseline, + "pool": role, + "n": len(selected), + "paired_difference": sum( + scores[loop][r["id"]] - scores[base][r["id"]] for r in selected + ) + / len(selected), + "both_models_necessary_atoms_correct_n": len(common), + "both_models_necessary_atoms_correct_coverage": len(common) / len(selected), + "conditional_paired_difference": sum( + scores[loop][r["id"]] - scores[base][r["id"]] for r in common + ) + / len(common) + if common + else None, + } + ) + means = {} + for architecture in ("standard8", "loop4x2", "standard4"): + names = [s["name"] for s in config["runs"] if s["architecture"] == architecture] + means[architecture] = {} + for group in ( + "atomic", + "train_composition", + "test_all", + "test_ii", + "test_io", + "test_oi", + "test_oo", + "autonomous", + ): + values = [summary[n][group]["alias_em"] for n in names] + means[architecture][group] = { + "mean": statistics.mean(values), + "sample_sd": statistics.stdev(values), + "per_initialization": values, + } + result = { + "passed": True, + "runs": len(config["runs"]), + "scientific_updates": sum(s["steps"] for s in config["runs"]), + "independent_dataset_splits": 1, + "paired_initializations": 3, + "paired_exposures_equal_at_all_nodes": True, + "architecture_scores": means, + "paired_comparisons": comparisons, + "source_data_sha256": sha256(config["data_file"]), + "official_scorer_sha256": sha256(scorer), + } + write_json(art / "confirmation-summary.json", summary) + write_json(art / "confirmation-recount-audit.json", result) + return result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..1b6fcadbe2e7be2944fe6e398e29c0812ca1329f --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py @@ -0,0 +1,119 @@ +"""Registered relation/component and paired-knowledge trajectory descriptions.""" + +from __future__ import annotations + +import json +from collections import defaultdict +from pathlib import Path + +from .realworld_composition_data import write_json + + +def threshold_intervals(history, group, threshold): + passed = [r["metrics"][group]["alias_em"] >= threshold for r in history] + + def interval(index): + if index is None: + return None + return [history[index - 1]["step"] if index else None, history[index]["step"]] + + first = next((i for i, value in enumerate(passed) if value), None) + sustained = next((i for i, value in enumerate(passed) if value and all(passed[i:])), None) + return { + "first_observed_interval": interval(first), + "sustained_observed_interval": interval(sustained), + } + + +def analyze_confirmation(config): + root = Path(config["results_root"]) / config["phase"] + data = json.loads(Path(config["data_file"]).read_text()) + held = {r["id"]: r for r in data["evaluation_compositions"]} + endpoint_groups, thresholds, nodes = {}, {}, {} + for spec in config["runs"]: + name = spec["name"] + out = root / name + raw = json.loads((out / "endpoint-predictions.json").read_text())["test_all"] + by_relation, by_component = defaultdict(list), defaultdict(list) + for prediction in raw: + row = held[prediction["id"]] + by_relation[" -> ".join(e[1] for e in row["edges"])].append(prediction["alias_em"]) + by_component[row["group"]].append(prediction["alias_em"]) + endpoint_groups[name] = { + key: {k: {"n": len(v), "alias_em": sum(v) / len(v)} for k, v in groups.items()} + for key, groups in [ + ("relation_pair", by_relation), + ("source_head_bridge_component", by_component), + ] + } + history = json.loads((out / "learning.json").read_text()) + thresholds[name] = { + f"{group}_{value}": threshold_intervals(history, group, value) + for group, value in [("train_composition", 0.99), ("test_all", 0.5), ("test_all", 0.9)] + } + nodes[name] = {} + for step in config["evaluation_nodes"]: + node = json.loads((out / f"predictions-{step:07d}.json").read_text()) + nodes[name][step] = { + group: {r["id"]: r["alias_em"] for r in node[group]} + for group in ("atomic", "test_all") + } + trajectories = [] + for seed in sorted({s["initialization"] for s in config["runs"]}): + specs = {s["architecture"]: s for s in config["runs"] if s["initialization"] == seed} + loop = specs["loop4x2"]["name"] + for baseline in ("standard8", "standard4"): + base = specs[baseline]["name"] + for step in config["evaluation_nodes"]: + left, right = nodes[loop][step], nodes[base][step] + assert set(left["test_all"]) == set(right["test_all"]) + for pool in ("all", "OO"): + selected = [ + held[i] + for i in left["test_all"] + if pool == "all" or held[i]["role"] == pool + ] + common = [ + r + for r in selected + if all(n["atomic"][a] for n in (left, right) for a in r["atom_ids"]) + ] + trajectories.append( + { + "initialization": seed, + "baseline": baseline, + "step": step, + "pool": pool, + "panel_n": len(selected), + "both_models_necessary_atoms_correct_n": len(common), + "both_models_necessary_atoms_correct_coverage": len(common) + / len(selected), + "full_panel_paired_difference": sum( + left["test_all"][r["id"]] - right["test_all"][r["id"]] + for r in selected + ) + / len(selected), + "conditional_paired_difference": sum( + left["test_all"][r["id"]] - right["test_all"][r["id"]] + for r in common + ) + / len(common) + if common + else None, + } + ) + result = { + "endpoint_groups": endpoint_groups, + "threshold_intervals": thresholds, + "paired_knowledge_trajectories": trajectories, + "trajectory_scope": ( + "Fixed panels at registered nodes; threshold brackets are descriptive and do not " + "identify exact crossing times or establish grokking." + ), + "endpoint_scope": ( + "Full registered evaluation pool; source components are shared by questions, " + "not independent worlds." + ), + } + write_json(Path(config["artifact_root"]) / "confirmation-analysis.json", result) + return result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/recurrence_use.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/recurrence_use.py new file mode 100644 index 0000000000000000000000000000000000000000..3f2cf4432769a0bc1ea0278bf25468307718877b --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/recurrence_use.py @@ -0,0 +1,416 @@ +"""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 frequency +from creating additional scientific observations. +""" + +from __future__ import annotations + +import time + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import EOS, prompt_rows, truth_path_details +from .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, + } diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/representation_alignment.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/representation_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..923e412fdf09bfaf85ca6de1fcb11cf4d6e754de --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/representation_alignment.py @@ -0,0 +1,269 @@ +"""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 hashlib +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .latent_scaling import build_world, construct, model_digest +from .storage_composition import data_digest, evaluate, file_hash, pack_sentences +from .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}, + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/shared_cache.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/shared_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf5aec02ab0270e60a6c41882c24bdd4b3d34cc --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/shared_cache.py @@ -0,0 +1,133 @@ +"""First-recursion KV access in the historical closed-book LoopGPT backbone. + +Only attention access changes. Each layer retains its own first-pass K/V; +embeddings, normalization, residuals, MLPs and supervision are unchanged. +""" + +from __future__ import annotations + +from numbers import Integral + +import torch +from torch.nn import functional as F + +from .grok_loop_model import LoopGPT, _positive_integer +from .grok_loop_model import flops as ordinary_flops +from .latent_scaling import construct as ordinary_construct + +ARMS = ("local", "shared_full", "shared_window", "shared_detached") + + +class SharedCacheGPT(LoopGPT): + def __init__(self, config, repeats, dropout=0.0, arm="shared_full", window=2): + if arm not in ARMS: + raise ValueError(f"Unknown memory arm: {arm}") + if isinstance(window, bool) or not isinstance(window, Integral) or window < 0: + raise ValueError("window counts nonnegative preceding local positions") + super().__init__(config, repeats, dropout, "legacy_unique") + self.memory_arm, self.window = arm, int(window) + self.disable_shared = False + self.duplicate_current = False # engineering identity control only + positions = torch.arange(config.context) + causal = positions[None, :] <= positions[:, None] + local = causal & (positions[None, :] >= positions[:, None] - self.window) + self.register_buffer("shared_causal_mask", causal, persistent=False) + self.register_buffer("local_window_mask", local, persistent=False) + + def forward(self, tokens, positions=None, repeats=None): + count = self.repeats if repeats is None else _positive_integer(repeats, "repeats") + if self.memory_arm == "local" or count == 1: + return super().forward(tokens, positions, count) + length = tokens.shape[1] + if length > self.config.context: + raise ValueError("Input exceeds mask context") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(length, device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + causal = self.shared_causal_mask[:length, :length] + local_mask = ( + self.local_window_mask[:length, :length] + if self.memory_arm == "shared_window" + else causal + ) + joined_mask = torch.cat((causal, local_mask), dim=-1) + shared = [] + for recursion in range(count): + for layer, block in enumerate(self.blocks): + z = block.ln1(x) + batch, size, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, size, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + q, k, v = (t.transpose(1, 2) for t in (q, k, v)) + if recursion == 0: + shared.append((k, v)) + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=p) + elif self.disable_shared: + y = F.scaled_dot_product_attention(q, k, v, attn_mask=local_mask, dropout_p=p) + else: + first_k, first_v = (k, v) if self.duplicate_current else shared[layer] + if self.memory_arm == "shared_detached": + first_k, first_v = first_k.detach(), first_v.detach() + y = F.scaled_dot_product_attention( + q, + torch.cat((first_k, k), dim=-2), + torch.cat((first_v, v), dim=-2), + attn_mask=joined_mask, + dropout_p=p, + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, size, 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 construct(spec, device): + if "memory_arm" not in spec: + return ordinary_construct(spec, device) + reference = ordinary_construct(spec, "cpu") + torch.manual_seed(spec["initialization"]) + return SharedCacheGPT( + reference.config, spec["repeats"], spec["dropout"], spec["memory_arm"], spec["window"] + ).to(device) + + +def executed_flops(config, repeats, batch, sequence, arm, output_positions=9, backward=True): + """Executed dense matmul shapes, including masked work; excludes elementwise ops. + + Concatenated attention has twice the key dimension, even for a small window. + The ordinary estimate counts QK and AV over a square sequence, not only the + visible causal entries. Backward follows the historical 3-forward convention. + Detachment changes true backward work; this common estimate is approximate. + """ + base = ordinary_flops(config, repeats, batch, sequence, output_positions, backward) + if arm == "local": + return base + extra = 4 * batch * config.layers * (repeats - 1) * sequence**2 * config.width + return base + extra * (3 if backward else 1) + + +def cached_positions(layers, repeats, length, arm, window): + """Analytic decoding history slots, not measured training allocation.""" + if arm in {"local", "shared_full", "shared_detached"}: + return layers * repeats * length + return layers * (length + (repeats - 1) * min(window, length)) + + +def install_training_adapter(spec): + """Reuse the unchanged historical sampler, optimizer, scorer and audit.""" + from . import latent_scaling as latent + + latent.construct = construct + latent.flops = lambda config, repeats, batch, sequence, output_positions=9, backward=True: ( + executed_flops( + config, repeats, batch, sequence, spec["memory_arm"], output_positions, backward + ) + ) + return latent diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/small_lm_composition.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/small_lm_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..f7bc9b1ea8e7d825eb5f27c33bb4d7e38bb7bcc1 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/small_lm_composition.py @@ -0,0 +1,543 @@ +"""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 hashlib +import json +import math +import re +import shutil +import time +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +import transformers +from 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) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/small_lm_followup.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/small_lm_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..4c986ea475b4f0abe83ea3d0411a049344ac0e08 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/small_lm_followup.py @@ -0,0 +1,558 @@ +"""Small full-Qwen development: matched rehearsal, pairing, and factual updates.""" + +from __future__ import annotations + +import copy +import itertools +import json +import math +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import transformers +from 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) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/storage_composition.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/storage_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..094211c26edecbed2a534bad16c84c42b2cdebd0 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/storage_composition.py @@ -0,0 +1,424 @@ +"""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, and +all non-padding next tokens contribute to the training loss. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .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 result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/storage_frontier.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/storage_frontier.py new file mode 100644 index 0000000000000000000000000000000000000000..db36e560aed8b173bb72c836b3d02dc8381bbcc5 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/storage_frontier.py @@ -0,0 +1,262 @@ +"""Stable training and nested fact loads in ordinary GPT/Loop architectures. + +The historical storage_composition implementation is reused without changing its +frozen sources, truth, tokenizer, architecture or full-generation score. +""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .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 result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/text_loss_source.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/text_loss_source.py new file mode 100644 index 0000000000000000000000000000000000000000..6f9377848d4673a2937273cf26a33f8e859874d0 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/text_loss_source.py @@ -0,0 +1,256 @@ +"""Factorial loss-source interventions on an unchanged text-pretraining stream.""" + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, write_json +from .grok_loop_model import flops +from .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"), + ), + ) diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/text_pretrain.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/text_pretrain.py new file mode 100644 index 0000000000000000000000000000000000000000..2682a0925a00e0e8b0eef3781521830d891ef9d7 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/text_pretrain.py @@ -0,0 +1,401 @@ +"""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 in +supervision. This is controlled template-language pretraining, not a pretrained +natural-language model or a replication of the original bioS scale. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, GraphStep, make_optimizer, write_json +from .grok_loop_model import LoopGPT, flops + +WORDS = [ + "", + "", + "", + "'s", + "is", + ".", + "This", + "record", + "has", + "no", + "additional", + "fact", + "here", + "mentor", + "advisor", + "coach", + "supervisor", + "city", + "district", + "region", + "campus", +] +LENGTH = 26 +PAD, EOS, BOS = 0, 1, 2 + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def vocabulary(spec): + return ( + WORDS + + [f"Person{i:03d}" for i in range(spec["heads_n"])] + + [f"Expert{i:03d}" for i in range(spec["bridges_n"])] + + [f"Place{i:03d}" for i in range(spec["tails_n"])] + ) + + +def atomic_sentence(row): + h, r, t = map(int, row) + return [BOS, h, 3, r, 4, t, 5, EOS] + + +def composite_sentence(row): + h, r1, _b, r2, t = map(int, row) + return [BOS, h, 3, r1, 3, r2, 4, t, 5, EOS] + + +def pack_documents(documents, groups): + """Reset positions per record in every arm; BOS is an exogenous boundary. + + All remaining next-token targets, including names, relations and EOS, are + supervised. The next record's BOS and padding are never prediction targets. + """ + seq, positions, segments = [], [], [] + for doc, group in zip(documents, groups, strict=True): + seq.extend(doc) + positions.extend(range(len(doc))) + segments.extend([group] * len(doc)) + if len(seq) > LENGTH: + raise ValueError("Record exceeds fixed context") + n = len(seq) + seq += [PAD] * (LENGTH - n) + positions += [0] * (LENGTH - n) + segments += list(range(100, 100 + LENGTH - n)) + labels = np.asarray(seq[1:], dtype=np.int64) + labels[(labels == BOS) | (labels == PAD)] = -100 + seg = np.asarray(segments[:-1]) + mask = (seg[:, None] == seg[None, :]) & np.tri(LENGTH - 1, dtype=bool) + return ( + np.asarray(seq[:-1], dtype=np.int64), + np.asarray(positions[:-1], dtype=np.int64), + mask[None], + labels, + ) + + +def build_world(spec): + """One supplied world; complete head-tail pairs held out before rendering.""" + rng = np.random.default_rng(spec["world"]) + hn, bn, tn = spec["heads_n"], spec["bridges_n"], spec["tails_n"] + hs = np.arange(len(WORDS), len(WORDS) + hn) + bs = np.arange(hs[-1] + 1, hs[-1] + 1 + bn) + ts = np.arange(bs[-1] + 1, bs[-1] + 1 + tn) + first = np.array([(h, r, rng.choice(bs)) for h in hs for r in range(13, 17)]) + second = np.array([(b, r, rng.choice(ts)) for b in bs for r in range(17, 21)]) + lookup = {(int(h), int(r)): int(t) for h, r, t in second} + paths = np.array( + [(h, r1, b, r2, lookup[int(b), r2]) for h, r1, b in first for r2 in range(17, 21)], + dtype=np.int64, + ) + reserved = rng.random((hn, tn)) < spec["holdout_fraction"] + held = reserved[paths[:, 0] - hs[0], paths[:, 4] - ts[0]] + background = paths[:, 0] < hs[0] + hn // 2 + groups = { + "atomic_first": first, + "atomic_second": second, + "background_train": paths[background & ~held], + "background_test": paths[background & held], + "target_train": paths[~background & ~held], + "target_test": paths[~background & held], + } + for key, rows in groups.items(): + if not len(rows): + raise ValueError(f"Empty world stratum {key}; do not silently reroll") + train_pairs = {tuple(r[[0, 4]]) for r in paths[~held]} + test_pairs = {tuple(r[[0, 4]]) for r in paths[held]} + assert not train_pairs & test_pairs + # Typed atomics can never expose a head and a tail together. + assert not set(first[:, 0]) & set(second[:, 0]) + assert not set(first[:, 2]) & set(second[:, 2]) + groups["atomic"] = np.concatenate([first, second]) + groups["all_paths"] = paths + return groups + + +def training_table(world, arm): + if arm not in ("P0", "P1", "P2"): + raise ValueError(arm) + packed = [pack_documents([atomic_sentence(r)], [0]) for r in world["atomic"]] + base_end = len(packed) + packed.extend(pack_documents([composite_sentence(r)], [0]) for r in world["background_train"]) + background_end = len(packed) + neutral = [BOS, 6, 7, 8, 9, 10, 11, 12, 5, EOS] + for row in world["target_train"]: + h, r1, b, r2, t = row + third = composite_sentence(row) if arm == "P2" else neutral + packed.append( + pack_documents( + [atomic_sentence([h, r1, b]), atomic_sentence([b, r2, t]), third], + [0, 1, 2] if arm == "P0" else [0, 0, 2], + ) + ) + table = tuple(np.stack([row[i] for row in packed]) for i in range(4)) + return table, [0, base_end, background_end, len(packed)] + + +class TextGPT(LoopGPT): + def forward(self, tokens, position_ids=None, attention_mask=None, patch=None, cache=None): + if position_ids is None: + position_ids = torch.arange(tokens.shape[1], device=tokens.device)[None] + p = self.dropout if self.training else 0.0 + x = F.dropout(self.token(tokens) + self.position(position_ids), p=p, training=self.training) + for layer, block in enumerate(self.iter_blocks()): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=attention_mask, + is_causal=attention_mask is None, + dropout_p=p, + ) + attn = F.dropout( + a.proj(y.transpose(1, 2).reshape(batch, length, width)), p=p, training=self.training + ) + mlp = F.dropout(block.mlp(block.ln2(x + attn)), p=p, training=self.training) + if cache is not None: + cache[layer] = { + "attention": attn.detach(), + "mlp": mlp.detach(), + "full": (x + attn + mlp).detach(), + } + if patch is not None and layer == patch["layer"]: + pos, value, component = patch["position"], patch["value"], patch["component"] + if component == "full": + x = x + attn + mlp + x = x.clone() + x[:, pos] = value + continue + if component == "attention": + attn = attn.clone() + attn[:, pos] = value + elif component == "mlp": + mlp = mlp.clone() + mlp[:, pos] = value + else: + raise ValueError(component) + x = x + attn + mlp + return F.linear(self.ln_final(x), self.token.weight) + + +class TextGraphStep(GraphStep): + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, positions, mask, labels = (t[self.index] for t in self.table) + logits = self.model(x, position_ids=positions, attention_mask=mask) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def construct(spec, device): + torch.manual_seed(spec["initialization"]) + cfg = ModelConfig( + vocab_size=len(vocabulary(spec)), + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=LENGTH, + ) + return TextGPT(cfg, repeats=spec["repeats"], dropout=spec["dropout"]).to(device) + + +@torch.inference_mode() +def evaluate(model, rows, device, composite=False, patch=None, batch_size=256): + model.eval() + encode = composite_sentence if composite else atomic_sentence + prompts = np.asarray([encode(r)[:-3] for r in rows], dtype=np.int64) + answers, stops, probs = [], [], [] + for start in range(0, len(rows), batch_size): + x = torch.as_tensor(prompts[start : start + batch_size], device=device) + intervention = ( + None if patch is None else dict(patch, value=patch["value"][start : start + batch_size]) + ) + logits = model(x, patch=intervention)[:, -1] + target = torch.as_tensor(rows[start : start + batch_size, -1], device=device) + probs.extend(logits.softmax(-1).gather(1, target[:, None]).squeeze(1).tolist()) + prediction = logits.argmax(-1) + answers.extend(prediction.tolist()) + x = torch.cat([x, prediction[:, None]], dim=1) + period = model(x, patch=intervention)[:, -1].argmax(-1) + x = torch.cat([x, period[:, None]], dim=1) + eos = model(x, patch=intervention)[:, -1].argmax(-1) + stops.extend(torch.stack([period, eos], dim=1).tolist()) + ans, stop, probability = np.asarray(answers), np.asarray(stops), np.asarray(probs) + correct = ans == rows[:, -1] + full = correct & (stop[:, 0] == 5) & (stop[:, 1] == EOS) + return dict( + n=len(rows), + answer_accuracy=float(correct.mean()), + accuracy=float(full.mean()), + answer_probability=float(probability.mean()), + ), dict(answer=ans, stops=stop, probability=probability, target=rows[:, -1]) + + +def run(spec, output, device): + output = Path(output) + if (output / "complete.json").exists(): + return json.loads((output / "complete.json").read_text()) + output.mkdir(parents=True, exist_ok=True) + lock = json.loads(Path(spec["source_lock"]).read_text()) + for file, expected in lock["sources"].items(): + assert sha(file) == expected, file + assert lock["config_sha256"] == sha(spec["config_path"]) + torch.set_num_threads(2) + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_per_process_memory_fraction(0.08, device) + world = build_world(spec) + cpu_table, bounds = training_table(world, spec["arm"]) + np.savez_compressed(output / "world.npz", **world) + np.savez_compressed( + output / "training-table.npz", + **{k: v for k, v in zip(("tokens", "positions", "mask", "labels"), cpu_table, strict=True)}, + ) + write_json(output / "spec.json", spec) + write_json(output / "vocabulary.json", vocabulary(spec)) + model = construct(spec, device) + opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"]) + table = tuple(torch.as_tensor(t, device=device) for t in cpu_table) + streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(3)] + latest = output / "latest.pt" + start, elapsed, histories = 0, 0.0, [] + if latest.exists(): + state = torch.load(latest, map_location=device, weights_only=False) + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + for stream, saved in zip(streams, state["streams"], strict=True): + stream.load_state_dict(saved) + start, elapsed, histories = state["step"], state["seconds"], state["histories"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + counts = spec["batch_parts"] + supervised_per_step = sum(n * tokens for n, tokens in zip(counts, [7, 9, 23], strict=True)) + step_flops = flops( + model.config, spec["repeats"], sum(counts), LENGTH - 1, output_positions=LENGTH - 1 + ) + + def checkpoint(step, seconds): + metrics, predictions = {}, {} + for split in ( + "atomic", + "background_train", + "background_test", + "target_train", + "target_test", + ): + metrics[split], preds = evaluate( + model, world[split], device, composite=split != "atomic" + ) + predictions.update({split + "_" + k: v for k, v in preds.items()}) + atomic_ok = predictions["atomic_answer"] == world["atomic"][:, -1] + knowledge = { + (int(h), int(r)): bool(ok) + for (h, r, _t), ok in zip(world["atomic"], atomic_ok, strict=True) + } + eligible = np.array( + [ + knowledge[int(h), int(r1)] and knowledge[int(b), int(r2)] + for h, r1, b, r2, _t in world["target_test"] + ] + ) + target_ok = predictions["target_test_answer"] == world["target_test"][:, -1] + metrics["target_atomic_correct"] = dict( + n=int(eligible.sum()), + coverage=float(eligible.mean()), + answer_accuracy=float(target_ok[eligible].mean()) if eligible.any() else None, + ) + record = dict( + step=step, + seconds=seconds, + supervised_tokens=step * supervised_per_step, + estimated_flops=step * step_flops, + metrics=metrics, + ) + histories.append(record) + np.savez_compressed(output / f"predictions-{step:06d}.npz", **predictions) + write_json(output / "learning.json", histories) + model.train() + state = dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + step=step, + seconds=seconds, + histories=histories, + spec=spec, + streams=[s.state_dict() for s in streams], + cpu_rng=torch.get_rng_state(), + cuda_rng=torch.cuda.get_rng_state(device), + ) + tmp = output / "latest.tmp" + torch.save(state, tmp) + tmp.replace(latest) + if step in spec["weight_nodes"]: + torch.save( + dict(model=state["model"], step=step, spec=spec), output / f"weights-{step:06d}.pt" + ) + print(json.dumps(dict(run=output.name, **record)), flush=True) + + if start == 0: + checkpoint(0, elapsed) + model.train() + graph = TextGraphStep(model, opt, table, sum(counts)) + tick = time.monotonic() + for step in range(start + 1, spec["steps"] + 1): + idx = np.concatenate( + [ + stream.take(n) + offset + for stream, n, offset in zip(streams, counts, bounds[:-1], strict=True) + ] + ) + for group in opt.param_groups: + group["lr"].fill_(spec["lr"] * min(1.0, step / spec["warmup"])) + graph(torch.as_tensor(idx, device=device)) + if step in spec["nodes"]: + torch.cuda.synchronize() + elapsed += time.monotonic() - tick + checkpoint(step, elapsed) + tick = time.monotonic() + result = dict( + status="complete", + final=histories[-1], + parameters=sum(p.numel() for p in model.parameters()), + source_lock_sha256=sha(spec["source_lock"]), + world_sha256=sha(output / "world.npz"), + peak_memory_bytes=torch.cuda.max_memory_allocated(device), + ) + write_json(output / "complete.json", result) + return result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/text_structure.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/text_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c74f97848144e288267dedd2df039a1f8c1a52 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/text_structure.py @@ -0,0 +1,432 @@ +"""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 and +bridges are disjoint from background; answer values are deliberately shared. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .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 result diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/twohop_depth.py b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/twohop_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..19b9a4b76eadef68acf7603b8434567145244311 --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/src/llm_memory_editability/twohop_depth.py @@ -0,0 +1,362 @@ +"""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 contextlib +import hashlib +import json +import os +from pathlib import Path + +import numpy as np +import torch +from 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}" diff --git a/docs/development-artifacts/shared-cache-branch-v1/source/tests/test_shared_cache.py b/docs/development-artifacts/shared-cache-branch-v1/source/tests/test_shared_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..247951505d14e6d14e71706eb51a9990663b3c8a --- /dev/null +++ b/docs/development-artifacts/shared-cache-branch-v1/source/tests/test_shared_cache.py @@ -0,0 +1,82 @@ +"""Scientific contracts for cross-recursion KV sharing.""" + +import copy + +import pytest +import torch + +from llm_memory_editability.bios_model import ModelConfig +from llm_memory_editability.grok_loop_model import LoopGPT +from llm_memory_editability.latent_scaling import model_digest +from llm_memory_editability.shared_cache import ARMS, SharedCacheGPT, executed_flops + + +def model(arm="shared_full", repeats=3): + torch.manual_seed(51) + return SharedCacheGPT( + ModelConfig(vocab_size=39, width=16, layers=2, heads=2, context=16), repeats, arm=arm + ) + + +@pytest.mark.parametrize("arm", ARMS) +def test_parameter_initialization_and_R1_equal_historical_model(arm): + actual = model(arm) + torch.manual_seed(51) + reference = LoopGPT(actual.config, 3, 0.0, "legacy_unique") + assert model_digest(actual) == model_digest(reference) + x = torch.tensor([[2, 3, 4, 5, 6]]) + torch.testing.assert_close(actual(x, repeats=1), reference(x, repeats=1), rtol=0, atol=0) + if arm == "local": + torch.testing.assert_close(actual(x), reference(x), rtol=0, atol=0) + + +@pytest.mark.parametrize("arm", ARMS) +def test_future_tokens_do_not_leak_through_either_cache(arm): + m = model(arm).eval() + a = torch.tensor([[2, 3, 4, 5, 6, 7]]) + b = torch.tensor([[2, 3, 4, 18, 19, 20]]) + torch.testing.assert_close(m(a)[:, :3], m(b)[:, :3], rtol=0, atol=0) + torch.testing.assert_close(m(a)[:, :3], m(a[:, :3]), rtol=1e-5, atol=1e-6) + + +def test_detach_preserves_forward_and_changes_parameter_gradient(): + normal = model() + detached = copy.deepcopy(normal) + detached.memory_arm = "shared_detached" + x = torch.tensor([[2, 3, 4, 5]]) + torch.testing.assert_close(normal(x), detached(x), rtol=0, atol=0) + normal(x)[:, -1].square().sum().backward() + detached(x)[:, -1].square().sum().backward() + a, b = normal.blocks[0].attention.qkv.weight.grad, detached.blocks[0].attention.qkv.weight.grad + assert torch.linalg.vector_norm(a - b) > 1e-5 + assert all(p.grad is not None for p in detached.parameters()) + + +def test_window_counts_preceding_tokens_and_current_entry(): + m = model("shared_window") + assert torch.equal(m.local_window_mask[5].nonzero().flatten(), torch.tensor([3, 4, 5])) + assert torch.equal(m.shared_causal_mask[5].nonzero().flatten(), torch.arange(6)) + + +def test_disable_and_duplicate_controls_and_cache_is_per_call(): + m = model().eval() + reference = model("local").eval() + x = torch.tensor([[2, 3, 4, 5]]) + m.disable_shared = True + torch.testing.assert_close(m(x), reference(x), rtol=1e-5, atol=1e-6) + m.disable_shared = False + m.duplicate_current = True + torch.testing.assert_close(m(x), reference(x), rtol=1e-5, atol=1e-6) + m.duplicate_current = False + expected = m(x).detach() + m(torch.tensor([[9, 10, 11, 12]])) + torch.testing.assert_close(m(x), expected, rtol=0, atol=0) + + +def test_shared_attention_increases_executed_shape_budget_even_with_short_window(): + c = model().config + ordinary = executed_flops(c, 3, 192, 9, "local") + shared = executed_flops(c, 3, 192, 9, "shared_full") + assert shared - ordinary == 3 * 4 * 192 * 2 * 2 * 9**2 * 16 + assert shared == executed_flops(c, 3, 192, 9, "shared_window") + assert shared == executed_flops(c, 3, 192, 9, "shared_detached") diff --git a/docs/development-artifacts/write-target-confirmation-v1/execution-lock.json b/docs/development-artifacts/write-target-confirmation-v1/execution-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..e3038fd50f23ed3589471c01c32ab226b21a904c --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/execution-lock.json @@ -0,0 +1,3 @@ +{ + "config_sha256": "acf1c17238e06b49876171cc5c83bffd7d5e59b7109f7f74b8514c006db5d3c7" +} diff --git a/docs/development-artifacts/write-target-confirmation-v1/frozen-config.json b/docs/development-artifacts/write-target-confirmation-v1/frozen-config.json new file mode 100644 index 0000000000000000000000000000000000000000..2b7e48573a6fe3a4a7d1d15d656606ef809e3e07 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/frozen-config.json @@ -0,0 +1,714 @@ +{ + "batch": "write-target-confirmation-v1", + "module": "write_target_editing", + "gpus": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6 + ], + "runtime": { + "docker_context": "lm-memory", + "docker_host": "unix:///run/docker-lm-memory/docker.sock", + "image": "sha256:a994f1a1886220693eb26b7ff201147fbd4b49477d335ab2707330cab771063f", + "python": "/opt/conda/bin/python", + "cpus": 4, + "memory": "24g", + "env": { + "PYTHONDONTWRITEBYTECODE": "1", + "XDG_CACHE_HOME": "/tmp/cache", + "TORCH_HOME": "/tmp/torch", + "TORCHINDUCTOR_CACHE_DIR": "/tmp/torchinductor", + "TRITON_CACHE_DIR": "/tmp/triton" + } + }, + "specs": [ + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775101-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned", + "parent_checkpoint_sha256": "9ba1147aa9e3593d1d02bcdb85e414d997537b95741d1961dcc26fddaac8642f", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775101-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned", + "parent_checkpoint_sha256": "9ba1147aa9e3593d1d02bcdb85e414d997537b95741d1961dcc26fddaac8642f", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775101-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned", + "parent_checkpoint_sha256": "9ba1147aa9e3593d1d02bcdb85e414d997537b95741d1961dcc26fddaac8642f", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775102-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned", + "parent_checkpoint_sha256": "4dc0b7662668de0c0f5d01a696bef70ce46916fe9a04e229a31a26a59710aad3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775102-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned", + "parent_checkpoint_sha256": "4dc0b7662668de0c0f5d01a696bef70ce46916fe9a04e229a31a26a59710aad3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775102-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned", + "parent_checkpoint_sha256": "4dc0b7662668de0c0f5d01a696bef70ce46916fe9a04e229a31a26a59710aad3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775101-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned", + "parent_checkpoint_sha256": "9fc43fcc48b8d82d8b3d0780ad92905888185ac037372d186668a249abf19808", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775101-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned", + "parent_checkpoint_sha256": "9fc43fcc48b8d82d8b3d0780ad92905888185ac037372d186668a249abf19808", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775101-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned", + "parent_checkpoint_sha256": "9fc43fcc48b8d82d8b3d0780ad92905888185ac037372d186668a249abf19808", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775102-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned", + "parent_checkpoint_sha256": "f2432dd48e266c85a91b19a6c1049555bc9067142d63155ba84d666bb8a469b7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775102-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned", + "parent_checkpoint_sha256": "f2432dd48e266c85a91b19a6c1049555bc9067142d63155ba84d666bb8a469b7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775102-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned", + "parent_checkpoint_sha256": "f2432dd48e266c85a91b19a6c1049555bc9067142d63155ba84d666bb8a469b7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775101-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned", + "parent_checkpoint_sha256": "56845c38b7bd88a6358cb31c3f375ccd63bd7bcac38d0edd0ddb46bf388c28d7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775101-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned", + "parent_checkpoint_sha256": "56845c38b7bd88a6358cb31c3f375ccd63bd7bcac38d0edd0ddb46bf388c28d7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775101-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned", + "parent_checkpoint_sha256": "56845c38b7bd88a6358cb31c3f375ccd63bd7bcac38d0edd0ddb46bf388c28d7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775102-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned", + "parent_checkpoint_sha256": "b3679fba3d439b50ed1ea89f94e1bea5366f6fa9540cb9af40da4beddf5161a3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775102-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned", + "parent_checkpoint_sha256": "b3679fba3d439b50ed1ea89f94e1bea5366f6fa9540cb9af40da4beddf5161a3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775102-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned", + "parent_checkpoint_sha256": "b3679fba3d439b50ed1ea89f94e1bea5366f6fa9540cb9af40da4beddf5161a3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + } + ], + "additional_sources": [ + "tests/test_write_target_editing.py", + "scripts/run_write_target_editing.py", + "docs/development-artifacts/learning-use-20261007/protocol.md", + "configs/write-target-editing-v1.json", + "results/write-target-development-v1/development-decision.json" + ], + "development_operational_gate": "results/write-target-development-v1/development-decision.json", + "allocated_optimizer_updates": 73728, + "frozen_utc": "2026-10-07T04:47:48.121832+00:00", + "repository": "/ossfs/workspace/llm-memory-editability", + "source_root": "/ossfs/workspace/llm-memory-editability/docs/development-artifacts/write-target-confirmation-v1/source", + "results_root": "/ossfs/workspace/llm-memory-editability/results/write-target-confirmation-v1", + "source": { + "configs/experiment-tracking-defaults.json": "41d4b73b9d2f57f71fe51dd8500275f2c9fb3476ec24a9eeee3a8deadb5ecaa2", + "configs/write-target-confirmation-v1.json": "cbd614eca12a5de11b8cb874991fbbf35c7562ad5356e20ab1c2d0bcf6edc17c", + "configs/write-target-editing-v1.json": "8b80ee56e0be7f647310638e0c25dd8d6c9335be6903298ad6a14fc0c80520cf", + "docs/development-artifacts/learning-use-20261007/protocol.md": "e11e865b4bc74d8216221d694244c300a6a7a7c99794ec0060174b44d5942263", + "results/write-target-development-v1/development-decision.json": "a7d0815cf8fffeb5bc65b1cdfeb0abb8bf58b754bafaafa58ba6b4fbad1f3337", + "scripts/execute_learning_use.py": "c9cfef8ea43adc5860b6a43bdd6809744c4516f4aebbe8adc9820c5f17ab43da", + "scripts/run_memory_interface_next.py": "f80f1cfdd3fa0a2685489c4101c234387745e66e46427208b523886eefe96bb3", + "scripts/run_write_target_editing.py": "22b7b12134b022a800c2b6e14a4a8dbae8c48b8655df3ed635c57da157f0c13b", + "src/llm_memory_editability/__init__.py": "84e6bb4a97b68f67f3256135c2b5fc35d9a83ceb04914a6cf3d38d926b015f7f", + "src/llm_memory_editability/__main__.py": "0af76e0612dd46d8097cd06d02bcd6220d89354be49910110a80b9942fdb71b3", + "src/llm_memory_editability/alignment_coverage.py": "152b868b836ff3ae18d8bb572ffe6ce956ea26edde1d283726b82215125736ff", + "src/llm_memory_editability/architecture_bridge.py": "777fe51d98b09275f487386660106e93c6c8b49e25b94e804510ed968c2df04c", + "src/llm_memory_editability/architecture_bridge_toy.py": "320d859c4d11b68299266d3f9bdb9a7e6867d635eb3d347827be082c60f0ffca", + "src/llm_memory_editability/bios_analysis.py": "41d836fc201b9ae4f1988e0cdda3dc3be4ebc3ca898ab2ff69ca8445212407ff", + "src/llm_memory_editability/bios_branch.py": "f5b0f0ae79f84d64e33862e40fffbc4bd9a8fd102414995e8a2d41560009c09d", + "src/llm_memory_editability/bios_capacity.py": "a9c306f0e326a8b97eccc4c0b404d45a3e3d8697186092ac562f645b4b370ba4", + "src/llm_memory_editability/bios_causal_paths.py": "10ea265743293fff64cc2201b7b49f5a22dd3bc3ff6a320f469948c233e65620", + "src/llm_memory_editability/bios_confirmation_stats.py": "e40f0347bd44e8602c18fc2fbee9647010d509d6f6dc7bc3c5cb8e98036e9c9b", + "src/llm_memory_editability/bios_context_control.py": "9205a7f8d25e0f1311d78c73638b97466f425886e62165166ba104f53050a40d", + "src/llm_memory_editability/bios_context_gradient.py": "8376dec9883b1d2c3ef06e5e04ad01fec6a1b9eceaa5cd74db02a79629bc536f", + "src/llm_memory_editability/bios_cross.py": "47b8f55adbe13d9bc6e1c5c9170cc95e382261ffb1f31980706ac95be03623bf", + "src/llm_memory_editability/bios_cross_continue.py": "e6fd3a86157566559ab0e0571fbefcc1a28f22ec7add66da2105ea81d63cdaf8", + "src/llm_memory_editability/bios_cross_scale.py": "a1be3c598403b72661b9b2df642b2b1236ae1df6fdf46d982d4d89d19487f658", + "src/llm_memory_editability/bios_cross_train.py": "0106cae29be447319be2e7f6f0e1f5b60cc6224282331906f43ebc65ab795f38", + "src/llm_memory_editability/bios_data.py": "d5568901f2042a6d89d447f47eddae9764eced0a9e71e3ea5adc0038a7e636d6", + "src/llm_memory_editability/bios_direction.py": "1240f83f5ee558101bbf6f808522fa6c37ffe09dc2296749bd5e685eff8aa41d", + "src/llm_memory_editability/bios_direction_cross.py": "66cf337b3a52508e82da6190ea01916662f1fe6fddef036844f9d1be2c179888", + "src/llm_memory_editability/bios_direction_formation.py": "e2b19c17c6b7ebb7a884782f2c7750a7c65b935c17694d4424d354c62d0a24ed", + "src/llm_memory_editability/bios_direction_refresh.py": "4f80060d4232ec3bf4fb5d99b0823d20ee759e088aeedf4bd49ab841357d0127", + "src/llm_memory_editability/bios_edit.py": "dbbbc01ce57acef79d5cc46bcd39e301b256fa1e8c9eff7b1ce5ece693f86f2f", + "src/llm_memory_editability/bios_followup.py": "06b4ffd3bbb65e2ff4df0f68e3fbf9f368257196bd4ef36eb1ffb0f7b15ee43b", + "src/llm_memory_editability/bios_measure.py": "8c275b658c5c99316a19e2328eb53952f26b8a858b591784509391780ead3267", + "src/llm_memory_editability/bios_mechanism_causal.py": "41aeed0ba09eba1b869e74dc29236aaa2abf142a596916dc06316754c7f21d8a", + "src/llm_memory_editability/bios_mechanism_causal_v2.py": "bc37408e458014e746c061c65b4672e67e30adee2b5a85b325a0282fbec00dfe", + "src/llm_memory_editability/bios_mechanism_edit.py": "ca9351ef08189c643a5b0a009af3e52b2578d5ae6265510f603cb78b229667dd", + "src/llm_memory_editability/bios_mechanism_interventions.py": "190c75e0a2779fe96936bff38d13a03e17e0dfd9faba3d2909ffc4a65265d96f", + "src/llm_memory_editability/bios_model.py": "99efb7feeeb15f33dd3f08174c1190f4aa470e3877d8ac6692b2d43fed4c5f4d", + "src/llm_memory_editability/bios_organization.py": "42f714473695da4c8543f666fd15a7eab7cef1e571429b25f81818b5505bd9d5", + "src/llm_memory_editability/bios_organization_train.py": "833426232b693495711e38101553e8bff370c837c722d76e7f9f5f2d2ed3cad6", + "src/llm_memory_editability/bios_original_data.py": "092689c2a05aad564ff8a7c6e1ac669d7e0475908e525766cf70922037cd2488", + "src/llm_memory_editability/bios_original_diagnostics.py": "6dd51ead7d16c1960740716fb73cb4409828666ac0332baae4c14730e39dd120", + "src/llm_memory_editability/bios_original_model.py": "8a52e58d343320ccce9e2f1b43674cc6765b840bd4feebed4813f78296ab29a9", + "src/llm_memory_editability/bios_original_report.py": "3483f72d479a861a4513f0a1a5dc7cbf53bcbace6a652d39f389b46ffb82286e", + "src/llm_memory_editability/bios_original_train.py": "86b2ef1be03223dff26bc7997b91143be81fb46fd29ab8650a9cde8a39eb6891", + "src/llm_memory_editability/bios_path_diagnostics.py": "7d95f31f9fa9099d6b05666b9a638f880aa83a88554d934c3ff05e86880d0f7e", + "src/llm_memory_editability/bios_path_minimal.py": "6fe8f0f6dd0950adfbbc5ad0524c1fe7e96b5c054d04338c046728535257a12e", + "src/llm_memory_editability/bios_path_transfer.py": "2a079c54c2778e9bcb8fb36ebea4f90c43ac7bb7135e6d61e8a91a250ae3a0e1", + "src/llm_memory_editability/bios_readout_control.py": "545260dcaeac15766857271cbe8646ed3f096e445215064790b4ad62b6425afe", + "src/llm_memory_editability/bios_relation_response.py": "56a21f6b7cd028aff011f99c9222518d0ef04bb803eda79a176e355cd735e0ca", + "src/llm_memory_editability/bios_shortcut_confirmation.py": "92306cd8d88e0329916b52d9aadb992db286fae4ad7cf72cd846ab2b9a22553e", + "src/llm_memory_editability/bios_shortcut_confirmation_sets.py": "063d867951c621f8110c5c2547458aa5039899d64e44c199b86a45b4661e142e", + "src/llm_memory_editability/bios_shortcut_control.py": "a9369b1a042ef644b231763e2b62ac2b12451c3a526ccf121fd476a72fa27325", + "src/llm_memory_editability/bios_shortcut_edit.py": "68c4980269249cbb1acf787fe5679bfad762460487f4a0cfc8e5e7f728ed8a68", + "src/llm_memory_editability/bios_shortcut_edit_v2.py": "55ee452c248a44e0abb50f9806a00772dc6e72b683541db6cc17ffd1ac18e899", + "src/llm_memory_editability/bios_shortcut_matched_edit.py": "a8bba1a538fe4b3d5739a2ec4d223daf54b3988d74a7aa86854af3971acd4123", + "src/llm_memory_editability/bios_train.py": "c1d84d38aa1853815075041535ae3fa9890f5cf1f9f5d9019136c79521033046", + "src/llm_memory_editability/bridge_reencoding.py": "128c02424642e2a479b8a439bd0342c89f77bf3befe3783a5fef9ebe01375ae5", + "src/llm_memory_editability/bridge_workspace.py": "fe8f98ff6348d879c0b3c6db6b24f18eaabe03692729f0b0c967fe8d3b5a124a", + "src/llm_memory_editability/capacity_controls.py": "dc0b6ea601216b0997c45271a2ce8e02121148f37c88649e68d8960c9a6f1796", + "src/llm_memory_editability/capacity_scaling.py": "5ee176e8d16e6e2a7becca7b89109712f940e21ead6b73a61a2ae974435e8678", + "src/llm_memory_editability/cli.py": "01c814b9644988be1bf2ab660b2010ad5e7beab99067116c2afb2b6957f9fd3b", + "src/llm_memory_editability/composition_curves.py": "520c4503f3d1525612432dd2c0b9fbf56d2e39ee5d6dff9f1484f19a7bfae8ec", + "src/llm_memory_editability/curve_tracking.py": "50cc8a1d652c44ef14d42b4a44cc800fb15e2ed72f4b83c4848870d76ab56fec", + "src/llm_memory_editability/depth_step.py": "bd69879d5ec6124c05ca28a62c2c2459734e5b4b17d32ae92005308de63b8279", + "src/llm_memory_editability/depth_step_edit_calibration.py": "2dd20b15ae1f92eb6f685eca1e914923ff349a6a94277cfd3a5a74ad9155b4b8", + "src/llm_memory_editability/depth_step_mechanism.py": "546ce23095e755959d8114ed2bcf3f3f0d70f4a8e38e5c9b5d98c7a28ea7c5a6", + "src/llm_memory_editability/experiment_tracking.py": "2afe9e767123bee16cf56f59c6c2953a100338ecf1f971945c4968a064551866", + "src/llm_memory_editability/experiments.py": "e575aceb2e3804956655d91710809818aec04c0b16a22edb441f5757629371d1", + "src/llm_memory_editability/grok_depth.py": "7d6d5af38a5dc4438b1e7ff44df8e833169d500f0d60d8933932bdb8822aca26", + "src/llm_memory_editability/grok_depth_bridge.py": "414a0dbf17c369ad6d15714c2c026aafc4fb12bb1813a3c056efe8035fe2773d", + "src/llm_memory_editability/grok_depth_data.py": "c1451a0647ef7c25567398efd63848dbb44fdf066d07718c02f7e556e6c8b94a", + "src/llm_memory_editability/grok_depth_extension.py": "f91923d3a7f154c7432e4763a0a90c0863eb75b7b35c8742838c9949795ab9f6", + "src/llm_memory_editability/grok_loop_data.py": "504de57da94618578cf792a3963f99e2dac587424d74ceae6b4c02c1d9680a8e", + "src/llm_memory_editability/grok_loop_mechanism.py": "aa11f58d3aa378741218eee29106b55da5601e1ff9bc3ac7e39ae55f26e613e2", + "src/llm_memory_editability/grok_loop_model.py": "07e84388997a1710e5c821e54cf6d23726e4289aab178347761e060851fea6cc", + "src/llm_memory_editability/grok_loop_same_bridge.py": "06538ab83312484367f84eefdf4944bddc8f3f45507dfcb96e005cb3017a3349", + "src/llm_memory_editability/grok_loop_same_bridge_eval.py": "dea9ebb3130a0d7816b11cd01ac6d105f09e3aa4a051857b71693da261632410", + "src/llm_memory_editability/grok_loop_supervision.py": "a24661453cb82764f81d631b9a1fb4642df0fc7181c5adf7cd6ac46960c9f9b7", + "src/llm_memory_editability/grok_loop_train.py": "4931606ee614aaadebbc3460c9ad9a86fbb12b5b6a1bbda9f3714f81424ff142", + "src/llm_memory_editability/grok_multihop.py": "67ed1f37b04fbef7031f208e5ca140aea1b6158adb64ec8b0fe12217eb53cdbc", + "src/llm_memory_editability/grok_multihop_data.py": "d417b4d39e70cfa4010a8cd737a362d8159d73c2377330b04bf471a5079da851", + "src/llm_memory_editability/grok_usage_data.py": "cfce0e5835665933ee1a1561ee681ffa6520c564be7e2292d9206399f86e7ced", + "src/llm_memory_editability/grok_usage_train.py": "5509ab6b2ad0c93e185cdfc211a7ee5afef45a5021a74aa8ce8bce520f694f70", + "src/llm_memory_editability/grokking_dynamics_mechanism.py": "713470c8432ea27c602208cf0625452859924b83f8c62927c81894070815432c", + "src/llm_memory_editability/grokking_reproduction.py": "7e3a89d96f6fef7bd4665ac46dd1acb6e7cb461c6878647ecc7c6f425ac31117", + "src/llm_memory_editability/hebbian_data.py": "f2f5458d624fc4a49781a557641de7388937e90fda846ab03f7e17a3f455dd0e", + "src/llm_memory_editability/hebbian_followup.py": "752244bd78c5b02ba1d37a276e0547a5ff5bcf7a47986d64642f0db36cc4f4aa", + "src/llm_memory_editability/hebbian_future.py": "9fa7d88102e5b79e91735f530fe98fdd2bba20fad146238cde4f6eb591cf7105", + "src/llm_memory_editability/hebbian_interface.py": "a1ead4b413aef8f3082dcd569318fd132b64ed1a1ddb0c0c3a3aae4686589198", + "src/llm_memory_editability/hebbian_learning.py": "3dd0317b90943a22aabb80dcdc24eb38199623c5fb84a67641c3acd5de6a650e", + "src/llm_memory_editability/hebbian_model.py": "e0413d8288a679800f3f7bafc8ef072a0d6d5b29fc49de417077569eec49cc3e", + "src/llm_memory_editability/hebbian_statistics.py": "8c3a37806bed9661666c55bcb7c727ab78d9f4b2a1b384323f6a33c51d0a11f8", + "src/llm_memory_editability/hebbian_train.py": "71ca785eafbe3438da45c4f5fa543a62424f1fd5176b04b317b0c78e7c96ecbf", + "src/llm_memory_editability/independent_alignment.py": "e1c7937e1afc8908cd1e16d766bc63316f336a6b296738369eb79c2c08e8976b", + "src/llm_memory_editability/interface_editing.py": "f5a9aba43a4c03373bfb59510322a9be800de53af4c3f87e967c7e03f648e0a0", + "src/llm_memory_editability/interface_tracking.py": "e93609e37b5b8cdd7751b2ed546dc4d24ada6864bf90224d60f2c30161f4d378", + "src/llm_memory_editability/knowledge_change.py": "6d090144a090d2bb53d7034f18af305e6dc50dceb488b6dc724046a47e35ed4b", + "src/llm_memory_editability/latent_scaling.py": "231050e859da58c52b9ea47d09fb5de91271df0d24cbab42dead3f911adc6119", + "src/llm_memory_editability/latent_support.py": "71e2483f8b5eb7e447594bf04def731add89f4cf140954fe87f793a69cb440a3", + "src/llm_memory_editability/low_rank.py": "e1ddb5714d492311a43af2d5fd3dd5f578d8144db0b3d860ca71e3b603d018e1", + "src/llm_memory_editability/memory_reuse.py": "e95814cd98de22adc54e458f0b5933f2c3f13a0640c0c71a841780a9b1b52e57", + "src/llm_memory_editability/multihop_scaling.py": "cbb60954b2738d17a1fce125087f87ee203fe98c5d462d14ad22ccff5790c7c6", + "src/llm_memory_editability/natural_composition_confirmation.py": "e13986431617be78b05db8c1f84f522f5cf4b6af7cd1b2e9d89345423be977e2", + "src/llm_memory_editability/natural_composition_confirmation_v2.py": "9bfa6540da812d4e6e2a21d2a8942dd73908269ce46aff15915b1782382dee75", + "src/llm_memory_editability/neural.py": "f0df4d9bbb47b1febf0baf76d53b58319e598b6bbb29d31abca575e2dd13e025", + "src/llm_memory_editability/neural_data.py": "8812cb49f223dff57ac2fbbeb8055aa3017302e0450c194ecc984eaefcc3596e", + "src/llm_memory_editability/neural_models.py": "c5ecb2fd69aa205a22688c95049750a7b8a0fd58b7c888a026252273b3af9091", + "src/llm_memory_editability/parametric_architecture.py": "b19ebaa377705f582fef367163312f74c2b3d2cc0451d8df03f47eff16e37a19", + "src/llm_memory_editability/parametric_architecture_train.py": "232d2a9e1c3db2023cafd15cf107e57a6f37fc8139d8c81a45e5a3121ef31c5d", + "src/llm_memory_editability/qwen_constraints.py": "1b371c02d59becde87d61f3e8db20c9064588ff1908be66c06570ed2c5b1ab6f", + "src/llm_memory_editability/qwen_path_learning.py": "d62080bf19605df02e9a140332c8981094a6e65b4c84a14b35734248e278a231", + "src/llm_memory_editability/qwen_path_train.py": "09f03b01179a2cef8d98f803f61cea7e48ce636259222e394b0248d6744aec9d", + "src/llm_memory_editability/realworld_composition.py": "323f1cdb0f3c25a085e95b6f85fe352b1a91274aa5b3bbaca4e0686fdb4510c0", + "src/llm_memory_editability/realworld_composition_data.py": "7208e0d0789f0287963b6e36d2646171e334f40ee365af13af79944f81e221be", + "src/llm_memory_editability/realworld_confirmation.py": "e160fa1ab79580281753752b3e8f39584e5f2ba6a3b5d27abece6c99a291efe2", + "src/llm_memory_editability/realworld_confirmation_analysis.py": "c8a89a57f913e034d7fd2c805fc4567900cd1c4881d5b66e8ac0f44deee75802", + "src/llm_memory_editability/recurrence_use.py": "144fb9561ead5dbce0589ee986b6452af31405b1ff4fd30aae36a72076b62469", + "src/llm_memory_editability/representation_alignment.py": "9794218f052a19019a5cb6427b84877a5174de3c0485bad441cdaed0ec7bd6b6", + "src/llm_memory_editability/residual_cache.py": "fc78dec3d8cbaedb0ae9b0ca07d7dc35220f54b4158fb800b5112a47c65f9806", + "src/llm_memory_editability/sequential_data.py": "e0b240eec4beacee42c42be116f8eb2de81a5c6f8987a39e81bfa50b297aba72", + "src/llm_memory_editability/sequential_transfer.py": "6eab684539f4ce84f44058d3988dcec055471ab6ae7cd9cf0ffc3fc0150e424d", + "src/llm_memory_editability/shared_cache.py": "c207467bf357887be09e8cf5235ffbcbbd93762eb201027fc666c032e6d187cd", + "src/llm_memory_editability/small_lm_composition.py": "93796eee05e305ad538a498f013463d6bcde4a03de720eff6f4bfedf903f21d1", + "src/llm_memory_editability/small_lm_followup.py": "90fdbbc5c1509d30e0e369c201b5caccac0c063636ad99101f9e3ea603ce7780", + "src/llm_memory_editability/storage_composition.py": "fa4d8b073ecb3ac69a3204ee446a4bc1ecf0c36f9d8dd1dcd0b6835c245e4c5a", + "src/llm_memory_editability/storage_frontier.py": "2a1adcbbb0439ed771e17090878b9f7c9861d2fef4544172a88c35bd037d4a22", + "src/llm_memory_editability/text_loss_source.py": "579471a04def8a11e9cc072fcb909d6e84c3b61c8d901d0d029e126f14a6d3fe", + "src/llm_memory_editability/text_pretrain.py": "cd777a56ba270d3c71ed3260f68501ee0685d4cc58a4f7b952719236adf874cb", + "src/llm_memory_editability/text_structure.py": "9c8e3f00b263a62d53868a6224830e702dcb4348c05d52cc438c1e37e365287d", + "src/llm_memory_editability/twohop_depth.py": "870ad9f1f3a3736b77b1b0781d25961803d9d2e1df9aed1c709a669691b76def", + "src/llm_memory_editability/write_target_editing.py": "5d56acecd4385553d19235cebc03cc16720db5e6304b765b30b094f96e46be55", + "tests/test_write_target_editing.py": "901496e3df00a2d26c4b2d151830349e48f020c67efb333c2323bd413831bee4" + }, + "input_files": { + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned/model.pt": "9ba1147aa9e3593d1d02bcdb85e414d997537b95741d1961dcc26fddaac8642f", + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned/run.json": "d733cbb497bf8af0ee13ce901fbeaf9eb8ec1f4a2b25ddb61957c0710ebb3bd9", + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned/model.pt": "4dc0b7662668de0c0f5d01a696bef70ce46916fe9a04e229a31a26a59710aad3", + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned/run.json": "274307b6182fa8aac9c291ac2a48d4d4e401874f57c42d2204e6047f98f46292", + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned/model.pt": "9fc43fcc48b8d82d8b3d0780ad92905888185ac037372d186668a249abf19808", + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned/run.json": "d185700f74b279f3eb844dbea9cceaad81c9fe4bd21aa5a3661beef5347da6ec", + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned/model.pt": "f2432dd48e266c85a91b19a6c1049555bc9067142d63155ba84d666bb8a469b7", + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned/run.json": "834ae4b8804f0b28d8cc66c6803589c48f5661ddd22db233d46f866c30eda877", + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned/model.pt": "56845c38b7bd88a6358cb31c3f375ccd63bd7bcac38d0edd0ddb46bf388c28d7", + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned/run.json": "e180220efa373b7532d6d3c0a4f65d5dbda62783b6d2eac21af5c533e6118eb8", + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned/model.pt": "b3679fba3d439b50ed1ea89f94e1bea5366f6fa9540cb9af40da4beddf5161a3", + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned/run.json": "827f6960829d7747d4bb0fd06b2866830f0ea02b63bc40f6ddeb2ce5dd24dc1f" + }, + "git_commit": "f298768b6843c8e53a0009b3adc0291eda5fea2c" +} diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/configs/experiment-tracking-defaults.json b/docs/development-artifacts/write-target-confirmation-v1/source/configs/experiment-tracking-defaults.json new file mode 100644 index 0000000000000000000000000000000000000000..92273f717dfdee8e79a02a1a3fd47f874f8435f8 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/configs/experiment-tracking-defaults.json @@ -0,0 +1,11 @@ +{ + "enabled": true, + "provider": "wandb", + "sdk_version": "0.30.0", + "entity": "zhusq20", + "project": "llm-memory-editability", + "mode": "online", + "poll_seconds": 15, + "system_metrics": true, + "scope": "Future experiment batches; do not attach to existing frozen runs without a request" +} diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/configs/write-target-confirmation-v1.json b/docs/development-artifacts/write-target-confirmation-v1/source/configs/write-target-confirmation-v1.json new file mode 100644 index 0000000000000000000000000000000000000000..5a848a6966871bbe0b022a977c48528d240c33a1 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/configs/write-target-confirmation-v1.json @@ -0,0 +1,561 @@ +{ + "batch": "write-target-confirmation-v1", + "module": "write_target_editing", + "gpus": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6 + ], + "runtime": { + "docker_context": "lm-memory", + "docker_host": "unix:///run/docker-lm-memory/docker.sock", + "image": "sha256:a994f1a1886220693eb26b7ff201147fbd4b49477d335ab2707330cab771063f", + "python": "/opt/conda/bin/python", + "cpus": 4, + "memory": "24g", + "env": { + "PYTHONDONTWRITEBYTECODE": "1", + "XDG_CACHE_HOME": "/tmp/cache", + "TORCH_HOME": "/tmp/torch", + "TORCHINDUCTOR_CACHE_DIR": "/tmp/torchinductor", + "TRITON_CACHE_DIR": "/tmp/triton" + } + }, + "specs": [ + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775101-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned", + "parent_checkpoint_sha256": "9ba1147aa9e3593d1d02bcdb85e414d997537b95741d1961dcc26fddaac8642f", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775101-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned", + "parent_checkpoint_sha256": "9ba1147aa9e3593d1d02bcdb85e414d997537b95741d1961dcc26fddaac8642f", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775101-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned", + "parent_checkpoint_sha256": "9ba1147aa9e3593d1d02bcdb85e414d997537b95741d1961dcc26fddaac8642f", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775102-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned", + "parent_checkpoint_sha256": "4dc0b7662668de0c0f5d01a696bef70ce46916fe9a04e229a31a26a59710aad3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775102-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned", + "parent_checkpoint_sha256": "4dc0b7662668de0c0f5d01a696bef70ce46916fe9a04e229a31a26a59710aad3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775102-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned", + "parent_checkpoint_sha256": "4dc0b7662668de0c0f5d01a696bef70ce46916fe9a04e229a31a26a59710aad3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775101-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned", + "parent_checkpoint_sha256": "9fc43fcc48b8d82d8b3d0780ad92905888185ac037372d186668a249abf19808", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775101-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned", + "parent_checkpoint_sha256": "9fc43fcc48b8d82d8b3d0780ad92905888185ac037372d186668a249abf19808", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775101-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned", + "parent_checkpoint_sha256": "9fc43fcc48b8d82d8b3d0780ad92905888185ac037372d186668a249abf19808", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775102-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned", + "parent_checkpoint_sha256": "f2432dd48e266c85a91b19a6c1049555bc9067142d63155ba84d666bb8a469b7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775102-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned", + "parent_checkpoint_sha256": "f2432dd48e266c85a91b19a6c1049555bc9067142d63155ba84d666bb8a469b7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775102-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned", + "parent_checkpoint_sha256": "f2432dd48e266c85a91b19a6c1049555bc9067142d63155ba84d666bb8a469b7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775101-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned", + "parent_checkpoint_sha256": "56845c38b7bd88a6358cb31c3f375ccd63bd7bcac38d0edd0ddb46bf388c28d7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775101-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned", + "parent_checkpoint_sha256": "56845c38b7bd88a6358cb31c3f375ccd63bd7bcac38d0edd0ddb46bf388c28d7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775101-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned", + "parent_checkpoint_sha256": "56845c38b7bd88a6358cb31c3f375ccd63bd7bcac38d0edd0ddb46bf388c28d7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775101-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775102-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned", + "parent_checkpoint_sha256": "b3679fba3d439b50ed1ea89f94e1bea5366f6fa9540cb9af40da4beddf5161a3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775102-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned", + "parent_checkpoint_sha256": "b3679fba3d439b50ed1ea89f94e1bea5366f6fa9540cb9af40da4beddf5161a3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775102-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned", + "parent_checkpoint_sha256": "b3679fba3d439b50ed1ea89f94e1bea5366f6fa9540cb9af40da4beddf5161a3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775102-aligned", + "tracking_group": "write-target-confirmation-v1" + } + ], + "additional_sources": [ + "tests/test_write_target_editing.py", + "scripts/run_write_target_editing.py", + "docs/development-artifacts/learning-use-20261007/protocol.md", + "configs/write-target-editing-v1.json", + "results/write-target-development-v1/development-decision.json" + ], + "development_operational_gate": "results/write-target-development-v1/development-decision.json", + "allocated_optimizer_updates": 73728 +} diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/configs/write-target-editing-v1.json b/docs/development-artifacts/write-target-confirmation-v1/source/configs/write-target-editing-v1.json new file mode 100644 index 0000000000000000000000000000000000000000..6d47a4de3a7da49ba7bb49ef506c3dd6564b5ac4 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/configs/write-target-editing-v1.json @@ -0,0 +1,626 @@ +{ + "batch": "write-target-editing-v1", + "module": "write_target_editing", + "development_specs": [ + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "development-final_ce", + "phase": "development", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3", + "parent_checkpoint_sha256": "cb1e034f7174cc081d9802d27df7827f8aa8650927dd603be10fde07e4ed868d", + "candidate_seed": 780011, + "per_cell": 2, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-development-v1/runs/development-aligned_0.3-lr1e-05" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "development-early_ce", + "phase": "development", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3", + "parent_checkpoint_sha256": "cb1e034f7174cc081d9802d27df7827f8aa8650927dd603be10fde07e4ed868d", + "candidate_seed": 780011, + "per_cell": 2, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-development-v1/runs/development-aligned_0.3-lr1e-05" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "development-early_ce_align", + "phase": "development", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3", + "parent_checkpoint_sha256": "cb1e034f7174cc081d9802d27df7827f8aa8650927dd603be10fde07e4ed868d", + "candidate_seed": 780011, + "per_cell": 2, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-development-v1/runs/development-aligned_0.3-lr1e-05" + } + ], + "confirmation_specs": [ + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775101-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned", + "parent_checkpoint_sha256": "9ba1147aa9e3593d1d02bcdb85e414d997537b95741d1961dcc26fddaac8642f", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775101-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned", + "parent_checkpoint_sha256": "9ba1147aa9e3593d1d02bcdb85e414d997537b95741d1961dcc26fddaac8642f", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775101-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned", + "parent_checkpoint_sha256": "9ba1147aa9e3593d1d02bcdb85e414d997537b95741d1961dcc26fddaac8642f", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775102-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned", + "parent_checkpoint_sha256": "4dc0b7662668de0c0f5d01a696bef70ce46916fe9a04e229a31a26a59710aad3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775102-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned", + "parent_checkpoint_sha256": "4dc0b7662668de0c0f5d01a696bef70ce46916fe9a04e229a31a26a59710aad3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775102-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned", + "parent_checkpoint_sha256": "4dc0b7662668de0c0f5d01a696bef70ce46916fe9a04e229a31a26a59710aad3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775101-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned", + "parent_checkpoint_sha256": "9fc43fcc48b8d82d8b3d0780ad92905888185ac037372d186668a249abf19808", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775101-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned", + "parent_checkpoint_sha256": "9fc43fcc48b8d82d8b3d0780ad92905888185ac037372d186668a249abf19808", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775101-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned", + "parent_checkpoint_sha256": "9fc43fcc48b8d82d8b3d0780ad92905888185ac037372d186668a249abf19808", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775102-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned", + "parent_checkpoint_sha256": "f2432dd48e266c85a91b19a6c1049555bc9067142d63155ba84d666bb8a469b7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775102-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned", + "parent_checkpoint_sha256": "f2432dd48e266c85a91b19a6c1049555bc9067142d63155ba84d666bb8a469b7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775102-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned", + "parent_checkpoint_sha256": "f2432dd48e266c85a91b19a6c1049555bc9067142d63155ba84d666bb8a469b7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775101-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned", + "parent_checkpoint_sha256": "56845c38b7bd88a6358cb31c3f375ccd63bd7bcac38d0edd0ddb46bf388c28d7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775101-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned", + "parent_checkpoint_sha256": "56845c38b7bd88a6358cb31c3f375ccd63bd7bcac38d0edd0ddb46bf388c28d7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775101-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned", + "parent_checkpoint_sha256": "56845c38b7bd88a6358cb31c3f375ccd63bd7bcac38d0edd0ddb46bf388c28d7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775102-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned", + "parent_checkpoint_sha256": "b3679fba3d439b50ed1ea89f94e1bea5366f6fa9540cb9af40da4beddf5161a3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775102-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned", + "parent_checkpoint_sha256": "b3679fba3d439b50ed1ea89f94e1bea5366f6fa9540cb9af40da4beddf5161a3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775102-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned", + "parent_checkpoint_sha256": "b3679fba3d439b50ed1ea89f94e1bea5366f6fa9540cb9af40da4beddf5161a3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775102-aligned" + } + ], + "scientific_scope": "Paired extension on three existing worlds and two initializations, not new-world confirmation.", + "calibration": "Fixed recipe admissibility using only target E, U_atomic and necessary_atomic; no downstream D selection.", + "independent_unit": "world; initialization and cases are paired repeated measures", + "development_gate": "all E=1, all U_atomic>=.95, all necessary_atomic>=.95; early readout reported separately", + "runtime": { + "docker_context": "lm-memory", + "docker_host": "unix:///run/docker-lm-memory/docker.sock", + "image": "sha256:bd2a622ec8273f54786cd4029f55b717bcc488afeb688bee4f98c0bd5127bfe5", + "python": "/opt/conda/bin/python", + "cpus": 4, + "memory": "16g", + "env": { + "PYTHONDONTWRITEBYTECODE": "1", + "XDG_CACHE_HOME": "/tmp/cache", + "TORCH_HOME": "/tmp/torch", + "TORCHINDUCTOR_CACHE_DIR": "/tmp/torchinductor", + "TRITON_CACHE_DIR": "/tmp/triton" + } + }, + "budget": { + "development_jobs": 3, + "development_branches": 12, + "development_updates": 6144, + "confirmation_jobs": 18, + "confirmation_branches": 144, + "confirmation_updates": 73728, + "training_updates_total": 79872, + "steps_per_branch": 512, + "notes": "Every case has all three writing objectives and each objective has an old-fact sham; every branch starts from its unchanged parent." + } +} diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/docs/development-artifacts/learning-use-20261007/protocol.md b/docs/development-artifacts/write-target-confirmation-v1/source/docs/development-artifacts/learning-use-20261007/protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..fda8870bad8ed95d079e68e34131851bbe44a4e7 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/docs/development-artifacts/learning-use-20261007/protocol.md @@ -0,0 +1,36 @@ +# 知识学习与继续使用:2026-10-07执行协议 + +用户已授权设计并开展实验,使用当前空闲GPU并行观测。本协议记录本轮实际比较;当前研究路线仍只维护在 `docs/roadmap.md`。历史实验、权重与冻结源码均不修改。 + +## 主问题 + +先学会组合,再只学习从未见过的原子事实,原来的使用能力能否迁移?事实能回答、能组合、更新后能继续使用分别评价,不把第一层仅作为筛选条件。 + +## 顺序新知识实验 + +- 数据:既有2Wiki来源的真实名称、三元组、问题和答案。重新划分A/B,B的两条事实均不得进入阶段A原子或组合训练;目标实体须有其它真实A事实作为出现支持,关系搭配须在A组合中出现。源图中的显式直接/反向泄漏和名称歧义按数据审计排除。保留每条来源与实际分母;熟悉实体表示曾在A出现,不预先保证模型已掌握。 +- 一个开发划分,三个固定确认划分。三个确认划分来自同一真实图,不称三个独立世界;初始化与划分层级分开报告。数据选择只依据图和来源,不依据模型预测。 +- 固定普通四层完整Transformer,宽256、8头、GPT2 tokenizer、dropout=0,从随机初始化训练全部参数。首轮开发A阶段8,000更新、B阶段4,000更新,batch/microbatch=128,AdamW峰值lr=3e-4、wd=.1、两段余弦与200步warmup。所有历史共用按全局步定义的同一学习率日程。 +- 三种历史:A原子+AA组合后接B原子+A原子回放;A原子重复后接相同B阶段;前一种历史的同一份实际训练例总清单打乱后从头混合。另设组合父条件仅继续复习A原子的sham。主三历史都不提供含B的组合答案。 +- A阶段每批一半原子、一半组合,原子对照将组合槽换成A原子;B阶段一半B原子、一半A原子。顺序组合与混合的实际样本多重集、监督token相同;padding和批次构成带来的实际计算差异逐项记录,不声称FLOPs完全一致。 +- 初始开发采用两个配对初始化,每个初始化四历史。正式预算依据开发学习轨迹选择后固定,不能依据BB成绩挑配方或训练节点。所有开发结果保留。 +- 固定评价:A/B原子、训练组合、AA/BA/AB/BB直接生成、必要事实正确子集及其覆盖;阶段边界与终点另报模型自产第一跳后的第二次调用。别名EM为主,规范答案、无歧义别名、EOS/截断及NLL另报。 +- 开发首先看A原子、训练组合是否学会,以及AA留出上是否形成可测组合能力;B阶段看B原子学习和AA保持。操作失败先改开发配方,不把低BB本身当淘汰标准。确认集不参与任何选择。连续原子学习若损伤AA,使用sham区分继续训练与新事实干扰;必要的A组合回放另立修订,不暗中改变主臂。 +- 解释:组合历史优于原子历史支持先前使用经历的帮助;混合高而顺序低且AA保持支持学习顺序的额外困难;混合与顺序都低说明该配方的跨事实组合有限;AA下降时优先研究保持。 + +## 编辑写入目标实验 + +- 复用既有共享GPT对齐父模型,固定共享首块MLP参数可更新,其余冻结。只考察图选严格首跳事实,不按派生答案表现挑样本。 +- 三个目标:最终原子CE;再加早期实体CE;再加早期残差方向对新实体输入Embedding的对齐。额外CE和方向项系数均为.3,沿用父模型经过验证的权重。三个臂用同一新实体标签,不提供第二关系或派生答案。 +- 所有臂计算相同目标组件,未启用项权重置零;同lr=1e-5、32条旧原子父分布KL回放、Adam和512步。每个编辑配原旧事实复习sham;记录0/32/128/512步。 +- 开发父模型使用2个历史图选严格首跳事实,三个目标各独立容器。先重载历史编辑权重,测早期状态的新/旧实体读出及方向,再做新训练。开发判断只读E、必要事实及U原子保持,不能用D传播择优。 +- 确认采用三个既有世界、每世界两个初始化、每父模型四个图选事实、三个写入目标及edit/sham:18个独立作业、144个512步分支。属于配对扩展,不称新世界确认。 +- 主报全池D新答案、旧答案残留、未影响原子与组合保持;父模型会答子集同时报告覆盖。早期身份/方向是直接测量,不另训预测器。只改好身份、还是必须改表示形式、或两者都不足,由三个目标的端到端结果区分。 + +## 方法继承与执行 + +已阅读原文方法和相关附录:Grokking of Implicit Reasoning(NeurIPS 2024)§2–3及E.2,How do Transformers Learn Implicit Reasoning(NeurIPS 2025)§2.1–2.4,MQuAKE(EMNLP 2023)§2–4。继承原子/组合划分、首/次跳角色和编辑/后果/保持分开评价;扩展知识获得的时间顺序与同标签写入目标。完整阅读材料在 `results/literature-framing-review-20261007/`。 + +使用 `docker --context lm-memory`,固定已验证镜像,每作业独立容器、GPU、CPU/内存、tmpfs及持久结果目录,不开放端口。每次提交核对GPU实际占用及三个daemon容器预留,并取得GPU执行锁。全部科学作业同步启用W&B,团队zhusq20、项目llm-memory-editability;凭据只由主机记录进程读取。冻结配置、源码、输入哈希和配对训练计划;独立进程重载计分后才标为审计通过。工程失败停止该批后续提交,已运行任务正常结束,失败记录保留。 + +8张GPU的FP32/BF16矩阵计算、反向和同步检查已通过,证据为 `results/learning-use-runtime-20261007/summary.json`。开发与正式实验分别冻结,开发未完成不预先宣称正式结论或云端同步成功。 diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/results/write-target-development-v1/development-decision.json b/docs/development-artifacts/write-target-confirmation-v1/source/results/write-target-development-v1/development-decision.json new file mode 100644 index 0000000000000000000000000000000000000000..74b69aae5aef5001be76267e6b06e783105714e2 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/results/write-target-development-v1/development-decision.json @@ -0,0 +1,128 @@ +{ + "operational_gate_passed": true, + "decision_rule": "Every edit/sham E=1; U_atomic and necessary_atomic >=.95; no D access", + "configuration_search": false, + "records": [ + { + "run": "results/write-target-development-v1/runs/development-early_ce", + "case_id": "first_strict-00", + "objective": "early_ce", + "arm": "edit", + "target_accuracy": 1.0, + "U_atomic_accuracy": 0.9909182643794148, + "necessary_atomic_accuracy": 1.0, + "early_target_accuracy": 1.0 + }, + { + "run": "results/write-target-development-v1/runs/development-early_ce", + "case_id": "first_strict-00", + "objective": "early_ce", + "arm": "sham", + "target_accuracy": 1.0, + "U_atomic_accuracy": 1.0, + "necessary_atomic_accuracy": 1.0, + "early_target_accuracy": 1.0 + }, + { + "run": "results/write-target-development-v1/runs/development-early_ce", + "case_id": "first_strict-01", + "objective": "early_ce", + "arm": "edit", + "target_accuracy": 1.0, + "U_atomic_accuracy": 0.9939455095862765, + "necessary_atomic_accuracy": 1.0, + "early_target_accuracy": 1.0 + }, + { + "run": "results/write-target-development-v1/runs/development-early_ce", + "case_id": "first_strict-01", + "objective": "early_ce", + "arm": "sham", + "target_accuracy": 1.0, + "U_atomic_accuracy": 1.0, + "necessary_atomic_accuracy": 1.0, + "early_target_accuracy": 1.0 + }, + { + "run": "results/write-target-development-v1/runs/development-early_ce_align", + "case_id": "first_strict-00", + "objective": "early_ce_align", + "arm": "edit", + "target_accuracy": 1.0, + "U_atomic_accuracy": 0.9899091826437941, + "necessary_atomic_accuracy": 1.0, + "early_target_accuracy": 1.0 + }, + { + "run": "results/write-target-development-v1/runs/development-early_ce_align", + "case_id": "first_strict-00", + "objective": "early_ce_align", + "arm": "sham", + "target_accuracy": 1.0, + "U_atomic_accuracy": 1.0, + "necessary_atomic_accuracy": 1.0, + "early_target_accuracy": 1.0 + }, + { + "run": "results/write-target-development-v1/runs/development-early_ce_align", + "case_id": "first_strict-01", + "objective": "early_ce_align", + "arm": "edit", + "target_accuracy": 1.0, + "U_atomic_accuracy": 0.9939455095862765, + "necessary_atomic_accuracy": 1.0, + "early_target_accuracy": 1.0 + }, + { + "run": "results/write-target-development-v1/runs/development-early_ce_align", + "case_id": "first_strict-01", + "objective": "early_ce_align", + "arm": "sham", + "target_accuracy": 1.0, + "U_atomic_accuracy": 1.0, + "necessary_atomic_accuracy": 1.0, + "early_target_accuracy": 1.0 + }, + { + "run": "results/write-target-development-v1/runs/development-final_ce", + "case_id": "first_strict-00", + "objective": "final_ce", + "arm": "edit", + "target_accuracy": 1.0, + "U_atomic_accuracy": 0.9909182643794148, + "necessary_atomic_accuracy": 1.0, + "early_target_accuracy": 0.0 + }, + { + "run": "results/write-target-development-v1/runs/development-final_ce", + "case_id": "first_strict-00", + "objective": "final_ce", + "arm": "sham", + "target_accuracy": 1.0, + "U_atomic_accuracy": 1.0, + "necessary_atomic_accuracy": 1.0, + "early_target_accuracy": 1.0 + }, + { + "run": "results/write-target-development-v1/runs/development-final_ce", + "case_id": "first_strict-01", + "objective": "final_ce", + "arm": "edit", + "target_accuracy": 1.0, + "U_atomic_accuracy": 0.9939455095862765, + "necessary_atomic_accuracy": 1.0, + "early_target_accuracy": 0.0 + }, + { + "run": "results/write-target-development-v1/runs/development-final_ce", + "case_id": "first_strict-01", + "objective": "final_ce", + "arm": "sham", + "target_accuracy": 1.0, + "U_atomic_accuracy": 1.0, + "necessary_atomic_accuracy": 1.0, + "early_target_accuracy": 1.0 + } + ], + "created_utc": "2026-10-07T04:47:24.561322+00:00" +} diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/scripts/execute_learning_use.py b/docs/development-artifacts/write-target-confirmation-v1/source/scripts/execute_learning_use.py new file mode 100644 index 0000000000000000000000000000000000000000..b391ab7142a93986bfc978d575d6fe5b5c71ed25 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/scripts/execute_learning_use.py @@ -0,0 +1,344 @@ +"""Freeze and run new learning/use experiments without touching historical batches.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import json +import shutil +import subprocess +import sys +import time +import traceback +from pathlib import Path + +from run_memory_interface_next import environment, now, write + +PROJECT = Path("/ossfs/workspace/llm-memory-editability") +SCRIPT = "scripts/execute_learning_use.py" + + +def read(path): + return json.loads(Path(path).read_text()) + + +def sha(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def freeze(path): + config = read(path) + assert config["runtime"]["docker_context"] == "lm-memory" + assert config["runtime"]["image"].startswith("sha256:") + assert set(config["gpus"]) <= set(range(8)) and config["gpus"] + names = [spec["name"] for spec in config["specs"]] + assert names and len(names) == len(set(names)) + assert all(Path(name).name == name for name in names) + artifact = PROJECT / "docs/development-artifacts" / config["batch"] + source = artifact / "source" + if source.exists(): + raise FileExistsError("Frozen source already exists; use a new revision") + assert not (PROJECT / "results" / config["batch"] / "controller-state.json").exists() + inputs = {} + for spec in config["specs"]: + for key in ("data_file",): + if key in spec: + target = (PROJECT / spec[key]).resolve() + spec[key] = str(target) + spec[key + "_sha256"] = sha(target) + if key == "data_file": + assert spec.get("data_sha256", sha(target)) == sha(target) + spec["data_sha256"] = sha(target) + inputs[str(target)] = sha(target) + if "parent_dir" in spec: + parent = (PROJECT / spec["parent_dir"]).resolve() + spec["parent_dir"] = str(parent) + spec["parent_checkpoint_sha256"] = sha(parent / "model.pt") + inputs[str(parent / "model.pt")] = spec["parent_checkpoint_sha256"] + if (parent / "run.json").exists(): + inputs[str(parent / "run.json")] = sha(parent / "run.json") + if "tokenizer" in spec: + tokenizer = (PROJECT / spec["tokenizer"]).resolve() + spec["tokenizer"] = str(tokenizer) + for token_file in tokenizer.iterdir(): + if token_file.is_file(): + inputs[str(token_file)] = sha(token_file) + files = list((PROJECT / "src/llm_memory_editability").glob("*.py")) + files += [PROJECT / SCRIPT, PROJECT / "scripts/run_memory_interface_next.py"] + files += [PROJECT / "configs/experiment-tracking-defaults.json", path.resolve()] + files += [PROJECT / name for name in config.get("additional_sources", [])] + hashes = {} + for file in sorted(set(files)): + relative = file.relative_to(PROJECT) + target = source / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(file, target) + hashes[str(relative)] = sha(target) + config.update( + frozen_utc=now(), + repository=str(PROJECT), + source_root=str(source), + results_root=str(PROJECT / "results" / config["batch"]), + source=hashes, + input_files=inputs, + git_commit=subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=PROJECT, text=True + ).strip(), + ) + destination = artifact / "frozen-config.json" + write(destination, config) + write(artifact / "execution-lock.json", {"config_sha256": sha(destination)}) + print(json.dumps({"config": str(destination), "runs": len(names)})) + + +def checked(path): + assert sha(path) == read(path.with_name("execution-lock.json"))["config_sha256"] + config = read(path) + for relative, expected in config["source"].items(): + assert sha(Path(config["source_root"]) / relative) == expected, relative + for target, expected in config["input_files"].items(): + assert sha(target) == expected, target + return config + + +def gpu_available(gpu): + result = subprocess.run( + [ + "nvidia-smi", + "-i", + str(gpu), + "--query-gpu=memory.used,utilization.gpu", + "--format=csv,noheader,nounits", + ], + capture_output=True, + text=True, + check=True, + ) + memory, utilization = [int(value.strip()) for value in result.stdout.strip().split(",")] + if memory >= 256 or utilization >= 5: + return False + # A container can reserve a GPU before its first CUDA allocation. + for context in ("default", "d157", "lm-memory"): + identifiers = subprocess.check_output( + ["docker", "--context", context, "ps", "-q"], text=True + ).split() + if not identifiers: + continue + snapshots = json.loads( + subprocess.check_output( + ["docker", "--context", context, "inspect", *identifiers], text=True + ) + ) + for snapshot in snapshots: + for request in snapshot["HostConfig"].get("DeviceRequests") or []: + if request.get("Count") == -1 or str(gpu) in (request.get("DeviceIDs") or []): + return False + return True + + +def claim_gpu(gpu): + lock = open(f"/tmp/lm-learning-use-gpu-{gpu}.lock", "w") + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if not gpu_available(gpu): + lock.close() + return None + return lock + except BlockingIOError: + lock.close() + return None + + +def start_tracker(config, root): + command = [ + str(PROJECT / ".venv-wandb/bin/python"), + "-u", + "-m", + "llm_memory_editability.interface_tracking", + "--root", + str(root), + "--runs-dir", + str(root / "runs"), + "--defaults", + config["source_root"] + "/configs/experiment-tracking-defaults.json", + ] + with (root / "tracking.log").open("a") as log: + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + ) + write(root / "tracking-process.json", {"pid": process.pid, "command": command}) + deadline = time.monotonic() + 45 + while not (root / "tracking-ready.json").exists(): + if process.poll() is not None or time.monotonic() > deadline: + raise RuntimeError("W&B sidecar failed to initialize; see tracking.log") + time.sleep(0.25) + return process + + +def controller(path): + config = checked(path) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + lock = (root / "controller.lock").open("w") + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if (root / "controller-state.json").exists(): + raise FileExistsError( + "Existing history must be explicitly recovered, never silently restarted" + ) + shutil.copy2(path, root / "frozen-config.json") + state = dict( + state="starting", + started_utc=now(), + completed=[], + failed=[], + active={}, + queued=[spec["name"] for spec in config["specs"]], + gpus=config["gpus"], + ) + write(root / "controller-state.json", state) + active, pending = {}, list(enumerate(config["specs"])) + tracker = None + try: + tracker = start_tracker(config, root) + state["state"] = "running" + while pending or active: + for gpu, job in list(active.items()): + if job["process"].poll() is None: + continue + job["log"].close() + out = job["out"] + audit = read(out / "audit.json") if (out / "audit.json").exists() else {} + passed = job["process"].returncode == 0 and audit.get("passed") is True + state["completed" if passed else "failed"].append(job["spec"]["name"]) + write( + out / "process-status.json", + { + "returncode": job["process"].returncode, + "passed": passed, + "utc": now(), + }, + ) + if not passed and not (out / "failure.json").exists(): + write(out / "failure.json", {"reason": "worker_or_independent_audit_failed"}) + job["gpu_lock"].close() + del active[gpu] + if tracker.poll() is not None: + state["tracking_failure"] = tracker.returncode + # A failed contract pauses further submissions; already running jobs finish normally. + can_schedule = not state["failed"] and "tracking_failure" not in state + if can_schedule: + for gpu in config["gpus"]: + if gpu in active or not pending: + continue + gpu_lock = claim_gpu(gpu) + if gpu_lock is None: + continue + index, spec = pending.pop(0) + out = root / "runs" / spec["name"] + out.mkdir(parents=True, exist_ok=False) + command = [ + sys.executable, + "-u", + config["source_root"] + "/scripts/run_memory_interface_next.py", + "worker", + "--config", + str(path), + "--index", + str(index), + "--gpu", + str(gpu), + ] + log = (out / "worker.log").open("a") + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + ) + active[gpu] = dict( + process=process, log=log, out=out, spec=spec, gpu_lock=gpu_lock + ) + write(out / "host-worker.json", {"pid": process.pid, "command": command}) + state.update( + active={ + str(gpu): {"name": job["spec"]["name"], "pid": job["process"].pid} + for gpu, job in active.items() + }, + queued=[spec["name"] for _, spec in pending], + updated_utc=now(), + ) + write(root / "controller-state.json", state) + if not can_schedule and not active: + break + time.sleep(2) + state.update( + state="complete" + if not pending and not state["failed"] and "tracking_failure" not in state + else "finished_with_failures", + finished_utc=now(), + ) + write(root / "controller-state.json", state) + except BaseException: + state.update( + state="finished_with_failures", error=traceback.format_exc(), updated_utc=now() + ) + write(root / "controller-state.json", state) + raise + finally: + # Do not kill scientific jobs on a controller error. Preserve ownership and evidence. + for job in active.values(): + job["log"].close() + if tracker is not None and tracker.poll() is not None: + write(root / "tracking-exit.json", {"returncode": tracker.returncode}) + + +def launch(path): + config = checked(path) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + if (root / "controller-process.json").exists(): + raise FileExistsError("Controller has already been launched") + command = [ + sys.executable, + "-u", + config["source_root"] + "/" + SCRIPT, + "controller", + "--config", + str(path), + ] + with (root / "controller.log").open("a") as log: + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + write(root / "controller-process.json", {"pid": process.pid, "command": command, "utc": now()}) + print( + json.dumps( + { + "pid": process.pid, + "results": str(root), + "wandb": "https://wandb.ai/zhusq20/llm-memory-editability", + } + ) + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["freeze", "launch", "controller"]) + parser.add_argument("--config", type=Path, required=True) + args = parser.parse_args() + {"freeze": freeze, "launch": launch, "controller": controller}[args.action]( + args.config.resolve() + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/scripts/run_memory_interface_next.py b/docs/development-artifacts/write-target-confirmation-v1/source/scripts/run_memory_interface_next.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c8e478944e615761647dd0d1c900a86e48ae81 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/scripts/run_memory_interface_next.py @@ -0,0 +1,397 @@ +"""Freeze and execute sequential research stages on explicitly assigned GPUs.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import importlib +import json +import os +import shutil +import subprocess +import sys +import time +import traceback +from datetime import datetime, timezone +from pathlib import Path + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temp.replace(path) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def environment(source): + env = dict(os.environ) + if not env.get("MEMORY_INTERFACE_CONTAINER"): + env["LD_LIBRARY_PATH"] = "/lib64" + ( + ":" + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "" + ) + env.update(OMP_NUM_THREADS="1", MKL_NUM_THREADS="1", PYTHONPATH=str(source / "src")) + return env + + +def freeze(input_path): + config = json.loads(input_path.read_text()) + root = Path.cwd().resolve() + artifact = root / "docs/development-artifacts" / config["batch"] + source = artifact / "source" + if source.exists(): + raise FileExistsError(source) + assert len(config["gpus"]) == 4 and set(config["gpus"]) == {2, 3, 4, 5} + assert config["runtime"]["image"].startswith("sha256:") + assert config["runtime"]["docker_host"].startswith("unix://") + assert config["runtime"]["docker_context"] == "lm-memory", "Use only the LM project's daemon" + assert config["runtime"]["docker_host"] == "unix:///run/docker-lm-memory/docker.sock" + names = [s["name"] for s in config["specs"]] + assert len(names) == len(set(names)) and names + files = sorted( + list(Path("src/llm_memory_editability").glob("*.py")) + + [Path(__file__).relative_to(root), Path("configs/experiment-tracking-defaults.json")] + + [Path(p) for p in config.get("additional_sources", [])] + ) + config["source"] = {} + for path in files: + dest = source / path + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, dest) + config["source"][str(path)] = digest(path) + config.update( + frozen_utc=now(), + repository=str(root), + source_root=str(source), + results_root=str(root / "results" / config["batch"]), + git_commit=subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), + ) + for spec in config["specs"]: + if "parent_dir" in spec: + parent = (root / spec["parent_dir"]).resolve() + spec["parent_dir"] = str(parent) + spec["parent_checkpoint_sha256"] = digest(parent / "model.pt") + path = artifact / "frozen-config.json" + write(path, config) + print(json.dumps({"config": str(path), "runs": len(names), "source_files": len(files)})) + + +def launch(config_path): + config = json.loads(config_path.read_text()) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + saved_config = root / "frozen-config.json" + if saved_config.exists() and saved_config.read_bytes() != config_path.read_bytes(): + raise RuntimeError("The result directory contains a different frozen configuration") + shutil.copyfile(config_path, saved_config) + state = root / "controller-state.json" + if state.exists() and json.loads(state.read_text()).get("state") == "running": + raise RuntimeError("A running controller already owns this stage") + script = Path(config["source_root"]) / "scripts" / Path(__file__).name + command = [sys.executable, "-u", str(script), "controller", "--config", str(config_path)] + with (root / "controller.log").open("a") as log: + proc = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + write(root / "controller-process.json", {"pid": proc.pid, "command": command}) + print(json.dumps({"pid": proc.pid, "root": str(root)})) + + +def controller(config_path): + config = json.loads(config_path.read_text()) + root, source = Path(config["results_root"]), Path(config["source_root"]) + for path, expected in config["source"].items(): + assert digest(source / path) == expected, f"Frozen source changed: {path}" + state = { + "state": "running", + "started_utc": now(), + "gpus": config["gpus"], + "completed": [], + "failed": [], + "active": {}, + } + write(root / "controller-state.json", state) + env = environment(source) + tracking_python = str(Path(config["repository"]) / ".venv-wandb/bin/python") + tracker_command = [ + tracking_python, + "-u", + "-m", + "llm_memory_editability.interface_tracking", + "--root", + str(root), + "--runs-dir", + str(root / "runs"), + "--defaults", + str(source / "configs/experiment-tracking-defaults.json"), + ] + tracking_log = (root / "tracking.log").open("a") + tracker = subprocess.Popen( + tracker_command, env=env, stdout=tracking_log, stderr=subprocess.STDOUT + ) + write(root / "tracking-process.json", {"pid": tracker.pid, "command": tracker_command}) + queue = list(range(len(config["specs"]))) + active = {} + try: + deadline = time.monotonic() + 30 + while not (root / "tracking-ready.json").exists() and tracker.poll() is None: + if time.monotonic() >= deadline: + break + time.sleep(0.2) + if tracker.poll() is not None or not (root / "tracking-ready.json").exists(): + state["tracking_failure"] = "Tracking process did not become ready" + state["state"] = "finished_with_failures" + write(root / "controller-state.json", state) + raise RuntimeError(state["tracking_failure"]) + while queue or active: + if tracker.poll() is not None: + state["tracking_failure"] = f"Tracking process exited early: {tracker.returncode}" + for gpu, (proc, index, log) in list(active.items()): + result = proc.poll() + if result is None: + continue + log.close() + name = config["specs"][index]["name"] + state["completed" if result == 0 else "failed"].append(name) + del active[gpu] + # Stop scheduling after a failed contract rather than silently run an invalid matrix. + if state["failed"] or state.get("tracking_failure"): + queue.clear() + for gpu in config["gpus"]: + if gpu in active or not queue: + continue + index = queue.pop(0) + spec = config["specs"][index] + out = root / "runs" / spec["name"] + if ( + (out / "complete.json").exists() + and (out / "audit.json").exists() + and json.loads((out / "audit.json").read_text()).get("passed") is True + ): + state["completed"].append(spec["name"]) + continue + out.mkdir(parents=True, exist_ok=True) + log = (out / "worker.log").open("a") + command = [ + sys.executable, + "-u", + __file__, + "worker", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + str(gpu), + ] + proc = subprocess.Popen(command, env=env, stdout=log, stderr=subprocess.STDOUT) + active[gpu] = (proc, index, log) + state["active"] = { + str(gpu): {"pid": p.pid, "name": config["specs"][i]["name"]} + for gpu, (p, i, _) in active.items() + } + state["updated_utc"] = now() + write(root / "controller-state.json", state) + time.sleep(2) + state["state"] = ( + "complete" + if not state["failed"] and not state.get("tracking_failure") + else "finished_with_failures" + ) + state["finished_utc"] = now() + write(root / "controller-state.json", state) + try: + tracker.wait(timeout=120) + except subprocess.TimeoutExpired: + write(root / "tracking-pending.json", {"pid": tracker.pid, "reason": "sync pending"}) + write(root / "tracking-exit.json", {"returncode": tracker.returncode}) + finally: + tracking_log.close() + + +def container_work(config_path, index, gpu): + """One isolated container per experiment, including its fresh-process audit.""" + config = json.loads(config_path.read_text()) + spec, runtime = config["specs"][index], config["runtime"] + out = Path(config["results_root"]) / "runs" / spec["name"] + docker = ( + ["docker", "--context", runtime["docker_context"]] + if runtime.get("docker_context") + else ["docker", "--host", runtime["docker_host"]] + ) + name = ( + "lm-interface-" + hashlib.sha256((config["batch"] + spec["name"]).encode()).hexdigest()[:20] + ) + command = docker + [ + "run", + "--name", + name, + "--label", + "project=llm-memory-editability", + "--label", + "batch=" + config["batch"], + "--network=none", + "--gpus", + f"device={gpu}", + "--cpus", + str(runtime.get("cpus", 4)), + "--memory", + runtime.get("memory", "16g"), + "--shm-size=1g", + "--read-only", + "--tmpfs", + "/tmp:rw,size=2g", + "--mount", + f"type=bind,src={config['repository']},dst={config['repository']},readonly", + "--mount", + f"type=bind,src={out},dst={out}", + "--workdir", + config["repository"], + "--env", + "MEMORY_INTERFACE_CONTAINER=1", + "--env", + f"PHYSICAL_GPU={gpu}", + "--env", + "PYTHONDONTWRITEBYTECODE=1", + "--env", + "OMP_NUM_THREADS=1", + "--env", + "MKL_NUM_THREADS=1", + "--env", + "PYTHONPATH=" + str(Path(config["source_root"]) / "src"), + ] + for key, value in runtime.get("env", {}).items(): + command += ["--env", f"{key}={value}"] + command += [ + runtime["image"], + runtime["python"], + "-u", + __file__, + "container-worker", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + "0", + ] + write(out / "container-command.json", {"name": name, "physical_gpu": gpu, "command": command}) + process = subprocess.Popen(command) + for _ in range(50): + snapshot = subprocess.run(docker + ["inspect", name], capture_output=True, text=True) + if snapshot.returncode == 0: + info = json.loads(snapshot.stdout)[0] + if info["State"].get("Running"): + write( + out / "container-runtime.json", + { + "physical_gpu": gpu, + "host_pid": info["State"]["Pid"], + "container_id": info["Id"], + "image": info["Image"], + "cpus": runtime.get("cpus", 4), + "memory": runtime.get("memory", "16g"), + }, + ) + break + if process.poll() is not None: + break + time.sleep(0.2) + result = process.wait() + inspected = subprocess.run(docker + ["inspect", name], capture_output=True, text=True) + if inspected.returncode == 0: + write(out / "container-inspect.json", json.loads(inspected.stdout)) + if result: + raise RuntimeError(f"Experiment container exited {result}: {name}") + + +def work(config_path, index, gpu, audit_only=False): + import torch + + config = json.loads(config_path.read_text()) + spec = config["specs"][index] + out = Path(config["results_root"]) / "runs" / spec["name"] + torch.set_num_threads(1) + device = torch.device(f"cuda:{gpu}") + if "parent_dir" in spec: + assert digest(Path(spec["parent_dir"]) / "model.pt") == spec["parent_checkpoint_sha256"] + module = importlib.import_module("llm_memory_editability." + config["module"]) + if audit_only: + module.audit(out, device) + return + if not (out / "complete.json").exists(): + if config["module"] == "alignment_coverage": + module.train(spec, out, config["source"], device) + else: + module.run(spec, out, device) + # Deliberately reload in a fresh Python process, not the writer's model object. + subprocess.run( + [ + sys.executable, + "-u", + __file__, + "audit", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + str(gpu), + ], + check=True, + env=environment(Path(config["source_root"])), + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "action", choices=["freeze", "launch", "controller", "worker", "container-worker", "audit"] + ) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--index", type=int, default=0) + parser.add_argument("--gpu", type=int, default=2) + args = parser.parse_args() + path = args.config.resolve() + if args.action == "freeze": + freeze(path) + elif args.action == "launch": + launch(path) + elif args.action == "controller": + controller(path) + else: + config = json.loads(path.read_text()) + out = Path(config["results_root"]) / "runs" / config["specs"][args.index]["name"] + try: + if args.action == "worker": + with open(f"/tmp/llm-memory-interface-gpu-{args.gpu}.lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + container_work(path, args.index, args.gpu) + elif args.action == "container-worker": + assert os.environ.get("MEMORY_INTERFACE_CONTAINER") == "1" + work(path, args.index, args.gpu) + else: + work(path, args.index, args.gpu, True) + except Exception: + write( + out / "failure.json", + {"action": args.action, "utc": now(), "traceback": traceback.format_exc()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/scripts/run_write_target_editing.py b/docs/development-artifacts/write-target-confirmation-v1/source/scripts/run_write_target_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..f0b4e0cb0cb70511569a1dec8aefffa8aa52e419 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/scripts/run_write_target_editing.py @@ -0,0 +1,46 @@ +"""Run, independently audit, or inspect fixed write-target edit comparisons.""" + +import argparse +import json +from pathlib import Path + +from llm_memory_editability import write_target_editing as experiment +from llm_memory_editability.grok_depth import write_json + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + run = sub.add_parser("run") + run.add_argument("--spec", type=Path, required=True) + run.add_argument("--out", type=Path, required=True) + run.add_argument("--device", default="cuda:0") + audit = sub.add_parser("audit") + audit.add_argument("--out", type=Path, required=True) + audit.add_argument("--device", default="cuda:0") + diagnostic = sub.add_parser("diagnostics") + diagnostic.add_argument("--existing-dir", type=Path, required=True) + diagnostic.add_argument("--out", type=Path, required=True) + diagnostic.add_argument("--device", default="cuda:0") + decision = sub.add_parser("development-decision") + decision.add_argument("--run-dirs", nargs="+", type=Path, required=True) + decision.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + if args.command == "run": + result = experiment.run(json.loads(args.spec.read_text()), args.out, args.device) + elif args.command == "audit": + result = experiment.audit(args.out, args.device) + elif args.command == "diagnostics": + result = experiment.diagnostics(args.existing_dir, args.out, args.device) + else: + result = experiment.development_decision(args.run_dirs) + write_json(args.out, result) + print( + json.dumps( + {key: value for key, value in result.items() if key not in {"branches", "records"}} + ) + ) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/__init__.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c606cfd654948ec99bedce5244b7c6608a801a1d --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/__init__.py @@ -0,0 +1,19 @@ +"""Analytical examples for research on shared structure and editability.""" + +from .experiments import run_minimal_example +from .low_rank import ( + best_rank_approximation, + evaluate_update, + numerical_rank, + representation_gap, +) + +__version__ = "0.1.0" + +__all__ = [ + "best_rank_approximation", + "evaluate_update", + "numerical_rank", + "representation_gap", + "run_minimal_example", +] diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/__main__.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..860f4f8babf02fc2d6920b26bf4ac11a3e254766 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/__main__.py @@ -0,0 +1,5 @@ +"""Support ``python -m llm_memory_editability``.""" + +from .cli import main + +raise SystemExit(main()) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/alignment_coverage.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/alignment_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..6efacd7bf323dd87ad027292dee80a9f665032fa --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/alignment_coverage.py @@ -0,0 +1,503 @@ +"""Paired geometric-supervision coverage in the established complete GPT task. + +All arms retain full-token CE and all-example first-hop CE. Coverage changes +only a multiplicative mask on the per-example geometric objective; every arm +executes the same forward and backward operations, including the zero mask. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .latent_scaling import build_world, model_digest +from .representation_alignment import new_model +from .representation_alignment import pack_training as pack_base_training +from .storage_composition import data_digest, evaluate, file_hash +from .storage_frontier import learning_rate + +COVERAGES = ("none", "composition_only", "all_atomic_and_composition") +NORMALIZATIONS = ("selected_mean", "batch_mean") +STRATA = ("common_atomic", "train_composite", "anchor_atomic") +COMPONENTS = ( + "text_ce", + "bridge_ce", + "alignment_loss", + "alignment_all_mean", + "alignment_selected_mean", + "alignment_batch_mean", + "alignment_selected_count", + "alignment_denominator", +) + + +def make_specs(phase="development"): + """Return the proposed paired matrix without freezing files or starting jobs.""" + if phase not in ("development", "confirmation"): + raise ValueError("Phase must be development or confirmation") + worlds = [810011] if phase == "development" else [810101, 810102, 810103] + initializations = [811011] if phase == "development" else [811101, 811102] + base = { + "phase": phase, + "stream_seed": 812011 if phase == "development" else 812101, + "heads_n": 256, + "bridges_n": 128, + "tails_n": 64, + "familiar_n": 64, + "strict_n": 32, + "anchor_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "composition_count": 256, + "width": 128, + "heads": 4, + "layers": 1, + "repeats": 2, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 16000, + "nodes": [0, 256, 1000, 2000, 4000, 8000, 16000], + "bridge_weight": 0.3, + "alignment_weight": 0.3, + } + arms = ( + ("none", "none", "batch_mean"), + ("composition_batch", "composition_only", "batch_mean"), + ("composition_selected", "composition_only", "selected_mean"), + ("all_batch", "all_atomic_and_composition", "batch_mean"), + ) + return [ + { + **base, + "nodes": list(base["nodes"]), + "world": world, + "initialization": initialization, + "arm": arm, + "alignment_coverage": coverage, + "alignment_normalization": normalization, + } + for world in worlds + for initialization in initializations + for arm, coverage, normalization in arms + ] + + +def validate_spec(spec): + if spec["alignment_coverage"] not in COVERAGES: + raise ValueError(f"Unknown alignment coverage: {spec['alignment_coverage']}") + if spec["alignment_normalization"] not in NORMALIZATIONS: + raise ValueError(f"Unknown alignment normalization: {spec['alignment_normalization']}") + if spec["bridge_weight"] != 0.3: + raise ValueError("This comparison fixes all-example first-hop CE weight at 0.3") + if not np.isfinite(spec["alignment_weight"]) or spec["alignment_weight"] < 0: + raise ValueError("Alignment weight must be finite and nonnegative") + if spec["batch_size"] <= 0 or spec["batch_size"] % 3: + raise ValueError("Batch size must divide equally into the three fixed streams") + nodes = spec["nodes"] + if not nodes or nodes[0] != 0 or nodes[-1] != spec["steps"]: + raise ValueError("Nodes must include initialization and the fixed endpoint") + if nodes != sorted(set(nodes)) or any(type(n) is not int or n < 0 for n in nodes): + raise ValueError("Nodes must be strictly increasing nonnegative integer steps") + if spec["steps"] <= 0: + raise ValueError("Training needs a positive fixed step budget") + + +def pack_training(world, coverage): + """Keep base data byte-identical and append an explicit geometry mask.""" + if coverage not in COVERAGES: + raise ValueError(f"Unknown alignment coverage: {coverage}") + arrays, sizes = pack_base_training(world) + if min(sizes) <= 0: + raise ValueError("All three training strata must be nonempty") + mask = np.zeros(sum(sizes), dtype=np.float32) + if coverage == "composition_only": + mask[sizes[0] : sizes[0] + sizes[1]] = 1 + elif coverage == "all_atomic_and_composition": + mask[:] = 1 + return (*arrays, mask), sizes + + +def objective( + model, + tokens, + labels, + targets, + geometry_mask, + bridge_weight=0.3, + alignment_weight=0.3, + normalization="selected_mean", +): + """Return the training loss and named, unweighted objective components. + + selected_mean divides by selected examples (clamped to one for an empty + mask). batch_mean divides by all examples. Both reductions are always + evaluated, and mask coverage is recorded separately from loss strength. + """ + if normalization not in NORMALIZATIONS: + raise ValueError(f"Unknown alignment normalization: {normalization}") + 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() + per_example = (F.normalize(bridge, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1) + mask = geometry_mask.to(dtype=per_example.dtype) + selected_count = mask.sum() + numerator = (per_example * mask).sum() + selected_denominator = selected_count.clamp_min(1) + # Avoid creating a device scalar from host data during CUDA graph capture. + batch_denominator = torch.ones_like(selected_count) * per_example.numel() + selected_mean = numerator / selected_denominator + batch_mean = numerator / batch_denominator + use_selected = float(normalization == "selected_mean") + denominator = use_selected * selected_denominator + (1 - use_selected) * batch_denominator + alignment = numerator / denominator + parts = torch.stack( + ( + text_ce, + bridge_ce, + alignment, + per_example.mean(), + selected_mean, + batch_mean, + selected_count, + denominator, + ) + ) + return text_ce + bridge_weight * bridge_ce + alignment_weight * alignment, parts + + +class CoverageStep(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, mask = (part[self.index] for part in self.table) + loss, self.components = objective( + self.model, + tokens, + labels, + targets, + mask, + self.spec["bridge_weight"], + self.spec["alignment_weight"], + self.spec["alignment_normalization"], + ) + 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']}-" + f"{spec['alignment_coverage']}-{spec['alignment_normalization']}" + ) + + +def _draw_indices(streams, offsets, counts, steps, batch_size): + indices = [] + for j, stream in enumerate(streams): + drawn = stream.take(steps * batch_size // 3).reshape(steps, -1) + counts[j] += np.bincount(drawn.ravel(), minlength=len(counts[j])) + indices.append(drawn + offsets[j]) + return np.concatenate(indices, axis=1) + + +def _coverage_presentations(counts, mask, sizes): + offset, result = 0, {} + for name, count, size in zip(STRATA, counts, sizes, strict=True): + result[name] = int(np.dot(count, mask[offset : offset + size].astype(np.int64))) + offset += size + result["total"] = sum(result.values()) + return result + + +def train(spec, out, source, device): + """Train one immutable attempt; save weights and exposures at every node.""" + validate_spec(spec) + out, device = Path(out), torch.device(device) + out.mkdir(parents=True, exist_ok=True) + if any((out / name).exists() for name in ("run.json", "model.pt", "complete.json")): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + if device.type != "cuda": + raise ValueError("The captured training step requires an explicitly allocated CUDA device") + 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, spec["alignment_coverage"]) + mask = arrays[-1] + model = new_model(spec, device) + initial_hash, world_hash = model_digest(model), data_digest(world) + identity = { + "spec": spec, + "source": source, + "implementation_sha256": file_hash(Path(__file__)), + "world_sha256": world_hash, + "initial_model_sha256": initial_hash, + } + write_json( + out / "run.json", + { + **identity, + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device), + "dtype": "float32", + "allow_tf32": True, + "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, + "strata": dict(zip(STRATA, sizes, strict=True)), + "geometry_unique_examples": _coverage_presentations( + [np.ones(n, dtype=np.int64) for n in sizes], mask, sizes + ), + "geometry_definition": ( + "squared distance of normalized early state and detached input embedding" + ), + "bridge_ce_coverage": "all_atomic_and_composition", + "geometry_normalization": spec["alignment_normalization"], + "tracking_owner": "external read-only batch runner", + }, + ) + 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 = CoverageStep(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, checkpoints, step, training_seconds = [], [], 0, 0.0 + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 9, output_positions=9) + 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] * len(COMPONENTS) + coverage = _coverage_presentations(counts, mask, sizes) + row = { + "step": step, + "metrics": metrics, + **dict(zip(COMPONENTS, parts, strict=True)), + "alignment_normalization": spec["alignment_normalization"], + "alignment_weight": spec["alignment_weight"], + "geometry_target_presentations": coverage, + "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], + "sample_stream_sha256": input_hash.hexdigest(), + } + 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", **{f"stratum{j}": c for j, c in enumerate(counts)} + ) + checkpoint = out / f"model-{step:06d}.pt" + torch.save( + { + **identity, + "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), + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": coverage, + }, + checkpoint, + ) + checkpoints.append({"step": step, "file": checkpoint.name, "sha256": file_hash(checkpoint)}) + write_json(out / "checkpoints.json", checkpoints) + 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 = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) + 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() + # Keep the established downstream loader interface on filesystems without links. + shutil.copyfile(out / f"model-{step:06d}.pt", out / "model.pt") + np.savez_compressed(out / "exposures.npz", **{f"stratum{j}": c for j, c in enumerate(counts)}) + write_json( + out / "complete.json", + { + **identity, + "finished_utc": utc(), + "metrics": history[-1]["metrics"], + "training_seconds": training_seconds, + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": history[-1]["geometry_target_presentations"], + "model_sha256": file_hash(out / "model.pt"), + "nodes_saved": spec["nodes"], + }, + ) + write_json(out / "status.json", {"state": "complete", "step": step}) + + +def audit(out, device, *, all_nodes=False): + """Verify all artifacts; independently reload the endpoint (or all nodes).""" + out, device = Path(out), torch.device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + run = json.loads((out / "run.json").read_text()) + complete = json.loads((out / "complete.json").read_text()) + history = json.loads((out / "learning.json").read_text()) + manifest = json.loads((out / "checkpoints.json").read_text()) + spec = run["spec"] + validate_spec(spec) + assert spec == complete["spec"] + assert [row["step"] for row in history] == spec["nodes"] + assert [entry["step"] for entry in manifest] == spec["nodes"] + assert complete["nodes_saved"] == spec["nodes"] + assert file_hash(out / "model.pt") == complete["model_sha256"] == manifest[-1]["sha256"] + world = build_world(spec) + assert data_digest(world) == run["world_sha256"] == complete["world_sha256"] + with np.load(out / "world.npz") as saved_world: + assert set(saved_world.files) == set(world) + for key, value in world.items(): + np.testing.assert_array_equal(value, saved_world[key]) + arrays, sizes = pack_training(world, spec["alignment_coverage"]) + mask, offsets = arrays[-1], np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] + counts = [np.zeros(n, dtype=np.int64) for n in sizes] + input_hash, step, audits = hashlib.sha256(), 0, [] + model = new_model(spec, device) + assert model_digest(model) == run["initial_model_sha256"] == complete["initial_model_sha256"] + for entry, row in zip(manifest, history, strict=True): + while step < entry["step"]: + n = min(128, entry["step"] - step) + indices = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) + input_hash.update(indices.tobytes()) + step += n + checkpoint = out / entry["file"] + assert file_hash(checkpoint) == entry["sha256"] + payload = torch.load(checkpoint, map_location="cpu", weights_only=False) + assert payload["spec"] == spec and payload["step"] == step + for key in ("source", "implementation_sha256", "world_sha256", "initial_model_sha256"): + assert payload[key] == run[key] == complete[key] + assert ( + payload["sample_stream_sha256"] == row["sample_stream_sha256"] == input_hash.hexdigest() + ) + coverage = _coverage_presentations(counts, mask, sizes) + assert ( + payload["geometry_target_presentations"] + == row["geometry_target_presentations"] + == coverage + ) + with np.load(out / f"exposures-{step:06d}.npz") as saved_counts: + for j, count in enumerate(counts): + np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) + np.testing.assert_array_equal(count, payload["counts"][j]) + if step == 0: + model.load_state_dict(payload["model"]) + assert model_digest(model) == run["initial_model_sha256"] + if not all_nodes and step != spec["steps"]: + audits.append({"step": step, "passed": True, "predictions_recomputed": False}) + continue + model.load_state_dict(payload["model"]) + metrics, predictions = evaluate(model, world, "low", device) + max_nll_error = 0.0 + with np.load(out / f"predictions-{step:06d}.npz") as saved: + assert set(saved.files) == set(predictions) + 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]) + for split, values in metrics.items(): + for key, actual in values.items(): + expected = row["metrics"][split][key] + if actual is None: + assert expected is None + else: + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-5) + audits.append( + { + "step": step, + "passed": True, + "predictions_recomputed": True, + "max_nll_error": max_nll_error, + } + ) + assert complete["sample_stream_sha256"] == input_hash.hexdigest() + assert complete["geometry_target_presentations"] == _coverage_presentations(counts, mask, sizes) + with np.load(out / "exposures.npz") as saved_counts: + for j, count in enumerate(counts): + np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) + result = { + "passed": True, + "metrics": metrics, + "nodes": audits, + "max_nll_error": max(a.get("max_nll_error", 0.0) for a in audits), + "all_nodes": all_nodes, + "allow_tf32": True, + "world_sha256": data_digest(world), + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": _coverage_presentations(counts, mask, sizes), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/architecture_bridge.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/architecture_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..3d611f12f7be01721c8f453b8981605455e4b585 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/architecture_bridge.py @@ -0,0 +1,549 @@ +"""Paired interventions on MLP output and same-layer sequence cache. + +Oracle bridge hints define an assisted diagnostic, not an identified natural +reasoning circuit. Cache interventions do not change model parameters. +""" + +from __future__ import annotations + +import contextlib +import copy +import hashlib +import json +import re +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "data/architecture-bridge-v1" +ART = ROOT / "docs/development-artifacts/architecture-bridge-v1" +RESULTS = ROOT / "results/architecture-bridge-v1" +CONFIG = ROOT / "configs/architecture-bridge-v1.json" + + +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 order(value): + return hashlib.sha256(f"142935:{value}".encode()).hexdigest() + + +def normalize(value): + import string + + value = value.lower().translate(str.maketrans("", "", string.punctuation)) + return " ".join(re.sub(r"\b(a|an|the)\b", " ", value).split()) + + +def grade(text, answer, aliases=()): + value = text.rsplit("Final answer:", 1)[-1].strip() + value = re.sub(r"^(?:Answer|Bridge):\s*", "", value, flags=re.I).strip().strip('"*') + predicted, gold = normalize(value), normalize(answer) + a, b = Counter(predicted.split()), Counter(gold.split()) + common = sum((a & b).values()) + return { + "em": predicted == gold, + "f1": 2 * common / (sum(a.values()) + sum(b.values())) if common else 0.0, + "alias_em": predicted in {normalize(x) for x in [answer, *aliases]}, + } + + +def base_prompt(row, question=None): + context = row.get("support_context", "") + parts = ["Question: What is 2 + 2?\nAnswer: 4", "Output only the short answer."] + if context: + parts.append("Use the supplied passages.\nPassages:\n" + context) + parts.append("Question: " + (question if question is not None else row["question"])) + return "\n\n".join(parts) + + +def prefix(row, bridge): + return base_prompt(row) + "\nIntermediate entity: " + bridge + "\n" + + +def prepare(): + from transformers import AutoTokenizer + + if (ART / "data-lock.json").exists(): + raise FileExistsError("This data selection is already frozen") + cfg = read(CONFIG) + toks = { + k: AutoTokenizer.from_pretrained(ROOT / v["path"], local_files_only=True) + for k, v in cfg["models"].items() + } + source_path = ROOT / "data/twohop-frozen-v1/cases.json" + source, selected, audit = read(source_path), [], {} + for dataset in cfg["datasets"]: + for split, count in cfg["cases_per_dataset"].items(): + pool = sorted( + [x for x in source if x["dataset"] == dataset and x["split"] == split], + key=lambda x: order(x["id"]), + ) + for row in pool[:count]: + r = copy.deepcopy(row) + names = sorted({p["bridge"] for p in pool}, key=order) + forbidden = {normalize(x) for x in [r["bridge"], *r.get("bridge_aliases", [])]} + gold = {normalize(x) for x in [r["answer"], *r.get("aliases", [])]} + target = {k: len(t.encode(prefix(r, r["bridge"]))) for k, t in toks.items()} + chosen = [] + for name in names: + norm = normalize(name) + if norm in forbidden or any(g and g in norm for g in gold): + continue + if all(len(t.encode(prefix(r, name))) == target[k] for k, t in toks.items()): + chosen.append(name) + if len(chosen) == 2: + break + reason = None + if len(chosen) < 2: + reason = "fewer_than_two_length_matched_wrong_bridges" + if max(target.values()) > cfg["max_prefix_tokens"]: + reason = "prefix_exceeds_budget" + if any(g and g in normalize(r["bridge"]) for g in gold): + reason = "correct_bridge_contains_final_answer" + competitors = [ + x["answer"] for x in pool if normalize(x["answer"]) != normalize(r["answer"]) + ] + r.update( + prefix_tokens=target, + corrupted_bridge=chosen[0] if chosen else None, + control_bridge=chosen[1] if len(chosen) > 1 else None, + exclusion_reason=reason, + competitor=(r.get("wrong_donor") or {}).get("answer", competitors[0]), + ) + selected.append(r) + audit[f"{dataset}:{split}"] = { + "selected": count, + "eligible": sum( + x["exclusion_reason"] is None + for x in selected + if x["dataset"] == dataset and x["split"] == split + ), + } + # E comes from selected evaluation rows; R and U are independent source groups + # from the unused historical pool. D is never used to choose a direction. + edits = [r for r in selected if r["dataset"] == "2wiki" and r["split"] == "evaluation"] + used = {r["group"] for r in selected if r["dataset"] == "2wiki"} + reserves = sorted( + [ + r + for r in source + if r["dataset"] == "2wiki" and r["split"] == "evaluation" and r["group"] not in used + ], + key=lambda r: order("keep:" + r["id"]), + ) + lc = cfg["local_learning"] + learning = { + "E": edits[: lc["episodes"]], + "R": reserves[: lc["keep_R"]], + "U": reserves[lc["keep_R"] : lc["keep_R"] + lc["unseen_U"]], + } + assert len(learning["U"]) == lc["unseen_U"] + write(DATA / "cases.json", selected) + write(DATA / "learning.json", learning) + write( + ART / "data-lock.json", + { + "config": cfg, + "config_sha256": digest(CONFIG), + "source_sha256": digest(source_path), + "cases_sha256": digest(DATA / "cases.json"), + "learning_sha256": digest(DATA / "learning.json"), + "audit": audit, + "selection": ( + "Fixed hash before outputs; excluded cases are retained without replacement." + ), + }, + ) + return audit + + +def cache_fields(cache, layer): + obj = cache.layers[layer] + if hasattr(obj, "recurrent_states"): + return [("conv_states", 0), ("recurrent_states", 0)] + return [("keys", None), ("values", None)] + + +def field_get(obj, name, index): + value = getattr(obj, name) + return value if index is None else value[index] + + +def field_set(obj, name, index, value): + if index is None: + setattr(obj, name, value) + else: + getattr(obj, name)[index] = value + + +def matched_random(delta, seed): + generator = torch.Generator(device=delta.device).manual_seed(seed) + random = torch.randn(delta.shape, device=delta.device, dtype=delta.dtype, generator=generator) + return random * (delta.norm() / random.norm().clamp_min(torch.finfo(delta.dtype).tiny)) + + +def change_cache(target, donor, layer, random_seed=None): + # Keep recipient metadata and update only equal-shaped tensors. Prefix length + # and token positions are identical across donors in the frozen selection. + stats = {} + for i, (name, index) in enumerate(cache_fields(target, layer)): + a = field_get(target.layers[layer], name, index) + b = field_get(donor.layers[layer], name, index) + if a.shape != b.shape: + raise ValueError(f"Unequal cache shapes for {name}: {a.shape} != {b.shape}") + delta = b - a + if random_seed is not None: + delta = matched_random(delta, random_seed + i) + stats[name + "_delta_norm"] = float(delta.norm()) + field_set( + target.layers[layer], name, index, b.clone() if random_seed is None else a + delta + ) + return stats + + +class Engine: + def __init__(self, key, device=None): + from transformers import ( + AutoTokenizer, + PreTrainedTokenizerFast, + Qwen3_5ForCausalLM, + Qwen3ForCausalLM, + ) + + self.cfg = read(CONFIG) + self.key, self.mc = key, self.cfg["models"][key] + self.device = torch.device(device or self.cfg["device"]) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + if self.device.type == "cuda": + torch.cuda.set_per_process_memory_fraction(self.cfg["gpu_memory_fraction"], self.device) + cls = Qwen3ForCausalLM if key == "qwen3" else Qwen3_5ForCausalLM + # In transformers 5.17 Qwen2Tokenizer rebuilds Qwen3.5's regex and drops + # Unicode combining marks. Load the official tokenizer.json unchanged. + tokenizer_cls = AutoTokenizer if key == "qwen3" else PreTrainedTokenizerFast + self.tok = tokenizer_cls.from_pretrained(ROOT / self.mc["path"], local_files_only=True) + self.model = ( + cls.from_pretrained( + ROOT / self.mc["path"], + local_files_only=True, + dtype=torch.float32, + attn_implementation="eager", + ) + .to(self.device) + .eval() + .requires_grad_(False) + ) + self.layers = self.model.model.layers + self.stats = Counter() + self.eos = self.tok.eos_token_id + + def ids(self, text): + return torch.tensor([self.tok.encode(text, add_special_tokens=False)], device=self.device) + + def forward(self, ids, cache=None, total=None): + total = ids.shape[1] if total is None else total + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += ids.numel() + return self.model( + input_ids=ids, + attention_mask=torch.ones((1, total), device=self.device, dtype=torch.long), + past_key_values=cache, + use_cache=True, + logits_to_keep=1, + ) + + @contextlib.contextmanager + def mlp_hook(self, layer, replacement=None, capture=None): + def hook(module, args, output): + if capture is not None: + capture[layer] = output[0, -1].detach().clone() + if replacement is None: + return None + modified = output.clone() + modified[0, -1] = replacement + return modified + + handle = self.layers[layer].mlp.register_forward_hook(hook) + try: + yield + finally: + handle.remove() + + @torch.no_grad() + def prefill(self, text, layer=None, replacement=None): + ids, captured = self.ids(text), {} + if ids.shape[1] > self.cfg["max_prefix_tokens"]: + raise ValueError("Prefix exceeds budget; truncation is forbidden") + with contextlib.ExitStack() as stack: + for li in self.mc["layers"]: + stack.enter_context( + self.mlp_hook(li, replacement if li == layer else None, captured) + ) + out = self.forward(ids) + return out.past_key_values, captured, ids.shape[1] + + @torch.no_grad() + def continuation_score(self, logits, cache, total, answer): + targets = self.tok.encode(" " + answer, add_special_tokens=False) + [self.eos] + values = [] + for index, token in enumerate(targets): + values.append(float(logits[0, -1].log_softmax(-1)[token])) + if index + 1 < len(targets): + total += 1 + out = self.forward(torch.tensor([[token]], device=self.device), cache, total) + logits, cache = out.logits, out.past_key_values + return {"sum_logp": sum(values), "mean_logp": float(np.mean(values)), "tokens": targets} + + @torch.no_grad() + def finish(self, cache, n_prefix, row, suffix=None): + suffix_ids = self.ids(self.cfg["suffix"] if suffix is None else suffix) + total = n_prefix + suffix_ids.shape[1] + out = self.forward(suffix_ids, cache, total) + logits, cache = out.logits, out.past_key_values + scores = {} + for name, answer in [("correct", row["answer"]), ("competitor", row["competitor"])]: + scores[name] = self.continuation_score(logits, copy.deepcopy(cache), total, answer) + scores["margin"] = scores["correct"]["mean_logp"] - scores["competitor"]["mean_logp"] + tokens = [] + for _ in range(self.cfg["generation_tokens"]): + token = int(logits[0, -1].argmax()) + tokens.append(token) + if token == self.eos: + break + total += 1 + out = self.forward(torch.tensor([[token]], device=self.device), cache, total) + logits, cache = out.logits, out.past_key_values + text = self.tok.decode(tokens, skip_special_tokens=True) + self.stats["generated_tokens"] += len(tokens) + return { + "text": text, + "tokens": tokens, + "ended_eos": tokens[-1] == self.eos, + **grade(text, row["answer"], row.get("unambiguous_aliases", row.get("aliases", []))), + "scores": scores, + } + + def direct(self, row, question=None, answer=None): + qrow = dict(row) + if answer is not None: + qrow.update(answer=answer, aliases=[], unambiguous_aliases=[]) + cache, _, length = self.prefill(base_prompt(row, question)) + return self.finish(cache, length, qrow) + + @torch.no_grad() + def case(self, row): + started = time.monotonic() + before_stats = self.stats.copy() + result = { + "id": row["id"], + "dataset": row["dataset"], + "split": row["split"], + "group": row["group"], + "exclusion_reason": row["exclusion_reason"], + "unassisted": self.direct(row), + "first_hop": self.direct(row, row["q1"], row["bridge"]), + "second_hop": self.direct(row, row["q2"]), + "interventions": [], + } + if row["exclusion_reason"]: + result["seconds"] = time.monotonic() - started + result["resources"] = dict(self.stats - before_stats) + return result + caches, activations, lengths = {}, {}, {} + for name, bridge in [ + ("correct", row["bridge"]), + ("corrupt", row["corrupted_bridge"]), + ("wrong", row["control_bridge"]), + ]: + caches[name], activations[name], lengths[name] = self.prefill(prefix(row, bridge)) + if len(set(lengths.values())) != 1: + raise AssertionError("Token-length matching contract broken") + n = lengths["corrupt"] + if n != row["prefix_tokens"][self.key]: + raise AssertionError("Tokenizer revision changed the frozen prefix length") + result["oracle_input"] = self.finish(copy.deepcopy(caches["correct"]), n, row) + for layer in self.mc["layers"]: + baseline = None + for condition in self.cfg["conditions"]: + donor = "wrong" if condition.endswith("wrong") else "correct" + seed = int(order(row["id"] + str(layer))[:8], 16) + use_mlp = condition.startswith(("mlp_", "joint_")) + use_state = condition.startswith(("state_", "joint_")) + stats = {} + if use_mlp: + delta = activations[donor][layer] - activations["corrupt"][layer] + if condition.endswith("random"): + delta = matched_random(delta, seed) + replacement = ( + activations["corrupt"][layer] + delta + if condition.endswith("random") + else activations[donor][layer] + ) + stats["mlp_delta_norm"] = float(delta.norm()) + cache, _, _ = self.prefill( + prefix(row, row["corrupted_bridge"]), layer, replacement + ) + else: + cache = copy.deepcopy(caches["corrupt"]) + if use_state or condition == "identity": + source = caches["corrupt"] if condition == "identity" else caches[donor] + stats.update( + change_cache( + cache, source, layer, seed + 1 if condition.endswith("random") else None + ) + ) + prediction = self.finish(cache, n, row) + if condition == "baseline": + baseline = prediction + if condition == "identity": + if prediction["tokens"] != baseline["tokens"]: + raise AssertionError("Identity cache changed generated tokens") + if abs(prediction["scores"]["margin"] - baseline["scores"]["margin"]) > 1e-5: + raise AssertionError("Identity cache changed scores") + result["interventions"].append( + { + "layer": layer, + "condition": condition, + "cache_kind": self.mc["kind"], + **stats, + **prediction, + } + ) + result["seconds"] = time.monotonic() - started + result["resources"] = dict(self.stats - before_stats) + return result + + def prompt_suffix_ids(self, prompt): + # Match prefill(prompt) followed by finish(suffix), including BPE boundaries. + return torch.cat([self.ids(prompt), self.ids(self.cfg["suffix"])], dim=1) + + def next_logits(self, prompt): + ids = self.prompt_suffix_ids(prompt) + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += ids.numel() + if torch.is_grad_enabled(): + self.stats["backward_input_tokens"] += ids.numel() + return self.model(input_ids=ids, use_cache=False, logits_to_keep=1).logits[0, -1] + + def target_loss(self, row): + x = self.prompt_suffix_ids(base_prompt(row, row["q1"])) + target = self.tok.encode(" " + row["bridge"], add_special_tokens=False) + [self.eos] + y = torch.tensor([target], device=self.device) + inputs = torch.cat([x, y[:, :-1]], dim=1) + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += inputs.numel() + self.stats["backward_input_tokens"] += inputs.numel() + self.stats["supervised_tokens"] += y.numel() + logits = self.model(input_ids=inputs, use_cache=False, logits_to_keep=len(target)).logits + return torch.nn.functional.cross_entropy(logits.flatten(0, 1), y.flatten()) + + def learning(self, episode, output_dir): + before_stats = self.stats.copy() + lc = self.cfg["local_learning"] + pools = read(DATA / "learning.json") + target = pools["E"][episode] + parameter = self.layers[lc["layer"]].mlp.down_proj.weight + original = parameter.detach().clone() + teacher = {} + for role in ["R", "U"]: + with torch.no_grad(): + teacher[role] = [ + self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1).detach() + for r in pools[role] + ] + result = {"episode": episode, "target_id": target["id"], "nodes": [], "training": []} + started = time.monotonic() + try: + parameter.requires_grad_(True) + optimizer = torch.optim.SGD([parameter], lr=lc["lr"]) + for step in range(lc["steps"] + 1): + if step in lc["nodes"]: + node = { + "step": step, + "E": self.direct(target, target["q1"], target["bridge"]), + "D": self.direct(target), + "R": [], + "U": [], + "parameter_delta_norm": float((parameter.detach() - original).norm()), + } + for role in ["R", "U"]: + for r, old_lp in zip(pools[role], teacher[role], strict=True): + r = dict(r, competitor=target["bridge"]) + with torch.no_grad(): + lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) + kl = float((old_lp.exp() * (old_lp - lp)).sum()) + node[role].append( + { + "id": r["id"], + "kl": kl, + **self.direct(r, r["q1"], r["bridge"]), + } + ) + result["nodes"].append(node) + write(output_dir / "progress.json", result) + if step == lc["steps"]: + break + optimizer.zero_grad(set_to_none=True) + loss = self.target_loss(target) + target_value = float(loss.detach()) + loss.backward() + replay_value = 0.0 + for r, old_lp in zip(pools["R"], teacher["R"], strict=True): + lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) + kl = (old_lp.exp() * (old_lp - lp)).sum() + replay_value += float(kl.detach()) / len(pools["R"]) + (lc["replay_KL_weight"] * kl / len(pools["R"])).backward() + norm = float(torch.nn.utils.clip_grad_norm_([parameter], lc["gradient_clip"])) + if not np.isfinite(target_value + replay_value + norm): + raise FloatingPointError("Nonfinite local learning response") + optimizer.step() + result["training"].append( + { + "step": step + 1, + "target_ce": target_value, + "R_kl": replay_value, + "gradient_norm": norm, + } + ) + torch.save( + { + "down_weight": parameter.detach().cpu(), + "target_id": target["id"], + "layer": lc["layer"], + "steps": lc["steps"], + }, + output_dir / "endpoint.pt", + ) + finally: + with torch.no_grad(): + parameter.copy_(original) + parameter.requires_grad_(False) + if not torch.equal(parameter, original): + raise AssertionError("Episode failed to restore original weight") + result["seconds"] = time.monotonic() - started + result["restored_original"] = True + result["resources"] = dict(self.stats - before_stats) + return result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/architecture_bridge_toy.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/architecture_bridge_toy.py new file mode 100644 index 0000000000000000000000000000000000000000..a406337c9f1b455c1c07183ec90de18541f7d03b --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/architecture_bridge_toy.py @@ -0,0 +1,410 @@ +"""A frozen small GQA / gated-delta mechanism experiment. + +Both models use RMSNorm, SwiGLU and tied token embeddings. The hybrid is a +deliberately small mechanism model, NOT an implementation of any Qwen release. +Its delta mixer has a genuine recurrent matrix, causal q/k/v convolution, +normalized q/k, input-dependent decay/write gates, and a headwise output gate. +""" + +from __future__ import annotations + +import hashlib +import math +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from llm_memory_editability.twohop_depth import BOS, ENTITY, EOS + + +class RMSNorm(nn.Module): + def __init__(self, width, eps): + super().__init__() + self.weight = nn.Parameter(torch.ones(width)) + self.eps = eps + + def forward(self, x): + return x * torch.rsqrt(x.square().mean(-1, keepdim=True) + self.eps) * self.weight + + +def rope(x, offset): + """Full rotary position embedding; head width is even.""" + width = x.shape[-1] + positions = torch.arange(offset, offset + x.shape[-2], device=x.device, dtype=x.dtype) + inverse = 10000.0 ** (-torch.arange(0, width, 2, device=x.device, dtype=x.dtype) / width) + phase = positions[:, None] * inverse[None, :] + even, odd = x[..., 0::2], x[..., 1::2] + return torch.stack( + (even * phase.cos() - odd * phase.sin(), even * phase.sin() + odd * phase.cos()), + dim=-1, + ).flatten(-2) + + +class GQA(nn.Module): + def __init__(self, cfg): + super().__init__() + width, self.heads, self.kv_heads = cfg["width"], cfg["heads"], cfg["kv_heads"] + self.dim = width // self.heads + self.q = nn.Linear(width, width, bias=False) + self.k = nn.Linear(width, self.kv_heads * self.dim, bias=False) + self.v = nn.Linear(width, self.kv_heads * self.dim, bias=False) + self.out = nn.Linear(width, width, bias=False) + self.q_norm = RMSNorm(self.dim, cfg["norm_eps"]) + self.k_norm = RMSNorm(self.dim, cfg["norm_eps"]) + + def forward(self, x, cache=None): + batch, length, width = x.shape + offset = 0 if cache is None else cache["k"].shape[2] + q = self.q(x).view(batch, length, self.heads, self.dim).transpose(1, 2) + k = self.k(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) + v = self.v(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) + q, k = rope(self.q_norm(q), offset), rope(self.k_norm(k), offset) + if cache is not None: + k, v = torch.cat((cache["k"], k), 2), torch.cat((cache["v"], v), 2) + new_cache = {"k": k, "v": v} + repeat = self.heads // self.kv_heads + keys, values = k.repeat_interleave(repeat, 1), v.repeat_interleave(repeat, 1) + scores = (q @ keys.transpose(-2, -1)) / math.sqrt(self.dim) + allowed = ( + torch.arange(k.shape[2], device=x.device)[None, :] + <= torch.arange(offset, offset + length, device=x.device)[:, None] + ) + scores = scores.masked_fill(~allowed, float("-inf")) + out = (scores.softmax(-1) @ values).transpose(1, 2).reshape(batch, length, width) + return self.out(out), new_cache + + +class GatedDelta(nn.Module): + def __init__(self, cfg): + super().__init__() + width, self.heads = cfg["width"], cfg["heads"] + self.dim, self.kernel = width // self.heads, cfg["conv_kernel"] + self.qkv = nn.Linear(width, 3 * width, bias=False) + self.conv_weight = nn.Parameter(torch.empty(self.kernel, 3 * width)) + self.decay = nn.Linear(width, self.heads, bias=True) + self.write = nn.Linear(width, self.heads, bias=True) + self.gate = nn.Linear(width, self.heads, bias=True) + self.out_norm = RMSNorm(self.dim, cfg["norm_eps"]) + self.out = nn.Linear(width, width, bias=False) + + def forward(self, x, cache=None): + batch, length, width = x.shape + raw = self.qkv(x) + if cache is None: + history = raw.new_zeros(batch, self.kernel - 1, 3 * width) + state = raw.new_zeros(batch, self.heads, self.dim, self.dim) + else: + history, state = cache["conv"], cache["state"] + full = torch.cat((history, raw), 1) + convolved = sum(full[:, j : j + length] * self.conv_weight[j] for j in range(self.kernel)) + q, k, v = F.silu(convolved).chunk(3, -1) + q = F.normalize(q.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) + k = F.normalize(k.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) + v = v.view(batch, length, self.heads, self.dim) + alpha = torch.exp(-F.softplus(self.decay(x))) + beta, gate = self.write(x).sigmoid(), self.gate(x).sigmoid() + outputs = [] + for t in range(length): + # S_t = alpha S_(t-1)(I-beta kk^T) + beta vk^T. + state = alpha[:, t, :, None, None] * state + read_at_key = (state * k[:, t, :, None, :]).sum(-1) + error = v[:, t] - read_at_key + state = state + beta[:, t, :, None, None] * (error[..., :, None] * k[:, t, :, None, :]) + outputs.append((state * q[:, t, :, None, :]).sum(-1)) + out = self.out_norm(torch.stack(outputs, 1)) * gate[..., None] + new_cache = {"conv": full[:, -(self.kernel - 1) :], "state": state} + return self.out(out.reshape(batch, length, width)), new_cache + + +class SwiGLU(nn.Module): + def __init__(self, cfg): + super().__init__() + self.up = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) + self.gate = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) + self.down = nn.Linear(cfg["mlp_hidden"], cfg["width"], bias=False) + + def forward(self, x): + return self.down(self.up(x) * F.silu(self.gate(x))) + + +class Block(nn.Module): + def __init__(self, kind, cfg): + super().__init__() + self.norm_mixer = RMSNorm(cfg["width"], cfg["norm_eps"]) + self.mixer = GQA(cfg) if kind == "gqa" else GatedDelta(cfg) + self.norm_mlp = RMSNorm(cfg["width"], cfg["norm_eps"]) + self.mlp = SwiGLU(cfg) + + +def apply_patch(output, patch): + if patch is None: + return output + result = output.clone() + result[:, patch["positions"]] = patch["value"].to(output) + return result + + +class ToyLM(nn.Module): + def __init__(self, architecture, cfg): + super().__init__() + self.config = cfg + self.architecture = architecture + self.token = nn.Embedding(ENTITY + cfg["entities"] + cfg["relations"], cfg["width"]) + self.blocks = nn.ModuleList(Block(kind, cfg) for kind in architecture["mixers"]) + self.norm_final = RMSNorm(cfg["width"], cfg["norm_eps"]) + + def forward( + self, tokens, positions=None, *, cache=None, patches=None, capture=False, return_cache=False + ): + h, states, trace = self.token(tokens), [], {} + patches = {} if patches is None else patches + for layer, block in enumerate(self.blocks): + past = None if cache is None else cache[layer] + mixer, state = block.mixer(block.norm_mixer(h), past) + mixer = apply_patch(mixer, patches.get(("mixer", layer))) + h = h + mixer + mlp = apply_patch(block.mlp(block.norm_mlp(h)), patches.get(("mlp", layer))) + h = h + mlp + states.append(state) + if capture: + trace[("mixer", layer)], trace[("mlp", layer)] = mixer, mlp + h = self.norm_final(h) + if positions is not None: + h = h[torch.arange(len(h), device=h.device)[:, None], positions] + logits = F.linear(h, self.token.weight) + return (logits, states, trace) if capture or return_cache else logits + + +def initialize(model, seed): + """Pair every common named and shaped parameter without RNG-order effects.""" + with torch.no_grad(): + for name, parameter in model.named_parameters(): + if name.endswith(".bias"): + parameter.zero_() + elif "norm" in name and name.endswith(".weight"): + parameter.fill_(1) + else: + key = hashlib.sha256(f"{seed}:{name}".encode()).digest() + generator = torch.Generator().manual_seed(int.from_bytes(key[:8], "little")) + std = 0.02 + if name.endswith("mixer.out.weight") or name.endswith("mlp.down.weight"): + std /= math.sqrt(2 * len(model.blocks)) + parameter.copy_(torch.randn(parameter.shape, generator=generator) * std) + + +def parameter_digest(model): + h = hashlib.sha256() + for name, parameter in model.named_parameters(): + h.update(name.encode()) + h.update(parameter.detach().cpu().contiguous().numpy().tobytes()) + return h.hexdigest() + + +def exposure(cfg, steps): + count = cfg["batch_per_kind"] * steps + return { + "steps": steps, + "atomic_examples": count, + "training_composite_examples": count, + "valid_input_tokens": count * 11, + "processed_tokens_including_padding": count * 12, + "supervised_answer_eos_tokens": count * 4, + } + + +def flops_estimate(model, cfg, steps): + """Conventional 6*N*T estimate plus transparent small mixer correction.""" + params = sum(p.numel() for p in model.parameters()) + tokens = exposure(cfg, steps)["processed_tokens_including_padding"] + n_gqa = model.architecture["mixers"].count("gqa") + n_delta = model.architecture["mixers"].count("delta") + length, width, heads = 6, cfg["width"], cfg["heads"] + dim = width // heads + mixing = tokens * (n_gqa * 12 * length * width + n_delta * 24 * heads * dim * dim) + return { + "parameter_count": params, + "conventional_6_parameter_token_flops": 6 * params * tokens, + "additional_mixing_flops_approx": mixing, + "total_approx": 6 * params * tokens + mixing, + "limitation": ( + "Rough training estimate, not profiler measurements; 6NT includes embeddings " + "and excludes detailed normalization/activation costs." + ), + } + + +@torch.no_grad() +def generate(model, x, y, device, batch=128, patches=None): + result = {key: [] for key in ("pred", "eos", "logp", "logits")} + for start in range(0, len(x), batch): + tokens = torch.as_tensor(x[start : start + batch], device=device) + target = torch.as_tensor(y[start : start + batch], device=device) + part = None + if patches is not None: + part = { + key: { + "positions": value["positions"], + "value": value["value"][start : start + batch], + } + for key, value in patches.items() + } + logits = model(tokens, patches=part)[:, -1] + prediction = logits.argmax(-1) + stop = model(torch.cat((tokens, prediction[:, None]), 1), patches=part)[:, -1].argmax(-1) + result["pred"].append(prediction.cpu().numpy()) + result["eos"].append(stop.cpu().numpy()) + result["logp"].append(logits.log_softmax(-1).gather(1, target[:, None]).cpu().numpy()[:, 0]) + result["logits"].append(logits.cpu().numpy()) + return {key: np.concatenate(value) for key, value in result.items()} + + +@torch.no_grad() +def evaluate(model, world, cfg, device): + model.eval() + arrays, metrics = {}, {} + for name, key, mask in ( + ("atomic", "atomic", slice(None)), + ("train", "composite", world["train_mask"]), + ("test", "composite", ~world["train_mask"]), + ): + x, y = world[key + "_x"][mask], world[key + "_y"][mask] + output = generate(model, x, y, device, cfg["eval_batch"]) + for field, value in output.items(): + arrays[f"{name}_{field}"] = value + correct = (output["pred"] == y) & (output["eos"] == EOS) + metrics[name] = { + "n": len(y), + "answer_accuracy": float(np.mean(output["pred"] == y)), + "exact_answer_eos": float(correct.mean()), + "answer_nll": float(-output["logp"].mean()), + } + indices = np.flatnonzero(~world["train_mask"]) + a, r1, r2 = world["comps"][indices].T + bridge = arrays["atomic_pred"][a * cfg["relations"] + r1] + bridge_eos = arrays["atomic_eos"][a * cfg["relations"] + r1] + second = np.c_[np.full(len(a), BOS), bridge, ENTITY + cfg["entities"] + r2] + y = world["composite_y"][indices] + output = generate(model, second, y, device, cfg["eval_batch"]) + arrays.update({f"two_call_{field}": value for field, value in output.items()}) + arrays["two_call_bridge"], arrays["two_call_bridge_eos"] = bridge, bridge_eos + correct = (output["pred"] == y) & (output["eos"] == EOS) & (bridge_eos == EOS) + metrics["two_call"] = {"n": len(y), "exact_answer_eos": float(correct.mean())} + atom_ok = (arrays["atomic_pred"] == world["atomic_y"]) & (arrays["atomic_eos"] == EOS) + gold_bridge = world["maps"][r1, a] + both = atom_ok[a * cfg["relations"] + r1] & atom_ok[gold_bridge * cfg["relations"] + r2] + direct_ok = (arrays["test_pred"] == y) & (arrays["test_eos"] == EOS) + arrays["test_both_atoms_correct"] = both + metrics["test_given_both_atoms"] = { + "n": int(both.sum()), + "coverage": float(both.mean()), + "exact_answer_eos": float(direct_ok[both].mean()) if both.any() else None, + } + return metrics, arrays + + +def intervention_conditions(traces, cfg, device): + """Same orthogonal transform for both donor norms; no fitted direction.""" + rng = np.random.default_rng(cfg["random_control_seed"]) + perm = torch.as_tensor(rng.permutation(cfg["width"]), device=device) + signs = torch.as_tensor(rng.choice([-1.0, 1.0], cfg["width"]), device=device) + sites = { + "mlp": (cfg["mlp_layer"], cfg["mlp_position"]), + "mixer": (cfg["mixer_layer"], cfg["mixer_position"]), + } + conditions, norms = {}, {} + for target in cfg["patch_targets"]: + kinds = ("mlp", "mixer") if target == "joint" else (target,) + for donor in cfg["patch_donors"]: + patches, measurements = {}, {} + for kind in kinds: + layer, position = sites[kind] + base = traces["identity"][(kind, layer)][:, [position]] + source = donor.replace("random_", "") + delta = traces[source][(kind, layer)][:, [position]] - base + if donor.startswith("random_"): + delta = delta[..., perm] * signs.to(delta) + patches[(kind, layer)] = {"positions": [position], "value": base + delta} + measurements[kind] = delta.flatten(1).norm(dim=-1).cpu().numpy() + key = f"{target}_{donor}" + conditions[key], norms[key] = patches, measurements + return conditions, norms + + +@torch.no_grad() +def diagnostics(model, world, cfg, device): + model.eval() + cases = world["cases"] + query = world["composite_x"][cases[:, 0]] + correct = np.c_[ + np.full(len(cases), BOS), + ENTITY + cases[:, 9], + ENTITY + cfg["entities"] + cases[:, 10], + ENTITY + cfg["entities"] + cases[:, 3], + ] + wrong = np.c_[ + np.full(len(cases), BOS), + ENTITY + cases[:, 6], + ENTITY + cfg["entities"] + cases[:, 2], + ENTITY + cfg["entities"] + cases[:, 3], + ] + traces = {} + for key, x in (("identity", query), ("correct", correct), ("wrong", wrong)): + _, _, traces[key] = model(torch.as_tensor(x, device=device), capture=True) + conditions, norms = intervention_conditions(traces, cfg, device) + target, competitor = ENTITY + cases[:, 5], ENTITY + cases[:, 8] + arrays = { + "case_ids": cases[:, 0], + "target": target, + "wrong_target": competitor, + "query": query, + "correct_donor": correct, + "wrong_donor": wrong, + } + baseline = generate(model, query, target, device, cfg["eval_batch"]) + base_ok = (baseline["pred"] == target) & (baseline["eos"] == EOS) + metrics = {} + for name, patches in {"baseline": None, **conditions}.items(): + output = ( + baseline + if patches is None + else generate(model, query, target, device, cfg["eval_batch"], patches) + ) + for field, value in output.items(): + arrays[f"{name}_{field}"] = value + row = np.arange(len(target)) + margin = output["logits"][row, target] - output["logits"][row, competitor] + arrays[f"{name}_margin"] = margin + exact = (output["pred"] == target) & (output["eos"] == EOS) + wrong_ok = (output["pred"] == competitor) & (output["eos"] == EOS) + metrics[name] = { + "n": len(target), + "correct_exact": float(exact.mean()), + "wrong_exact": float(wrong_ok.mean()), + "rescued": int((exact & ~base_ok).sum()), + "damaged": int((~exact & base_ok).sum()), + "baseline_correct_n": int(base_ok.sum()), + "baseline_incorrect_n": int((~base_ok).sum()), + "mean_correct_minus_wrong_margin": float(margin.mean()), + "max_logit_change": float(np.max(np.abs(output["logits"] - baseline["logits"]))), + } + for kind, value in norms.get(name, {}).items(): + arrays[f"{name}_{kind}_norm"] = value + # Functional interaction in the 2x2 channel intervention, not an attribution percentage. + for donor in ("correct", "wrong", "random_correct", "random_wrong"): + interaction = ( + arrays[f"joint_{donor}_margin"] + - arrays[f"mlp_{donor}_margin"] + - arrays[f"mixer_{donor}_margin"] + + arrays["baseline_margin"] + ) + arrays[f"interaction_{donor}"] = interaction + return metrics, arrays + + +def save_npz(path, arrays): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed(path, **arrays) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_analysis.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae07fb7fccdec9430d5e69bc1b304a9fcebe914 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_analysis.py @@ -0,0 +1,399 @@ +"""Audit saved edit predictions and describe failures without selecting successes.""" + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from .bios_data import N_BASE, RELATIONS, load_world, write_json + +RETENTION_GROUPS = ("0", "1", "2", "3", "2_base", "2_derived") + + +def read(path): + return json.loads(path.read_text()) + + +def failure_flags(point, accuracy=0.95, damage=0.01): + rates = [point["U_heldout_destruction"][g]["rate"] for g in RETENTION_GROUPS] + return { + "E": point["E_root"] < 1 or point["E_member"] < accuracy, + "D": point["D"] < accuracy, + "U": any(r is not None and r > damage for r in rates), + "unevaluable": any(r is None for r in rates), + } + + +def failure_signature(flags): + if flags["unevaluable"]: + return "unevaluable" + return "+".join(k for k in ("E", "D", "U") if flags[k]) or "pass" + + +def propagation_errors(world, sets, prediction): + ids = sets["D"] + value, ended = prediction["prediction"][ids], prediction["ended"][ids] + target = sets["target"][ids] + actual = sets["target"][2112 + world.person[ids]] + correct = (value == target) & ended + remaining = ~correct + counts = {"correct": int(correct.sum())} + for name, mask in ( + ("nontermination", ~ended), + ("old_default", value == world.answers[ids]), + ("personal_city_instead_of_company_default", value == actual), + ): + counts[name] = int((remaining & mask).sum()) + remaining &= ~mask + counts["other_wrong_value"] = int(remaining.sum()) + assert sum(counts.values()) == len(ids) + strata = {} + old_exception = world.exceptions[world.person[ids]] + for name, mask in ( + ("old_exception", old_exception), + ("updated_personal_equals_default", ~old_exception & (actual == target)), + ("updated_personal_differs_from_default", ~old_exception & (actual != target)), + ): + strata[name] = {"n": int(mask.sum()), "correct": int(correct[mask].sum())} + return {"counts": counts, "strata": strata} + + +def retention_masks(sets, old_correct, view="heldout"): + eligible = old_correct.copy() + if view != "full": + selected = np.zeros(len(eligible), dtype=bool) + selected[sets[view]] = True + eligible &= selected + masks = {str(g): eligible & (sets["strata"] == g) for g in range(4)} + masks["2_base"] = masks["2"] & (np.arange(len(eligible)) < N_BASE) + masks["2_derived"] = masks["2"] & (np.arange(len(eligible)) >= N_BASE) + return masks + + +def retention_counts(sets, correct, old_correct, view="heldout"): + return { + group: { + "known": int(mask.sum()), + "broken": int((mask & ~correct).sum()), + "rate": float((~correct[mask]).mean()) if mask.any() else None, + } + for group, mask in retention_masks(sets, old_correct, view).items() + } + + +def dump_csv(path, rows): + if not rows: + return + with path.open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def summarize_group(cases): + n = len(cases) + result = {"n": n} + for field in ("E", "E_root", "E_member", "D", "U_accuracy", "E_target_value_nll"): + result[f"mean_{field}"] = float(np.mean([c["final"][field] for c in cases])) + result.update( + final_pass=sum(c["final"]["joint_pass"] is True for c in cases), + ever_pass=sum(c["first_observed_joint_step"] is not None for c in cases), + regressed=sum( + c["first_observed_joint_step"] is not None and not c["final"]["joint_pass"] + for c in cases + ), + signatures=dict(Counter(c["failure_signature"] for c in cases)), + **{f"fail_{k}": sum(c["failure_flags"][k] for c in cases) for k in ("E", "D", "U")}, + ) + for g in RETENTION_GROUPS: + rates = [c["final"]["U_heldout_destruction"][g]["rate"] for c in cases] + result[f"fail_U{g}"] = sum(r is not None and r > 0.01 for r in rates) + result[f"mean_U{g}_damage"] = float(np.mean([r for r in rates if r is not None])) + result["D_error_counts"] = dict( + sum((Counter(c["propagation"]["counts"]) for c in cases), Counter()) + ) + result["mean_initial_new_answer_nll"] = float(np.mean([c["initial_nll"] for c in cases])) + return result + + +def run(args): + root, out = Path(args.root), Path(args.output) + out.mkdir(parents=True, exist_ok=True) + worlds = {i: load_world(f"data/bios-work-v1/world-{i}") for i in (0, 1)} + cases, audit, timelines = [], [], [] + lookup = {} + for run_dir in sorted(root.glob("world-*-seed-*-*")): + config = read(run_dir / "config.json") + world = worlds[config["world_seed"]] + for dirname, window in (("edits", 3), ("edits-window0", 0)): + completed = read(run_dir / dirname / "complete.json") + assert completed["status"] == "complete" and len(completed["cases"]) == 16 + for path in sorted((run_dir / dirname).glob("*/complete.json")): + c = read(path) + assert c["status"] == "complete" and c["final"]["step"] == 512 + assert c["window_zero_based"] == list(range(window, window + 3)) + sets = dict(np.load(path.parent / "sets.npz")) + pred = dict(np.load(path.parent / "predictions-512.npz")) + correct = (pred["prediction"] == sets["target"]) & pred["ended"] + np.testing.assert_array_equal(correct, pred["correct"]) + retention = retention_counts(sets, correct, sets["old_correct"]) + assert retention == c["final"]["U_heldout_destruction"] + for name, ids in ( + ("E", sets["E"]), + ("D", sets["D"]), + ("E_root", sets["E"][world.relation[sets["E"]] == 1]), + ("E_member", sets["E"][world.relation[sets["E"]] == 2]), + ): + assert float(correct[ids].mean()) == c["final"][name] + trajectory = read(path.parent / "trajectory.json") + for point in trajectory: + flags = failure_flags(point) + expected = None if flags["unevaluable"] else not any(flags.values()) + assert point["joint_pass"] == expected + flags = failure_flags(c["final"]) + damaged_by_relation = {} + for group, mask in retention_masks(sets, sets["old_correct"]).items(): + broken = mask & ~correct + damaged_by_relation[group] = { + name: int((broken & (world.relation == relation)).sum()) + for relation, name in enumerate((*RELATIONS, "derived_default_city")) + } + assert sum(damaged_by_relation[group].values()) == int(broken.sum()) + method = f"FT-{c['scope'].upper()}" + if c["branch"]: + method += f"+{c['branch']}" + meta = { + "run": run_dir.name, + "world": world.seed, + "seed": config["seed"], + "order": config["order"], + "window": window, + "method": method, + "kind": c["kind"], + "support": c["support"], + } + c.update( + meta, + directory=str(path.parent), + failure_flags=flags, + failure_signature=failure_signature(flags), + heldout_damage_by_relation=damaged_by_relation, + propagation=propagation_errors(world, sets, pred), + replay_retention=retention_counts(sets, correct, sets["old_correct"], "replay"), + initial_nll=trajectory[0]["E_target_value_nll"], + ever_E=any(not failure_flags(p)["E"] for p in trajectory), + ever_D=any(not failure_flags(p)["D"] for p in trajectory), + ever_U=any(not failure_flags(p)["U"] for p in trajectory), + last_failure_free_E_step=max( + (p["step"] for p in trajectory if not failure_flags(p)["E"]), default=None + ), + down_calibration=c["final"].get("down_calibration"), + ) + cases.append(c) + lookup[(run_dir.name, window, method, c["kind"], c["support"])] = (c, sets, pred) + audit.append( + {"path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()} + ) + timelines.extend( + {**meta, **p, "failure_flags": failure_flags(p)} for p in trajectory + ) + assert len(cases) == 256 + groups = defaultdict(list) + for c in cases: + groups[(c["window"], c["method"], c["order"], c["kind"])].append(c) + aggregates = [ + {"window": w, "method": m, "order": o, "kind": k, **summarize_group(cs)} + for (w, m, o, k), cs in sorted(groups.items()) + ] + common, duplicates, branch_pairs = [], [], [] + for (run_name, window, method, kind, support), (case, sets, pred) in lookup.items(): + if case["order"] == "SA": + other, other_sets, other_pred = lookup[ + (run_name[:-2] + "AS", window, method, kind, support) + ] + for field in ( + "E", + "D", + "target", + "heldout", + "replay", + "strata", + "edit_sampling", + "replay_sampling", + ): + np.testing.assert_array_equal(sets[field], other_sets[field]) + known = sets["old_correct"] & other_sets["old_correct"] + sa = retention_counts(sets, pred["correct"], known) + ass = retention_counts(sets, other_pred["correct"], known) + common.append( + { + "world": case["world"], + "seed": case["seed"], + "window": window, + "method": method, + "kind": kind, + "support": support, + "SA": sa, + "AS": ass, + } + ) + if method == "FT-ALL" and window == 3: + _, _, duplicate = lookup[(run_name, 0, method, kind, support)] + duplicates.append( + { + "run": run_name, + "kind": kind, + "support": support, + "identical_final_predictions": bool( + all(np.array_equal(pred[k], duplicate[k]) for k in pred) + ), + } + ) + if case["branch"]: + baseline, _, baseline_pred = lookup[(run_name, window, "FT-MLP", kind, support)] + branch_pairs.append( + { + "run": run_name, + "window": window, + "method": method, + "kind": kind, + "support": support, + **{f"delta_{k}": case["final"][k] - baseline["final"][k] for k in ("E", "D")}, + "baseline_joint": baseline["final"]["joint_pass"], + "branch_joint": case["final"]["joint_pass"], + "changed_predictions_vs_baseline": int( + (pred["prediction"] != baseline_pred["prediction"]).sum() + ), + "max_value_nll_difference_vs_baseline": float( + np.max(np.abs(pred["value_nll"] - baseline_pred["value_nll"])) + ), + } + ) + sensitivity = [] + for (window, method, order, kind), cs in sorted(groups.items()): + for accuracy in (0.90, 0.95, 0.99): + for damage in (0.0, 0.01, 0.02, 0.05): + sensitivity.append( + { + "window": window, + "method": method, + "order": order, + "kind": kind, + "accuracy_threshold": accuracy, + "damage_threshold": damage, + "n": len(cs), + "final_pass": sum( + not any(failure_flags(c["final"], accuracy, damage).values()) + for c in cs + ), + } + ) + quality = [] + for world in (0, 1): + for seed in (0, 1): + sa, ass = [ + read(root / f"world-{world}-seed-{seed}-{order}" / "complete.json")["final"] + for order in ("SA", "AS") + ] + quality.append( + { + "world": world, + "seed": seed, + "base_difference_pp": 100 * (sa["base_accuracy"] - ass["base_accuracy"]), + "derived_difference_pp": 100 + * (sa["derived_accuracy"] - ass["derived_accuracy"]), + "passed": bool( + min( + sa["base_accuracy"], + ass["base_accuracy"], + sa["derived_accuracy"], + ass["derived_accuracy"], + ) + >= 0.99 + and abs(sa["base_accuracy"] - ass["base_accuracy"]) <= 0.005 + and abs(sa["derived_accuracy"] - ass["derived_accuracy"]) <= 0.005 + and abs(sa["value_nll"] - ass["value_nll"]) <= 0.1 + ), + } + ) + quality_keys = {(q["world"], q["seed"]) for q in quality if q["passed"]} + quality_aggregates = [] + for (w, m, o, k), cs in sorted(groups.items()): + subset = [c for c in cs if (c["world"], c["seed"]) in quality_keys] + quality_aggregates.append( + {"window": w, "method": m, "order": o, "kind": k, **summarize_group(subset)} + ) + report = { + "phase": "symbolic development; descriptive; not independent edit replicates", + "cases": cases, + "groups": aggregates, + "common_known_retention": common, + "branch_paired_support0": branch_pairs, + "ft_all_window_duplicates": duplicates, + "quality_pairs": quality, + "quality_subset_groups": quality_aggregates, + "sensitivity": sensitivity, + "source_audit": audit, + "expected_cases": 256, + "audited_cases": len(cases), + } + write_json(out / "failure-analysis.json", report) + write_json(out / "edit-trajectories.json", timelines) + dump_csv( + out / "failure-summary.csv", + [{k: v for k, v in row.items() if not isinstance(v, dict)} for row in aggregates], + ) + dump_csv(out / "threshold-sensitivity.csv", sensitivity) + dump_csv(out / "branch-paired-support0.csv", branch_pairs) + dump_csv( + out / "case-failures.csv", + [ + { + **{ + k: c[k] + for k in ( + "run", + "world", + "seed", + "order", + "window", + "method", + "kind", + "support", + "failure_signature", + "first_observed_joint_step", + "initial_nll", + ) + }, + **{k: c["final"][k] for k in ("E", "E_root", "E_member", "D", "joint_pass")}, + } + for c in cases + ], + ) + print( + json.dumps( + { + "audited_cases": len(cases), + "groups": len(aggregates), + "quality_pairs_passed": len(quality_keys), + "FT_ALL_identical_duplicate_cases": sum( + d["identical_final_predictions"] for d in duplicates + ), + } + ) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", default="results/bios-dev-v1") + parser.add_argument("--output", default="results/bios-dev-v1/failure-analysis-20260926") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_branch.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c6ebef8f0f501ac43d2d94de8f4f59b954208b --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_branch.py @@ -0,0 +1,127 @@ +"""Equal-parameter residual branches from old-world activation directions.""" + +import time + +import numpy as np +import torch +from torch import nn + +from .bios_data import ANS +from .bios_train import precision + + +class ResidualBranch(nn.Module): + def __init__(self, q, mean, scale, width=32, seed=73): + super().__init__() + self.register_buffer("q", q) + self.register_buffer("mean", mean) + self.register_buffer("scale", scale) + # Explicit local RNG: same A in all arms without changing training RNG state. + generator = torch.Generator(device=q.device).manual_seed(seed) + self.a = nn.Parameter( + torch.randn(width, q.shape[1], generator=generator, device=q.device) / q.shape[1] ** 0.5 + ) + self.b = nn.Parameter(torch.zeros(q.shape[0], width, device=q.device)) + + def forward(self, v): + s = (v.float() @ self.q - self.mean) / self.scale + return (torch.nn.functional.gelu(s @ self.a.T) @ self.b.T).to(v.dtype) + + +@torch.no_grad() +def build_bases(model, world, data, layer=4, rank=32): + device = data["tokens"].device + values = [] + + def capture(_module, _inputs, output): + values.append(output[:, 3].float()) + + handle = model.blocks[layer].register_forward_hook(capture) + started = time.perf_counter() + try: + with precision(device): + for begin in range(2112, 4160, 256): + model( + data["prompts"][begin : begin + 256], + data["lengths"][begin : begin + 256, None] - 1, + ) + finally: + handle.remove() + v = torch.cat(values) + group_means = torch.stack( + [v[torch.as_tensor(world.employers == c, device=device)].mean(0) for c in range(64)] + ) + centered_means = group_means - v.mean(0) + _, shared_s, shared_vh = torch.linalg.svd(centered_means, full_matrices=False) + q_shared = shared_vh[:rank].T.contiguous() + residual = v - group_means[torch.as_tensor(world.employers, device=device)] + residual = residual - (residual @ q_shared) @ q_shared.T + _, independent_s, independent_vh = torch.linalg.svd(residual, full_matrices=False) + q_independent = independent_vh[:rank].T.contiguous() + valid = bool( + shared_s[rank - 1] > shared_s[0] * 1e-6 + and independent_s[rank - 1] > independent_s[0] * 1e-6 + ) + if not valid: + return None, {"available": False, "reason": "fewer than 32 nondegenerate directions"} + generator = torch.Generator(device=device).manual_seed(74) + q_random = torch.linalg.qr(torch.randn(v.shape[1], rank, generator=generator, device=device)).Q + bases, checks = {}, {} + for kind, q in (("shared", q_shared), ("independent", q_independent), ("random", q_random)): + projected = v @ q + mean, std = projected.mean(0), projected.std(0, correction=0) + std = std.clamp_min(0.01 * std.square().mean().sqrt()) + normalized = (projected - mean) / std + # Equal total variance across all branches (one, not dependent on their rank). + scale = std * normalized.square().sum(-1).mean().sqrt() + bases[kind] = (q, mean, scale) + normalized = (projected - mean) / scale + within = [] + for c in range(64): + mask = (world.employers == c) & ~world.exceptions + z = normalized[torch.as_tensor(mask, device=device)] + within.append((z - z.mean(0)).square().sum(-1).mean().item()) + checks[kind] = { + "same_company_relation_old_answer_identity_variance": float(np.mean(within)), + "total_variance": normalized.square().sum(-1).mean().item(), + } + if device.type == "cuda": + torch.cuda.synchronize(device) + return bases, { + "available": True, + "construction_seconds": time.perf_counter() - started, + "rank": rank, + "shared_32nd_relative_singular_value": (shared_s[rank - 1] / shared_s[0]).item(), + "independent_32nd_relative_singular_value": ( + independent_s[rank - 1] / independent_s[0] + ).item(), + "checks": checks, + } + + +def attach_branch(model, basis, layer=4, width=32): + branch = ResidualBranch(*basis, width=width) + model.add_module("edit_branch", branch) + + def save_position(_module, args): + branch.positions = args[0].eq(ANS).long().argmax(-1) + + def add(_module, _inputs, output): + rows = torch.arange(len(output), device=output.device) + result = output.clone() + result[rows, branch.positions] = result[rows, branch.positions] + branch( + output[rows, branch.positions] + ) + return result + + handles = [ + model.register_forward_pre_hook(save_position), + model.blocks[layer].register_forward_hook(add), + ] + return branch, handles + + +def remove_branch(model, handles): + for handle in handles: + handle.remove() + delattr(model, "edit_branch") diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_capacity.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_capacity.py new file mode 100644 index 0000000000000000000000000000000000000000..d07d84eb1c19bc5055e15255b0de00799b8713c5 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_capacity.py @@ -0,0 +1,48 @@ +"""Predeclared splits and query-level capacity diagnostics.""" + +import numpy as np + +from .bios_data import N_BASE, N_QUERIES, rng_for + + +def qa_split(world, mode): + if mode == "all": + return np.arange(N_BASE, N_QUERIES), np.array([], dtype=np.int64) + if mode != "half": + raise ValueError("Unknown QA split") + rng = rng_for(world.seed, 910) + train, heldout = [], [] + for company in np.unique(world.employers): + for exception in (False, True): + people = np.flatnonzero((world.employers == company) & (world.exceptions == exception)) + people = rng.permutation(people) + train.extend((N_BASE + people[: len(people) // 2]).tolist()) + heldout.extend((N_BASE + people[len(people) // 2 :]).tolist()) + return np.sort(train), np.sort(heldout) + + +def split_metrics(world, arrays, train_ids, heldout_ids): + correct, nll = arrays["correct"], arrays["value_nll"] + # The derivation needs the person's employer and that employer's default city. + # Build by semantic IDs rather than assuming a base-fact row layout. + employer = {int(world.person[i]): i for i in np.flatnonzero(world.relation == 0)} + defaults = {int(world.company[i]): i for i in np.flatnonzero(world.relation == 1)} + result = {} + for name, ids in (("trained", train_ids), ("heldout", heldout_ids)): + result[f"derived_{name}_count"] = len(ids) + result[f"derived_{name}_accuracy"] = float(correct[ids].mean()) if len(ids) else None + result[f"derived_{name}_nll"] = float(nll[ids].mean()) if len(ids) else None + eligible = np.array( + [ + i + for i in ids + if correct[employer[int(world.person[i])]] + and correct[defaults[int(world.company[i])]] + ], + dtype=np.int64, + ) + result[f"derived_{name}_known_components_count"] = len(eligible) + result[f"derived_{name}_known_components_accuracy"] = ( + float(correct[eligible].mean()) if len(eligible) else None + ) + return result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_causal_paths.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_causal_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2d8963ce2c5db80362fdd38cc80e83c8415b53 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_causal_paths.py @@ -0,0 +1,455 @@ +"""Offline donor-state interventions on frozen crossover models. + +Truth is used to match donor/recipient pairs and score outputs, never supplied as +an answer or bridge to the model. This is a causal diagnostic, not an editor. +""" + +import csv +import json +from pathlib import Path + +import numpy as np + +from .bios_cross import CHAINS, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_path_diagnostics import ( + INDISTINGUISHABLE, + classify_answers, + file_sha256, + free_generate_values, +) + +PAIR_TYPES = ( + "same_group_different_actual", + "different_group_same_actual_different_default", + "same_group_same_actual_different_person", + "different_group_different_actual_different_default", +) +POSITIONS = (2, 3, 4) +ANSWER_ROLES = ("recipient_default", "recipient_actual", "donor_default", "donor_actual") + + +def make_donor_plan(world, chain, per_population=64): + """Select using truth and train/heldout membership only, with fixed RNG. + + A missing donor stays -1. No prediction- or success-based replacement occurs. + The same world yields identical pairs across sizes, conditions and model seeds. + """ + heldout = world.person[world.heldout_ids[chain]] + train = world.person[world.train_ids[chain]] + rng = rng_for(world.seed, 971, chain) + recipients = [] + for exceptional in (False, True): + pool = heldout[world.exceptions[chain, heldout] == exceptional] + if len(pool) < per_population: + raise ValueError("Not enough heldout recipients for predeclared sample") + recipients.extend(rng.choice(pool, per_population, replace=False)) + recipients = np.asarray(recipients, dtype=np.int64) + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + recipient_rows, donor_rows, type_rows, candidate_counts = [], [], [], [] + for recipient in recipients: + same_group = group[train] == group[recipient] + same_actual = actual[train] == actual[recipient] + same_default = default[train] == default[recipient] + masks = ( + same_group & ~same_actual, + ~same_group & same_actual & ~same_default, + same_group & same_actual & (train != recipient), + ~same_group & ~same_actual & ~same_default, + ) + for pair_type, mask in enumerate(masks): + candidates = train[mask] + recipient_rows.append(recipient) + donor_rows.append(rng.choice(candidates) if len(candidates) else -1) + type_rows.append(pair_type) + candidate_counts.append(len(candidates)) + donor_rows = np.asarray(donor_rows, dtype=np.int64) + complete = (donor_rows.reshape(-1, len(PAIR_TYPES)) >= 0).all(axis=1) + return { + "case_id": np.arange(len(donor_rows), dtype=np.int64), + "recipient": np.asarray(recipient_rows, dtype=np.int64), + "donor": donor_rows, + "pair_type": np.asarray(type_rows, dtype=np.int8), + "candidate_count": np.asarray(candidate_counts, dtype=np.int32), + "common_recipient": np.repeat(complete, len(PAIR_TYPES)), + "recipient_old_exception": world.exceptions[chain, recipient_rows], + } + + +def intervention_state(recipient_state, donor_state, intervention, seed): + """Random control matches the donor-minus-recipient perturbation norm per row.""" + if recipient_state.shape != donor_state.shape: + raise ValueError("Activation shapes do not match") + delta = donor_state.astype(np.float64) - recipient_state.astype(np.float64) + norms = np.linalg.norm(delta, axis=-1) + if intervention == "donor": + patched = donor_state.copy() + elif intervention == "sham": + patched = recipient_state.copy() + elif intervention == "matched_random": + noise = np.random.default_rng(seed).standard_normal(delta.shape) + noise /= np.maximum(np.linalg.norm(noise, axis=-1, keepdims=True), 1e-30) + patched = (recipient_state + noise * norms[:, None]).astype(recipient_state.dtype) + else: + raise ValueError("Unknown intervention") + actual_norms = np.linalg.norm(patched.astype(np.float64) - recipient_state, axis=-1) + return patched, norms, actual_norms + + +def cache_clean_states(model, prompts, lengths, device, batch_size=256): + """Capture post-block residuals at fixed positions for clean prompt passes.""" + import torch + + from .bios_train import precision + + states = [[] for _ in model.blocks] + hooks = [] + for layer, block in enumerate(model.blocks): + + def capture(module, inputs, output, layer=layer): + states[layer].append(output[:, POSITIONS, :].detach().float().cpu().numpy()) + + hooks.append(block.register_forward_hook(capture)) + model.eval() + try: + with torch.no_grad(): + for start in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[start : start + batch_size], device=device) + n = torch.as_tensor(lengths[start : start + batch_size], device=device) + with precision(device): + model(p, (n - 1)[:, None]) + finally: + for hook in hooks: + hook.remove() + return np.stack([np.concatenate(layer_states) for layer_states in states]) + + +def generate_with_state_patch( + model, prompts, lengths, replacements, layer, position, device, batch_size=256 +): + """Apply the same pre-answer state patch in value and EOS generation passes. + + Positions <= 4 cannot depend on the generated token at position 5 under the + causal mask, so the clean prompt cache contains no teacher-forced answer. + """ + import torch + + from .bios_train import precision + + if position not in POSITIONS or np.any(lengths != 5): + raise ValueError("This diagnostic is restricted to five-token derived queries") + predictions, ended = [], [] + model.eval() + with torch.no_grad(): + for start in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[start : start + batch_size], device=device) + n = torch.as_tensor(lengths[start : start + batch_size], device=device) + replacement = torch.as_tensor(replacements[start : start + batch_size], device=device) + + def patch(module, inputs, output, replacement=replacement): + changed = output.clone() + changed[:, position] = replacement.to(output.dtype) + return changed + + hook = model.blocks[layer].register_forward_hook(patch) + try: + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), device=device, dtype=torch.long) + continuation[:, :5] = p + continuation[:, 5] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + finally: + hook.remove() + return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)} + + +def _candidate_values(world, chain, recipients, donors): + default = world.answers[world.root_ids[chain, world.memberships[chain]]] + actual = world.answers[world.actual_ids[chain]] + return np.column_stack( + [default[recipients], actual[recipients], default[donors], actual[donors]] + ) + + +def _node_rows(arrays, identity): + rows = [] + for pair_type, label in enumerate(PAIR_TYPES): + for population in ("all", "ordinary", "old_exception"): + for common_only in (False, True): + selected = arrays["pair_type"] == pair_type + if population != "all": + selected &= arrays["recipient_old_exception"] == (population == "old_exception") + if common_only: + selected &= arrays["common_recipient"] + n = int(selected.sum()) + before = arrays["baseline_correct"][selected] + after = arrays["correct"][selected] + row = { + **identity, + "pair_type": label, + "population": population, + "common_recipients_only": common_only, + "n": n, + "baseline_correct": int(before.sum()), + "correct": int(after.sum()), + "known_became_wrong": int((before & ~after).sum()), + "wrong_became_correct": int((~before & after).sum()), + "termination_error": int((~arrays["ended"][selected]).sum()), + "prediction_changed": int( + ( + arrays["prediction"][selected] + != arrays["baseline_prediction"][selected] + ).sum() + ), + "indistinguishable": int( + (arrays["class_code"][selected] == INDISTINGUISHABLE).sum() + ), + "mean_perturbation_norm": float(arrays["perturbation_norm"][selected].mean()) + if n + else None, + } + for i, role in enumerate(ANSWER_ROLES): + row[f"matches_{role}"] = int( + ( + ((arrays["matched_role_bits"][selected] & (1 << i)) != 0) + & arrays["ended"][selected] + ).sum() + ) + rows.append(row) + return rows + + +def diagnose_causal_run(run, output, step=15360, device="cuda", batch_size=256, per_population=64): + """One model, both relations, all layers/positions with fixed donor controls.""" + import torch + + from .bios_model import CausalLM, ModelConfig + from .bios_organization_train import atomic_numpy_save + + repository = Path(__file__).resolve().parents[2] + run, output = Path(run).resolve(), Path(output).resolve() + if output == run or run in output.parents: + raise ValueError("Never write causal diagnostics inside frozen training runs") + output.mkdir(parents=True, exist_ok=True) + config = json.loads((run / "config.json").read_text()) + if config["world"] not in (0, 1) or config["model"]["width"] not in (256, 768): + raise ValueError("This development diagnostic is frozen to worlds 0/1, widths 256/768") + checkpoint = run / f"model-{step}.pt" + device = torch.device(device) + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if array_hash(world.answers) != config["truth_sha256"]: + raise ValueError("World truth mismatch") + identity = { + "run": str(run), + "checkpoint": str(checkpoint), + "step": step, + "checkpoint_sha256": file_sha256(checkpoint), + "config_sha256": file_sha256(run / "config.json"), + "diagnostic_source_sha256": file_sha256(__file__), + "generation_helper_sha256": file_sha256( + repository / "src/llm_memory_editability/bios_path_diagnostics.py" + ), + "world": config["world"], + "seed": config["seed"], + "condition": config["condition"], + "width": config["model"]["width"], + "per_population": per_population, + "positions": list(POSITIONS), + "device_type": device.type, + "batch_size": batch_size, + "torch": torch.__version__, + "offline_truth_matching": True, + "role": "candidate_localization" if config["world"] == 0 else "development_replication", + } + config_path = output / "config.json" + if config_path.exists(): + if json.loads(config_path.read_text()) != identity: + raise ValueError("Causal diagnostic identity changed") + else: + write_json(config_path, identity) + if (output / "complete.json").exists(): + return + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + rows, plan_rows = [], [] + source_output_hashes = {} + for chain, name in enumerate(CHAINS): + dest = output / name + dest.mkdir(exist_ok=True) + plan = make_donor_plan(world, chain, per_population) + plan_path = dest / "plan.npz" + if plan_path.exists(): + with np.load(plan_path) as existing: + if any(not np.array_equal(existing[k], v) for k, v in plan.items()): + raise ValueError("Saved donor plan differs") + else: + atomic_numpy_save(plan_path, **plan) + source_output_hashes[str(plan_path.relative_to(output))] = file_sha256(plan_path) + valid = plan["donor"] >= 0 + selected = {k: v[valid] for k, v in plan.items()} + recipients, donors = selected["recipient"], selected["donor"] + for pair_type, label in enumerate(PAIR_TYPES): + for exceptional in (False, True): + matching = (plan["pair_type"] == pair_type) & ( + plan["recipient_old_exception"] == exceptional + ) + plan_rows.append( + { + "chain": name, + "pair_type": label, + "population": "old_exception" if exceptional else "ordinary", + "requested": int(matching.sum()), + "valid": int((matching & valid).sum()), + "missing": int((matching & ~valid).sum()), + } + ) + people = np.unique(np.concatenate([recipients, donors])) + ids = world.derived_ids[chain, people] + cache_path = dest / "clean-cache.npz" + if cache_path.exists(): + with np.load(cache_path) as cache: + states = cache["states"] + baseline = {k: cache[k] for k in ("prediction", "ended")} + if not np.array_equal(cache["people"], people): + raise ValueError("Clean cache people mismatch") + else: + states = cache_clean_states( + model, world.prompts[ids], world.lengths[ids], device, batch_size + ) + baseline = free_generate_values( + model, world.prompts[ids], world.lengths[ids], device, batch_size + ) + atomic_numpy_save(cache_path, people=people, states=states, **baseline) + source_output_hashes[str(cache_path.relative_to(output))] = file_sha256(cache_path) + ri, di = np.searchsorted(people, recipients), np.searchsorted(people, donors) + recipient_queries = world.derived_ids[chain, recipients] + candidates = _candidate_values(world, chain, recipients, donors) + base = { + **selected, + "recipient_query": recipient_queries, + "donor_query": world.derived_ids[chain, donors], + "candidate_tokens": candidates, + "baseline_prediction": baseline["prediction"][ri], + "baseline_ended": baseline["ended"][ri], + "baseline_correct": (baseline["prediction"][ri] == candidates[:, 0]) + & baseline["ended"][ri], + } + for layer in range(len(model.blocks)): + for position_index, position in enumerate(POSITIONS): + receiver_states = states[layer, ri, position_index] + donor_states = states[layer, di, position_index] + seed = [world.seed, 972, chain, layer, position] + for intervention in ("donor", "matched_random", "sham"): + node = dest / f"layer-{layer}-position-{position}-{intervention}.npz" + if node.exists(): + with np.load(node) as existing: + arrays = dict(existing) + if not np.array_equal(arrays["case_id"], selected["case_id"]): + raise ValueError("Saved node case mismatch") + else: + replacement, donor_norm, actual_norm = intervention_state( + receiver_states, donor_states, intervention, seed + ) + generated = generate_with_state_patch( + model, + world.prompts[recipient_queries], + world.lengths[recipient_queries], + replacement, + layer, + position, + device, + batch_size, + ) + classes, bits = classify_answers( + generated["prediction"], generated["ended"], candidates + ) + arrays = { + **base, + **generated, + "class_code": classes, + "matched_role_bits": bits, + "correct": (generated["prediction"] == candidates[:, 0]) + & generated["ended"], + "donor_delta_norm": donor_norm, + "perturbation_norm": actual_norm, + } + atomic_numpy_save(node, **arrays) + source_output_hashes[str(node.relative_to(output))] = file_sha256(node) + node_identity = { + "world": world.seed, + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "chain": name, + "layer": layer, + "position": position, + "intervention": intervention, + "terminal_control": layer == len(model.blocks) - 1, + } + rows.extend(_node_rows(arrays, node_identity)) + print( + json.dumps( + { + "event": "causal_node_complete", + "run": str(run), + "chain": name, + "layer": layer, + "position": position, + } + ), + flush=True, + ) + for filename, contents in (("summary.csv", rows), ("pair-coverage.csv", plan_rows)): + with (output / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + output / "schema.json", + { + "pair_types": PAIR_TYPES, + "answer_roles": ANSWER_ROLES, + "state": "post-transformer-block residual stream", + "positions": { + "2": "membership relation", + "3": "default relation", + "4": "answer marker", + }, + "world_roles": { + "0": "candidate localization", + "1": "development replication, not confirmation", + }, + "random_control": "Random vector matched per case to ||donor_state-recipient_state||_2", + "matching": "True group/actual/default answers select pairs offline; prompts contain " + "no true answer or true bridge entity.", + "missing": "No donor replacement across types; no prediction-based recipient selection", + "common_recipients": "Auxiliary rows require all four donor types; truth-selected", + "last_layer_controls": "Positions 2/3 cannot affect other tokens after final block; " + "position 4 directly changes value readout and is not routing evidence.", + "causal_scope": "Single-state replacement establishes an intervention effect, not a " + "unique mechanism or strict necessity. Same-point restoration equals sham.", + "eos": "Value and EOS are independently generated with identical intervention; " + "non-terminated values are failures even if an answer candidate matches.", + "overlap": "All matched roles retained; multiple roles remain indistinguishable", + }, + ) + write_json(output / "artifacts.json", source_output_hashes) + write_json( + output / "complete.json", + { + "complete": True, + "identity": identity, + "node_files": 2 * len(model.blocks) * len(POSITIONS) * 3, + "plan_rows": plan_rows, + "artifacts_sha256": file_sha256(output / "artifacts.json"), + }, + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_confirmation_stats.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_confirmation_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..27d0d82cc96b250b88771946b569218a090bee50 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_confirmation_stats.py @@ -0,0 +1,280 @@ +"""Locked world-level inference for the narrower shortcut confirmation. + +This module consumes independently audited endpoint counts, never query outcomes +for selecting hypotheses. Nested seeds, organizations, chains and supports are +averaged within a world before any inferential calculation. +""" + +import itertools +import math + +DEFAULT_STATISTICS = { + "revision": "shortcut-confirmation-statistics-v1", + "scope": "training-correlation behavioral confirmation, not organization-path mediation", + "worlds": list(range(100, 108)), + "seeds": [0, 1], + "conditions": ["company", "project", "neither"], + "chains": ["company", "project"], + "prevalences": ["low", "high"], + "supports": [0, 1], + "kinds": ["coherent", "exception"], + "width": 256, + "learning_step": 15360, + "editing_step": 512, + "learning_denominator": 64, + "editing_denominator": 9, + "primary_endpoint": "editing_exception_fixed9", + "confirmatory_family": [ + "editing_exception_fixed9", + "learning_original_exception", + "editing_coherent_fixed9", + ], + "contrast": "high-minus-low", + "unit": "world; all nested pairs equally weighted within each world", + "test": "two-sided one-sample t on eight world-level paired differences, df=7", + "assumption": "independent generated worlds; approximately normal world-level differences", + "multiplicity": "Holm across the three confirmatory endpoints, family alpha=0.05", + "intervals": ["95% marginal t", "98.33333333333333% Bonferroni simultaneous t"], + "sensitivity": "all 256 world sign flips; valid under null sign symmetry, not an " + "unconditional randomized-treatment test", + "zero_sd": "all-zero differences: t=0,p=1,CI=[0,0], degenerate/no equivalence; " + "constant nonzero differences: t/p/CI=null, Holm input=1, adjusted p=1", + "stopping": "fixed eight worlds; no interim outcome inspection or optional extension", + "publication": "all three endpoints, signs, all E/U/global-D/base checks published " + "regardless of significance; no automatic natural-language or editor-method trigger", +} + + +def _beta_fraction(a, b, x): + tiny, tolerance = 1e-300, 3e-14 + qab, qap, qam = a + b, a + 1, a - 1 + c, d = 1.0, 1.0 - qab * x / qap + d = 1 / (d if abs(d) >= tiny else tiny) + h = d + for m in range(1, 401): + double = 2 * m + aa = m * (b - m) * x / ((qam + double) * (a + double)) + d, c = 1 + aa * d, 1 + aa / c + d = 1 / (d if abs(d) >= tiny else tiny) + c = c if abs(c) >= tiny else tiny + h *= d * c + aa = -(a + m) * (qab + m) * x / ((a + double) * (qap + double)) + d, c = 1 + aa * d, 1 + aa / c + d = 1 / (d if abs(d) >= tiny else tiny) + c = c if abs(c) >= tiny else tiny + factor = d * c + h *= factor + if abs(factor - 1) <= tolerance: + return h + raise ArithmeticError("Incomplete beta continued fraction did not converge") + + +def regularized_beta(x, a, b): + if not (0 <= x <= 1 and a > 0 and b > 0): + raise ValueError("Invalid beta arguments") + if x in (0, 1): + return float(x) + scale = math.exp( + math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x) + ) + if x < (a + 1) / (a + b + 2): + result = scale * _beta_fraction(a, b, x) / a + else: + result = 1 - scale * _beta_fraction(b, a, 1 - x) / b + return min(1.0, max(0.0, result)) + + +def t_two_sided_p(statistic, degrees): + if degrees <= 0 or not math.isfinite(statistic): + raise ValueError("Finite t and positive degrees of freedom required") + return regularized_beta(degrees / (degrees + statistic**2), degrees / 2, 0.5) + + +def t_critical(alpha, degrees): + if not (0 < alpha < 1 and degrees > 0): + raise ValueError("Invalid t quantile arguments") + lower, upper = 0.0, 1.0 + while t_two_sided_p(upper, degrees) > alpha: + upper *= 2 + for _ in range(100): + middle = (lower + upper) / 2 + if t_two_sided_p(middle, degrees) > alpha: + lower = middle + else: + upper = middle + return (lower + upper) / 2 + + +def holm(p_values): + """Unavailable p-values conservatively occupy a place in the family as 1.""" + values = [1.0 if p is None else float(p) for p in p_values] + if any(not math.isfinite(p) or not 0 <= p <= 1 for p in values): + raise ValueError("p-values must be finite and in [0,1], or None") + order = sorted(range(len(values)), key=lambda i: (values[i], i)) + result, previous = [None] * len(values), 0.0 + for rank, index in enumerate(order): + previous = max(previous, min(1.0, (len(values) - rank) * values[index])) + result[index] = previous + return result + + +def sign_flip_sensitivity(values): + if len(values) != 8 or not all(math.isfinite(x) for x in values): + raise ValueError("Exactly eight finite world differences required") + observed = abs(math.fsum(values)) + tolerance = 1e-12 * max(1.0, math.fsum(abs(x) for x in values)) + extreme = sum( + abs(math.fsum(s * x for s, x in zip(signs, values, strict=True))) >= observed - tolerance + for signs in itertools.product((-1, 1), repeat=8) + ) + return {"p": extreme / 256, "extreme": extreme, "enumerated": 256} + + +def world_t_statistics(values): + values = [float(x) for x in values] + if len(values) != 8 or not all(math.isfinite(x) for x in values): + raise ValueError("Exactly eight finite world differences required") + mean = math.fsum(values) / 8 + variance = math.fsum((value - mean) ** 2 for value in values) / 7 + sd = math.sqrt(variance) + result = { + "worlds": 8, + "df": 7, + "mean": mean, + "sd": sd, + "sign_flip_sensitivity": sign_flip_sensitivity(values), + } + if max(values) == min(values): + zero = values[0] == 0 + result.update( + status="degenerate_zero" if zero else "degenerate_nonzero", + t=0.0 if zero else None, + p=1.0 if zero else None, + ci95=[0.0, 0.0] if zero else None, + ci_bonferroni=[0.0, 0.0] if zero else None, + ) + return result + standard_error = sd / math.sqrt(8) + statistic = mean / standard_error + result.update(status="estimable", t=statistic, p=t_two_sided_p(statistic, 7)) + for key, alpha in [("ci95", 0.05), ("ci_bonferroni", 0.05 / 3)]: + half = t_critical(alpha, 7) * standard_error + result[key] = [mean - half, mean + half] + return result + + +def _integer(value, label): + if isinstance(value, bool): + raise ValueError(f"Boolean integer for {label}") + parsed = int(value) + if isinstance(value, str) and str(parsed) != value: + raise ValueError(f"Noncanonical integer for {label}: {value!r}") + if not isinstance(value, str) and parsed != value: + raise ValueError(f"Noninteger value for {label}: {value!r}") + return parsed + + +def validate_endpoints(rows, editing=False): + keys = ["world", "seed", "condition", "chain", "prevalence"] + if editing: + keys += ["support", "kind"] + indexed = {} + for raw in rows: + row = dict(raw) + if not editing and "support" in row: + raise ValueError("Learning endpoints must not be repeated or labeled by support") + for name in ["world", "seed", "step", "n", "correct"] + (["support"] if editing else []): + row[name] = _integer(row[name], name) + if "width" in row and _integer(row["width"], "width") != 256: + raise ValueError("Unexpected model width") + if row["step"] != (512 if editing else 15360): + raise ValueError("Endpoint step differs from the fixed budget") + if row["n"] != (9 if editing else 64) or not 0 <= row["correct"] <= row["n"]: + raise ValueError("Fixed cohort count is invalid") + if not editing and (row["cohort"] != "original_exception" or row["split"] != "heldout"): + raise ValueError("Wrong learning cohort or split") + key = tuple(row[k] for k in keys) + if key in indexed: + raise ValueError(f"Duplicate endpoint: {key}") + indexed[key] = row + dimensions = [ + range(100, 108), + (0, 1), + ("company", "project", "neither"), + ("company", "project"), + ("low", "high"), + ] + if editing: + dimensions += [(0, 1), ("coherent", "exception")] + expected = set(itertools.product(*dimensions)) + if set(indexed) != expected: + raise ValueError( + f"Endpoint matrix mismatch: missing {len(expected - set(indexed))}, " + f"unexpected {len(set(indexed) - expected)}" + ) + return indexed + + +def analyze_endpoints(learning, editing): + learning = validate_endpoints(learning) + editing = validate_endpoints(editing, editing=True) + world_rows, case_rows = [], [] + for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: + kind = None if endpoint == "learning_original_exception" else endpoint.split("_")[1] + source, denominator = (learning, 64) if kind is None else (editing, 9) + for world in range(100, 108): + pairs = [] + for seed, condition, chain in itertools.product( + (0, 1), ("company", "project", "neither"), ("company", "project") + ): + for support in [None] if kind is None else (0, 1): + base = (world, seed, condition, chain) + suffix = () if kind is None else (support, kind) + low = source[(*base, "low", *suffix)] + high = source[(*base, "high", *suffix)] + row = { + "endpoint": endpoint, + "world": world, + "seed": seed, + "condition": condition, + "chain": chain, + "support": support, + "kind": kind, + "n": denominator, + "low_correct": low["correct"], + "high_correct": high["correct"], + "correct_difference": high["correct"] - low["correct"], + } + row["accuracy_difference"] = row["correct_difference"] / denominator + pairs.append(row) + case_rows.append(row) + n = len(pairs) * denominator + world_rows.append( + { + "endpoint": endpoint, + "world": world, + "paired_cases": len(pairs), + "nested_query_count_descriptive": n, + "low_accuracy": sum(r["low_correct"] for r in pairs) / n, + "high_accuracy": sum(r["high_correct"] for r in pairs) / n, + "difference": sum(r["correct_difference"] for r in pairs) / n, + } + ) + results = [] + for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: + values = [row["difference"] for row in world_rows if row["endpoint"] == endpoint] + results.append({"endpoint": endpoint, **world_t_statistics(values)}) + adjusted = holm([result["p"] for result in results]) + for result, value in zip(results, adjusted, strict=True): + result.update( + holm_input=1.0 if result["p"] is None else result["p"], + holm_adjusted_p=value, + reject_two_sided_family_05=result["p"] is not None and value <= 0.05, + ) + return { + "contract": DEFAULT_STATISTICS, + "results": results, + "world_effects": world_rows, + "paired_cases": case_rows, + "input_rows": {"learning": len(learning), "editing": len(editing)}, + } diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_context_control.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_context_control.py new file mode 100644 index 0000000000000000000000000000000000000000..26c20f349951ff08ba251e2e61c158ad8f4c0f85 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_context_control.py @@ -0,0 +1,250 @@ +"""Conditional P3 control: block cross-fact document attention during training. + +The frozen document tensors, absolute positions, loss masks, optimizer, QA stream, +and inference path are unchanged. Only document attention edges are removed. +This module is prepared for conditional execution; importing it does not train. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import time +from contextlib import contextmanager +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import bios_cross_train as frozen_trainer +from .bios_cross import CHAINS, CONDITIONS, audit, documents, make_cross_world, qa_schedule +from .bios_data import array_hash, write_json +from .bios_model import Attention, CausalLM +from .bios_organization_train import atomic_numpy_save +from .bios_path_diagnostics import autonomous_two_step + +RECORD_LENGTH = 6 +DOCUMENT_LENGTH = 60 +CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360) + + +def fact_causal_mask(length=DOCUMENT_LENGTH, record_length=RECORD_LENGTH, device=None): + """SDPA Boolean True means an allowed edge: same record and causal order.""" + if length <= 0 or record_length <= 0 or length % record_length: + raise ValueError("Document length must contain complete fact records") + position = torch.arange(length, device=device) + return (position[:, None] // record_length == position[None, :] // record_length) & ( + position[None, :] <= position[:, None] + ) + + +class FactIsolatedAttention(Attention): + """An existing Attention object's parameters are retained without reinitializing.""" + + def forward(self, x): + if not self.document_attention_isolated: + return super().forward(x) + batch, length, width = x.shape + if length != DOCUMENT_LENGTH: + raise ValueError("Document-only attention entered with a non-document tensor") + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=self.fact_mask, + is_causal=False, + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +class FactIsolatedCausalLM(CausalLM): + """Use the original initializer, forward, position IDs, and state-dict schema. + + In the frozen trainer the only 60-token training input is a document; QA + training inputs contain six tokens. Evaluation always uses the original + attention path, including an unusually long inference input. No dropout, + extra trainable parameter, random draw, or reset of position IDs is added. + """ + + def __init__(self, config): + super().__init__(config) + mask = fact_causal_mask() + for block in self.blocks: + attention = block.attention + attention.__class__ = FactIsolatedAttention + attention.document_attention_isolated = False + attention.register_buffer("fact_mask", mask, persistent=False) + + def forward(self, tokens, positions=None): + isolate = self.training and tokens.shape[1] == DOCUMENT_LENGTH + if self.training and tokens.shape[1] not in (RECORD_LENGTH, DOCUMENT_LENGTH): + raise ValueError("Unexpected training input length; document/QA dispatch is unsafe") + if isolate: + if positions is None or positions.shape[1] != 20: + raise ValueError("Document training must preserve all twenty supervised positions") + expected = torch.arange(DOCUMENT_LENGTH, device=tokens.device).view(10, 6)[:, 3:5] + if not torch.equal(positions, expected.reshape(1, 20).expand(len(tokens), -1)): + raise ValueError("Document supervision positions changed") + for block in self.blocks: + block.attention.document_attention_isolated = isolate + try: + return super().forward(tokens, positions) + finally: + for block in self.blocks: + block.attention.document_attention_isolated = False + + +@contextmanager +def isolated_model_factory(): + """Patch only this worker's factory while retaining the frozen trainer body.""" + original = frozen_trainer.CausalLM + if original is not CausalLM: + raise RuntimeError("The frozen trainer already has a modified model factory") + frozen_trainer.CausalLM = FactIsolatedCausalLM + try: + yield + finally: + frozen_trainer.CausalLM = original + + +def context_sources(): + directory = Path(__file__).parent + return { + **frozen_trainer.source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ("bios_context_control.py", "bios_path_diagnostics.py") + }, + } + + +def validate_study(study): + expected = { + "width": 256, + "layers": 8, + "heads": 4, + "steps": 15360, + "checkpoints": list(CHECKPOINTS), + "lr": 0.0001, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "learning_runs": 12, + "edit_cases": 0, + } + for key, value in expected.items(): + if study.get(key) != value: + raise ValueError(f"Context control changed its frozen study setting: {key}") + + +def run(args): + study = json.loads(Path(args.config).read_text()) + validate_study(study) + if args.world not in study["worlds"] or args.seed not in study["seeds"]: + raise ValueError("Context control is restricted to the development matrix") + output = Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + world = make_cross_world(args.world) + world_audit = audit(world) + docs, schedule = documents(world, args.condition), qa_schedule(world, study["steps"]) + contract = { + "protocol": "v2.8-p3-context-control", + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "study": study, + "sources": context_sources(), + "intervention": { + "training_document_attention": "causal within each six-token fact only", + "absolute_positions": "unchanged 0 through 59; never reset within facts", + "document_tokens_batches_and_supervision": "unchanged", + "QA_training_attention": "original causal attention", + "all_inference_attention": "original causal attention", + "mask_sha256": array_hash(fact_causal_mask().numpy()), + }, + "data": { + "truth_sha256": world_audit["truth_sha256"], + "prompts_sha256": world_audit["prompts_sha256"], + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + }, + "environment": { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + } + path = output / "launch-contract.json" + if path.exists(): + old = json.loads(path.read_text()) + for key in contract.keys() - {"environment"}: + if old[key] != contract[key]: + raise ValueError(f"Context control contract changed: {key}") + else: + write_json(path, contract) + if (output / "complete.json").exists(): + return + torch.set_num_threads(args.threads) + device = torch.device(args.device) + controlled_study = { + **study, + "context_contract": contract["sources"], + "context_intervention": contract["intervention"], + } + try: + with isolated_model_factory(): + model, _ = frozen_trainer.learning(args, world, output, controlled_study, device) + # Inference must be the original unrestricted forward path. + model.eval() + with np.load(output / f"predictions-{study['steps']}.npz") as saved: + direct = {key: saved[key] for key in ("prediction", "ended", "correct")} + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) + atomic_numpy_save(output / f"two-step-{name}.npz", **arrays) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": "P3-context-control-learning-only", + "learning_steps": study["steps"], + "edit_cases": 0, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + { + "type": type(error).__name__, + "message": str(error), + "time": time.time(), + }, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True, type=int) + parser.add_argument("--seed", required=True, type=int) + parser.add_argument("--condition", required=True, choices=CONDITIONS) + parser.add_argument("--config", default="configs/bios-context-control-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_context_gradient.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_context_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..89f78f244a71569026fd75d76ac6b10b702fed9d --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_context_gradient.py @@ -0,0 +1,669 @@ +"""Prospectively frozen context-statistic prediction of common-state gradients. + +The predictor contracts supervised target/context co-occurrences with fixed +embeddings and first-layer value weights. It uses neither real gradients nor +contextual activations, and has no fitted scale. It is a new residual-path +approximation, not a theorem for the project's Transformer or AdamW updates. +""" + +import argparse +import hashlib +import itertools +import json +import platform +import time +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path +from types import MethodType + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CONDITIONS, + documents, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_cross_train import tensor_queries +from .bios_data import array_hash, write_json +from .bios_model import CausalLM, ModelConfig + +TARGET = "blocks.0.attention.proj.weight" +CONTRASTS = (("company", "neither"), ("project", "neither"), ("company", "project")) + + +def sha(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def stamp(): + return datetime.now(timezone.utc).isoformat() + + +def allowed_mask(length, isolated, device=None): + pos = torch.arange(length, device=device) + mask = pos[None, :] <= pos[:, None] + if isolated: + mask &= pos[None, :] // 6 == pos[:, None] // 6 + return mask + + +def _isolated_forward(self, x): + batch, length, width = x.shape + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=allowed_mask(length, True, x.device), + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +@contextmanager +def attention_mode(model, isolated): + originals = [] + if isolated: + for block in model.blocks: + attention = block.attention + originals.append((attention, attention.forward)) + attention.forward = MethodType(_isolated_forward, attention) + try: + yield + finally: + for attention, forward in originals: + attention.forward = forward + + +def ln_vjp(x, upstream, layer): + """Exact input VJP of LayerNorm, without reading a real model gradient.""" + centered = x - x.mean(-1, keepdim=True) + inverse = torch.rsqrt(centered.square().mean(-1, keepdim=True) + layer.eps) + normalized = centered * inverse + affine = upstream * layer.weight + return inverse * ( + affine + - affine.mean(-1, keepdim=True) + - normalized * (affine * normalized).mean(-1, keepdim=True) + ) + + +@torch.no_grad() +def statistic_predictors(model, tokens, positions, labels, shuffled, isolated): + """Gradients of a zero-residual baseline plus one infinitesimal OV branch. + + x_j = E[token_j] + P[j] (or E[token_j] for the token-only control). + m_t = average_{j allowed at t} (Wv LN1(x_j) + bv). + epsilon_t = J_LNfinal(x_t)^T E^T (softmax(E LNfinal(x_t)) - onehot(y_t)). + Ghat = mean_t epsilon_t m_t^T. This is a contraction of position/mask + weighted token-target counts; all other residual branches are omitted. + The answer and EOS means returned here are separately normalized. + """ + width = model.config.width + result = {} + for position_aware in (True, False): + x = model.token(tokens) + if position_aware: + x = x + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + value = F.linear( + model.blocks[0].ln1(x), + model.blocks[0].attention.qkv.weight[2 * width :], + model.blocks[0].attention.qkv.bias[2 * width :], + ) + mask = allowed_mask(tokens.shape[1], isolated, tokens.device).to(x.dtype) + mask /= mask.sum(-1, keepdim=True) + mean_value = (mask @ value)[:, positions] + query = x[:, positions] + probability = F.linear(model.ln_final(query), model.token.weight).softmax(-1) + expected = probability @ model.token.weight + variants = ( + (("position", labels), ("shuffled", shuffled)) + if position_aware + else (("token", labels),) + ) + for name, targets in variants: + epsilon = ln_vjp(query, expected - model.token(targets), model.ln_final) + for offset, kind in enumerate(("answer", "eos")): + left, right = epsilon[:, offset::2], mean_value[:, offset::2] + result[f"{name}/{kind}"] = torch.einsum("btd,bte->de", left, right) / ( + left.shape[0] * left.shape[1] + ) + return result + + +def vector_metrics(actual, predicted): + actual = np.asarray(actual, dtype=np.float64).ravel() + predicted = np.asarray(predicted, dtype=np.float64).ravel() + an, pn = np.linalg.norm(actual), np.linalg.norm(predicted) + return { + "actual_norm": float(an), + "predicted_norm": float(pn), + "cosine": float(np.dot(actual, predicted) / (an * pn)) if an and pn else None, + "relative_error": float(np.linalg.norm(actual - predicted) / an) if an else None, + "norm_ratio": float(pn / an) if an else None, + } + + +def module_name(name): + if name.startswith("blocks."): + parts = name.split(".") + if parts[2] == "attention" and parts[3] == "qkv": + return ".".join(parts[:4]) + return ".".join(parts[:3]) + return name.split(".")[0] + + +def module_differences(first, second): + sums = {} + for name in first: + # The concatenated qkv parameter is additionally split by role. + pieces = [(module_name(name), first[name], second[name])] + if ".attention.qkv." in name: + pieces = [ + (name.split(".qkv.")[0] + "." + role, a, b) + for role, a, b in zip( + ("query", "key", "value"), + np.split(first[name], 3), + np.split(second[name], 3), + strict=True, + ) + ] + for group, left, right in pieces: + values = sums.setdefault(group, np.zeros(3, dtype=np.float64)) + left, right = left.astype(np.float64), right.astype(np.float64) + values += (np.sum((left - right) ** 2), np.sum(left**2), np.sum(right**2)) + return { + group: { + "difference_norm": float(np.sqrt(value[0])), + "relative_to_mean_arm_norm": float( + np.sqrt(value[0]) / ((np.sqrt(value[1]) + np.sqrt(value[2])) / 2) + ) + if value[1] + value[2] + else None, + } + for group, value in sums.items() + } + + +def source_files(root, config): + names = [ + "bios_context_gradient.py", + "bios_cross.py", + "bios_cross_train.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_organization.py", + ] + paths = [root / "src/llm_memory_editability" / name for name in names] + paths += [ + root / "scripts/run_bios_context_gradient.py", + root / "tests/test_bios_context_gradient.py", + ] + paths += [root / "configs/bios-context-gradient-v1.json"] + for world in config["worlds"]: + paths += [ + root / config["source_world_root"] / f"world-{world}" / name + for name in ("world.npz", "metadata.json", "audit.json") + ] + return paths + + +def freeze(root, config): + out = root / config["artifacts"] + lockpath = out / "preregistration-lock.json" + if lockpath.exists(): + raise FileExistsError("An existing prospective lock must not be replaced") + protocol = (root / "docs/experimental-protocol.md").read_text().split("## 16. ", 1)[1] + out.mkdir(parents=True, exist_ok=True) + (out / "preregistration.md").write_text("## 16. " + protocol) + sources = {} + for path in source_files(root, config): + relative = path.relative_to(root) + sources[str(relative)] = sha(path) + # Data stay in their original location, hash-bound by the lock. + if relative.parts[0] != "data": + copy = out / "frozen-files" / relative + copy.parent.mkdir(parents=True, exist_ok=True) + copy.write_bytes(path.read_bytes()) + write_json( + lockpath, + { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(out / "preregistration.md"), + "torch": torch.__version__, + "numpy": np.__version__, + "python": platform.python_version(), + }, + ) + return {"lock": str(lockpath), "sha256": sha(lockpath)} + + +def verify_lock(root, config): + lockpath = root / config["artifacts"] / "preregistration-lock.json" + lock = json.loads(lockpath.read_text()) + if lock["config"] != config: + raise ValueError("Configuration differs from prospective lock") + for path, expected in lock["sources"].items(): + if sha(root / path) != expected: + raise ValueError("Frozen source changed: " + path) + if sha(root / config["artifacts"] / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Prospective protocol changed") + return sha(lockpath) + + +def context_audit(world, config): + """Exact exposure/bigram audit plus a centered city-by-person Phi subblock.""" + people = [i for i, label in enumerate(world.token_labels) if label.startswith("person:")] + cities = np.unique(world.city_tokens) + pi, ci = np.full(world.vocab_size, -1), np.full(world.vocab_size, -1) + pi[people], ci[cities] = np.arange(len(people)), np.arange(len(cities)) + histograms, contexts, receipts = {}, {}, {} + for condition in CONDITIONS: + docs = documents(world, condition) + receipts[condition] = {"documents_sha256": array_hash(docs)} + counts = np.bincount(docs.ravel(), minlength=world.n_base) + receipts[condition]["exposure_sha256"] = array_hash(counts) + for isolated in (False, True): + joint = np.zeros((len(cities), len(people))) + marginal = np.zeros(len(people)) + bigrams = np.zeros((2, world.vocab_size), dtype=np.int64) + for epoch in range(config["rotations"]): + batch = render(world, epoch_documents(docs, world.seed, epoch)) + for col, pos in enumerate(batch["positions"][0]): + targets = batch["labels"][:, col] + # All answer predictors use ANS; EOS predictors use answer tokens. + values = targets if col % 2 == 0 else batch["tokens"][:, pos] + bigrams[col % 2] += np.bincount(values, minlength=world.vocab_size) + left = int(pos) // 6 * 6 if isolated else 0 + weight = 1 / (int(pos) - left + 1) + rows = ci[targets] + for prefix in range(left, int(pos) + 1): + columns = pi[batch["tokens"][:, prefix]] + valid = columns >= 0 + np.add.at(marginal, columns[valid], weight) + valid &= rows >= 0 + np.add.at(joint, (rows[valid], columns[valid]), weight) + contexts[condition, isolated] = (joint - marginal[None] / world.vocab_size) / ( + config["rotations"] * len(docs) * 20 + ) + histograms[condition] = bigrams + result = {"receipts": receipts, "comparisons": []} + for a, b in CONTRASTS: + equal = np.array_equal(histograms[a], histograms[b]) + if not equal or receipts[a]["exposure_sha256"] != receipts[b]["exposure_sha256"]: + raise ValueError("Organization exposure or supervised bigrams differ") + for isolated in (False, True): + first, second = contexts[a, isolated], contexts[b, isolated] + difference = np.max(np.abs(first - second)) + if isolated and difference > 1e-14: + raise ValueError("Isolated context statistics differ") + result["comparisons"].append( + { + "first": a, + "second": b, + "isolated": isolated, + "supervised_bigram_equal": equal, + "context_max_abs_difference": float(difference), + "context_relative_difference": float( + np.linalg.norm(first - second) / np.linalg.norm(second) + ), + } + ) + result["bigram_sha256"] = array_hash(histograms["neither"]) + result["qa_ids_sha256"] = array_hash(world.train_ids) + return result + + +def numpy_gradients(accumulators): + return {name: value.cpu().numpy().astype(np.float32) for name, value in accumulators.items()} + + +def measure_arm(model, world, condition, isolated, config, device, out): + docs = documents(world, condition) + named = dict(model.named_parameters()) + params = tuple(named.values()) + accumulators = { + kind: {name: torch.zeros_like(value, dtype=torch.float64) for name, value in named.items()} + for kind in ("answer", "eos") + } + predictions = { + f"{predictor}/{kind}": torch.zeros( + (model.config.width, model.config.width), dtype=torch.float64, device=device + ) + for predictor in config["predictors"] + for kind in ("answer", "eos") + } + losses = {"answer": 0.0, "eos": 0.0} + total_documents = len(docs) * config["rotations"] + started = time.perf_counter() + model.eval() + with attention_mode(model, isolated): + for epoch in range(config["rotations"]): + batch = render(world, epoch_documents(docs, world.seed, epoch)) + shuffled = batch["labels"].copy() + rng = np.random.default_rng( + np.random.SeedSequence([config["shuffle_seed"], world.seed, epoch]) + ) + # Each column is one relation at one absolute position. Marginals + # are exactly preserved, with the same permutations in every arm. + for col in range(shuffled.shape[1]): + shuffled[:, col] = shuffled[rng.permutation(len(docs)), col] + for begin in range(0, len(docs), config["measurement_batch"]): + end = min(begin + config["measurement_batch"], len(docs)) + tokens = torch.as_tensor(batch["tokens"][begin:end], device=device) + labels = torch.as_tensor(batch["labels"][begin:end], device=device) + positions = torch.as_tensor(batch["positions"][0], device=device) + shuffled_batch = torch.as_tensor(shuffled[begin:end], device=device) + weight = config["document_weight"] * 0.5 * (end - begin) / total_documents + predictors = statistic_predictors( + model, tokens, positions, labels, shuffled_batch, isolated + ) + for name, prediction in predictors.items(): + predictions[name].add_(prediction.double(), alpha=weight) + logits = model(tokens, positions[None].expand(len(tokens), -1)) + for offset, kind in enumerate(("answer", "eos")): + loss = F.cross_entropy( + logits[:, offset::2].flatten(0, 1), labels[:, offset::2].flatten() + ) + gradients = torch.autograd.grad(loss, params, retain_graph=offset == 0) + for name, gradient in zip(named, gradients, strict=True): + accumulators[kind][name].add_(gradient.double(), alpha=weight) + losses[kind] += float(loss.detach()) * (end - begin) / total_documents + print( + json.dumps({"event": "rotation", "arm": out.name, "rotation": epoch + 1}), + flush=True, + ) + result = {kind: numpy_gradients(accumulators[kind]) for kind in accumulators} + result["predictions"] = numpy_gradients(predictions) + out.mkdir(parents=True, exist_ok=False) + np.savez(out / "answer.npz", **result["answer"]) + np.savez(out / "eos.npz", **result["eos"]) + np.savez(out / "predictions.npz", **result["predictions"]) + metadata = { + "condition": condition, + "isolated": isolated, + "documents": total_documents, + "supervised_tokens": total_documents * 20, + "losses": losses, + "seconds": time.perf_counter() - started, + "files": {name: sha(out / name) for name in ("answer.npz", "eos.npz", "predictions.npz")}, + } + if any(not np.isfinite(value).all() for part in result.values() for value in part.values()): + raise FloatingPointError("Nonfinite gradients or predictions") + write_json(out / "receipt.json", metadata) + return result + + +def arm_data(path): + return { + kind: dict(np.load(path / f"{filename}.npz")) + for kind, filename in (("answer", "answer"), ("eos", "eos"), ("predictions", "predictions")) + } + + +def common_training_step(model, optimizer, world, config, step, device, schedule, data): + epoch, offset = divmod(step, 128) + arranged = epoch_documents(documents(world, "neither"), world.seed, epoch) + batch = render(world, arranged[offset * 16 : (offset + 1) * 16]) + tokens = torch.as_tensor(batch["tokens"], device=device) + positions = torch.as_tensor(batch["positions"], device=device) + labels = torch.as_tensor(batch["labels"], device=device) + qa = torch.as_tensor(schedule[step], device=device) + model.train() + optimizer.zero_grad(set_to_none=True) + for group in optimizer.param_groups: + group["lr"] = config["lr"] * min((epoch + 1) / config["warmup_epochs"], 1) + loss = F.cross_entropy(model(tokens, positions).flatten(0, 1), labels.flatten()) + (config["document_weight"] * loss).backward() + qa_loss = F.cross_entropy( + model(data["tokens"][qa], data["positions"][qa]).flatten(0, 1), data["labels"][qa].flatten() + ) + (config["qa_weight"] * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config["clip_norm"]) + if not torch.isfinite(loss + qa_loss + norm): + raise FloatingPointError("Nonfinite common training step") + optimizer.step() + return { + "step": step + 1, + "document_loss": float(loss.detach()), + "qa_loss": float(qa_loss.detach()), + } + + +def run(root, config, world_seed, seed, device): + lock_hash = verify_lock(root, config) + if world_seed not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("World/initialization is outside the frozen matrix") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.manual_seed(seed) + world = make_cross_world(world_seed, root / config["source_world_root"]) + out = root / config["output"] / f"world-{world_seed}-seed-{seed}" + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + raise FileExistsError("Completed run cannot be overwritten") + audit_path = out / "data-audit.json" + if not audit_path.exists(): + write_json(audit_path, context_audit(world, config)) + model = CausalLM( + ModelConfig( + world.vocab_size, config["width"], config["layers"], config["heads"], config["context"] + ) + ).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), + lr=config["lr"], + weight_decay=config["weight_decay"], + fused=device.type == "cuda", + ) + schedule = qa_schedule(world, max(config["states"])) + data = tensor_queries(world, device) + trajectory = [] + write_json( + out / "identity.json", + { + "world": world_seed, + "seed": seed, + "lock_sha256": lock_hash, + "created_at": stamp(), + "model": model.config_dict(), + "parameters": sum(p.numel() for p in model.parameters()), + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "torch": torch.__version__, + "numpy": np.__version__, + "qa_schedule_sha256": array_hash(schedule), + }, + ) + for step in range(max(config["states"]) + 1): + if step in config["states"]: + state_path = out / f"state-{step}.pt" + if state_path.exists(): + # Resumption reconstructs the exact common trajectory and verifies + # weights before using any existing diagnostic artifacts. + saved = torch.load(state_path, map_location=device, weights_only=False) + if any( + not torch.equal(v, saved["model"][k]) for k, v in model.state_dict().items() + ): + raise ValueError("Reconstructed reference weights differ") + else: + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "config": model.config_dict(), + }, + state_path, + ) + for mask in config["masks"]: + for condition in config["conditions"]: + path = out / f"step-{step}-{mask}-{condition}" + if (path / "receipt.json").exists(): + receipt = json.loads((path / "receipt.json").read_text()) + if any( + sha(path / name) != digest for name, digest in receipt["files"].items() + ): + raise ValueError("Existing gradient artifact hash mismatch") + continue + if path.exists(): + raise FileExistsError("Incomplete output must be retained and audited") + print( + json.dumps( + { + "event": "arm_start", + "world": world_seed, + "seed": seed, + "step": step, + "mask": mask, + "condition": condition, + } + ), + flush=True, + ) + measure_arm(model, world, condition, mask == "isolated", config, device, path) + write_json(out / "trajectory.json", trajectory) + if step < max(config["states"]): + trajectory.append( + common_training_step(model, optimizer, world, config, step, device, schedule, data) + ) + verify_lock(root, config) + files = {str(path.relative_to(out)): sha(path) for path in out.rglob("*") if path.is_file()} + write_json( + out / "complete.json", {"completed_at": stamp(), "lock_sha256": lock_hash, "files": files} + ) + + +def summarize(root, config): + verify_lock(root, config) + rows, modules, checks = [], [], [] + for world_seed, seed in itertools.product(config["worlds"], config["seeds"]): + runpath = root / config["output"] / f"world-{world_seed}-seed-{seed}" + completion = json.loads((runpath / "complete.json").read_text()) + for name, digest in completion["files"].items(): + if sha(runpath / name) != digest: + raise ValueError("Completed run artifact changed: " + name) + for step, mask in itertools.product(config["states"], config["masks"]): + arms = {c: arm_data(runpath / f"step-{step}-{mask}-{c}") for c in CONDITIONS} + for a, b in CONTRASTS: + identity = { + "world": world_seed, + "seed": seed, + "step": step, + "mask": mask, + "first": a, + "second": b, + } + for kind in ("answer", "eos", "combined"): + kinds = ("answer", "eos") if kind == "combined" else (kind,) + ga = {n: sum(arms[a][k][n] for k in kinds) for n in arms[a]["answer"]} + gb = {n: sum(arms[b][k][n] for k in kinds) for n in arms[b]["answer"]} + modules.append( + {**identity, "kind": kind, "modules": module_differences(ga, gb)} + ) + for predictor in config["predictors"]: + pred = sum( + arms[a]["predictions"][f"{predictor}/{k}"] + - arms[b]["predictions"][f"{predictor}/{k}"] + for k in kinds + ) + row = { + **identity, + "kind": kind, + "predictor": predictor, + **vector_metrics(ga[TARGET] - gb[TARGET], pred), + } + # Near-zero isolated contrasts are cancellation controls; + # cosine between rounding residues has no scientific meaning. + if mask == "isolated": + row["cosine"] = None + rows.append(row) + norm = np.linalg.norm(ga[TARGET] - gb[TARGET]) + reference = (np.linalg.norm(ga[TARGET]) + np.linalg.norm(gb[TARGET])) / 2 + if mask == "isolated": + checks.append( + { + **identity, + "kind": kind, + "relative_cancellation_residue": float(norm / reference), + } + ) + if any(c["relative_cancellation_residue"] > 1e-4 for c in checks): + raise ValueError("Isolated common-state gradient cancellation failed") + out = root / config["artifacts"] + write_json(out / "metrics.json", rows) + write_json(out / "module-metrics.json", modules) + write_json( + out / "audit.json", + {"passed": True, "runs": 4, "arms": 72, "isolated_checks": checks, "completed_at": stamp()}, + ) + primary = [ + r + for r in rows + if r["step"] == 0 + and r["mask"] == "open" + and r["kind"] == "answer" + and r["second"] == "neither" + ] + lines = [ + "# Context statistics and common-state gradients", + "", + "Descriptive development experiment; no fitted scale or significance tests.", + "", + "| World | Seed | Contrast | Predictor | Cosine | Relative error | Norm ratio |", + "| --- | --- | --- | --- | ---: | ---: | ---: |", + ] + for row in primary: + lines.append( + f"| {row['world']} | {row['seed']} | {row['first']}−{row['second']} | " + f"{row['predictor']} | {row['cosine']:.6f} | {row['relative_error']:.6f} | " + f"{row['norm_ratio']:.6f} |" + ) + (out / "report.md").write_text("\n".join(lines) + "\n") + print( + json.dumps( + { + "report": str(out / "report.md"), + "rows": len(rows), + "max_isolated_residue": max(c["relative_cancellation_residue"] for c in checks), + } + ) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=("freeze", "run", "summarize")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument( + "--config", type=Path, default=Path("configs/bios-context-gradient-v1.json") + ) + args = parser.parse_args() + root = Path(__file__).resolve().parents[2] + config = json.loads((root / args.config).read_text()) + if args.mode == "freeze": + print(json.dumps(freeze(root, config))) + elif args.mode == "run": + run(root, config, args.world, args.seed, torch.device(args.device)) + else: + summarize(root, config) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_cross.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..960ef7e03dd29b834df68149d8aca7cbcd077a10 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_cross.py @@ -0,0 +1,330 @@ +"""Two-chain organization crossover: shared facts, symmetric relational tasks. + +This is a new development world, not an alteration of the archived A/B/C runs. +Company and project each have 64 groups of 32 people and two old exceptions. +""" + +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +from .bios_data import ANS, BOS, EOS, N_BASE, N_PEOPLE, array_hash, load_world, rng_for, write_json + +CONDITIONS = ("company", "project", "neither") +CHAINS = ("company", "project") +SLOTS = 10 + + +@dataclass +class CrossWorld: + seed: int + prompts: np.ndarray + lengths: np.ndarray + answers: np.ndarray + relation: np.ndarray + person: np.ndarray + memberships: np.ndarray + defaults: np.ndarray + exceptions: np.ndarray + membership_ids: np.ndarray + root_ids: np.ndarray + actual_ids: np.ndarray + derived_ids: np.ndarray + train_ids: np.ndarray + heldout_ids: np.ndarray + city_tokens: np.ndarray + token_labels: list + n_base: int + + @property + def vocab_size(self): + return len(self.token_labels) + + +def make_cross_world(seed, source_root="data/bios-organization-v1"): + old = load_world(Path(source_root) / f"world-{seed}") + labels = ( + old.token_labels + + [f"project:{i}" for i in range(64)] + + ["relation:project", "relation:project_default", "relation:project_actual"] + ) + token = {name: i for i, name in enumerate(labels)} + rng = rng_for(seed, 901) + memberships = np.stack([old.employers, rng.permutation(np.repeat(np.arange(64), 32))]) + defaults = np.stack([old.defaults, rng.permutation(old.defaults)]) + exceptions = np.stack([old.exceptions, np.zeros(N_PEOPLE, dtype=bool)]) + actual = defaults[1, memberships[1]].copy() + for group in range(64): + people = rng.choice(np.flatnonzero(memberships[1] == group), 2, replace=False) + exceptions[1, people] = True + choices = np.unique(defaults[1][defaults[1] != defaults[1, group]]) + actual[people] = rng.choice(choices, 2) + n_base = N_BASE + 2 * N_PEOPLE + 64 + size = n_base + 2 * N_PEOPLE + prompts = np.zeros((size, 5), dtype=np.int64) + answers = np.zeros(size, dtype=np.int64) + lengths = np.full(size, 4, dtype=np.int64) + relation = np.zeros(size, dtype=np.int64) + person = np.full(size, -1, dtype=np.int64) + prompts[:N_BASE], answers[:N_BASE] = old.prompts[:N_BASE], old.answers[:N_BASE] + relation[:N_BASE], person[:N_BASE] = old.relation[:N_BASE], old.person[:N_BASE] + membership_ids = np.stack([np.arange(N_PEOPLE), N_BASE + np.arange(N_PEOPLE)]) + root_ids = np.stack([N_PEOPLE + np.arange(64), N_BASE + N_PEOPLE + np.arange(64)]) + actual_ids = np.stack( + [N_PEOPLE + 64 + np.arange(N_PEOPLE), N_BASE + N_PEOPLE + 64 + np.arange(N_PEOPLE)] + ) + person_tokens = np.array([token[f"person:{i}"] for i in range(N_PEOPLE)]) + new_values = [ + np.array([token[f"project:{i}"] for i in memberships[1]]), + old.city_tokens[defaults[1]], + old.city_tokens[actual], + ] + for rel, ids, values in zip( + (7, 8, 9), (membership_ids[1], root_ids[1], actual_ids[1]), new_values, strict=True + ): + subjects = ( + np.array([token[f"project:{i}"] for i in range(64)]) if rel == 8 else person_tokens + ) + rtoken = token[ + ("relation:project", "relation:project_default", "relation:project_actual")[rel - 7] + ] + prompts[ids, :4] = np.column_stack( + [np.full(len(ids), BOS), subjects, np.full(len(ids), rtoken), np.full(len(ids), ANS)] + ) + answers[ids], relation[ids] = values, rel + if rel != 8: + person[ids] = np.arange(N_PEOPLE) + derived_ids = n_base + np.arange(2 * N_PEOPLE).reshape(2, N_PEOPLE) + trained, heldout = [], [] + for chain in range(2): + ids = derived_ids[chain] + prompts[ids] = np.column_stack( + [ + np.full(N_PEOPLE, BOS), + person_tokens, + np.full(N_PEOPLE, token["relation:employer" if chain == 0 else "relation:project"]), + np.full( + N_PEOPLE, + token["relation:default_city" if chain == 0 else "relation:project_default"], + ), + np.full(N_PEOPLE, ANS), + ] + ) + answers[ids] = old.city_tokens[defaults[chain, memberships[chain]]] + lengths[ids], relation[ids], person[ids] = 5, 10 + chain, np.arange(N_PEOPLE) + split_rng = rng_for(seed, 902, chain) + included = [] + for group in range(64): + for exception in (False, True): + candidates = np.flatnonzero( + (memberships[chain] == group) & (exceptions[chain] == exception) + ) + included.extend(split_rng.permutation(candidates)[: len(candidates) // 2]) + trained.append(np.sort(ids[included])) + heldout.append(np.setdiff1d(ids, trained[-1])) + # Randomize the complete vocabulary, so appended token numbers carry no task order. + permutation = np.arange(len(labels)) + permutation[4:] = rng_for(seed, 903).permutation(permutation[4:]) + new_labels = [""] * len(labels) + for index, label in enumerate(labels): + new_labels[permutation[index]] = label + return CrossWorld( + seed, + permutation[prompts], + lengths, + permutation[answers], + relation, + person, + memberships, + defaults, + exceptions, + membership_ids, + root_ids, + actual_ids, + derived_ids, + np.stack(trained), + np.stack(heldout), + permutation[old.city_tokens], + new_labels, + n_base, + ) + + +def documents(world, condition): + if condition not in CONDITIONS: + raise ValueError("Unknown crossover condition") + docs = np.empty((N_PEOPLE, SLOTS), dtype=np.int64) + for rel in range(SLOTS): + if rel in (1, 8): + continue + ids = np.flatnonzero(world.relation[: world.n_base] == rel) + docs[world.person[ids], rel] = ids + for chain, slot in enumerate((1, 8)): + membership = world.memberships[chain] + group = membership.copy() + if condition != CHAINS[chain]: + rng = rng_for(world.seed, 904, chain) + members = np.stack( + [rng.permutation(np.flatnonzero(membership == g)) for g in range(64)] + ) + for lane in range(32): + cycle = rng.permutation(64) + group[members[cycle, lane]] = np.roll(cycle, -1) + docs[:, slot] = world.root_ids[chain, group] + return docs + + +def epoch_documents(docs, seed, epoch): + rows = rng_for(seed, 905, epoch).permutation(N_PEOPLE) + return np.roll(docs[rows], epoch % SLOTS, axis=1) + + +def render(world, ids): + tokens = np.empty((*ids.shape, 6), dtype=np.int64) + tokens[:, :, :4] = world.prompts[ids, :4] + tokens[:, :, 4], tokens[:, :, 5] = world.answers[ids], EOS + positions = (np.arange(SLOTS)[:, None] * 6 + np.array([3, 4])).ravel() + labels = np.stack([world.answers[ids], np.full_like(ids, EOS)], axis=-1) + return { + "tokens": tokens.reshape(len(ids), SLOTS * 6), + "positions": np.broadcast_to(positions, (len(ids), SLOTS * 2)).copy(), + "labels": labels.reshape(len(ids), SLOTS * 2), + } + + +def qa_schedule(world, steps): + streams = [] + for chain in range(2): + rng = rng_for(world.seed, 906, chain) + pool = world.train_ids[chain] + streams.append( + np.concatenate( + [rng.permutation(pool) for _ in range((steps * 20 + len(pool) - 1) // len(pool))] + )[: steps * 20].reshape(steps, 20) + ) + return np.concatenate(streams, axis=1) + + +def audit(world): + expected = np.ones(world.n_base, dtype=np.int64) + expected[world.root_ids.ravel()] = 32 + report = {} + for condition in CONDITIONS: + docs = documents(world, condition) + if not np.array_equal(np.bincount(docs.ravel(), minlength=world.n_base), expected): + raise ValueError("Unequal fact exposure") + personal = world.person[docs[:, [0, 2, 3, 4, 5, 6, 7, 9]]] + if not np.all(personal == np.arange(N_PEOPLE)[:, None]): + raise ValueError("Person grouping changed") + for chain, slot in enumerate((1, 8)): + linked = docs[:, slot] == world.root_ids[chain, world.memberships[chain]] + if not np.all(linked == (condition == CHAINS[chain])): + raise ValueError("Incorrect linked/unlinked manipulation") + slots = np.zeros((world.n_base, SLOTS), dtype=np.int64) + for epoch in range(SLOTS): + arranged = epoch_documents(docs, world.seed, epoch) + np.add.at(slots, (arranged, np.arange(SLOTS)[None, :]), 1) + if not np.array_equal(slots, np.repeat(expected[:, None], SLOTS, axis=1)): + raise ValueError("Unequal position exposure") + report[condition] = { + "documents_sha256": array_hash(docs), + "exposure_sha256": array_hash(expected), + } + for chain in range(2): + if not np.array_equal(np.bincount(world.memberships[chain]), np.full(64, 32)): + raise ValueError("Unequal group sizes") + for group in range(64): + members = world.memberships[chain] == group + if world.exceptions[chain, members].sum() != 2: + raise ValueError("Unequal exceptions") + if len(np.intersect1d(world.train_ids[chain], world.heldout_ids[chain])): + raise ValueError("QA leakage") + truth = world.city_tokens[world.defaults[chain, world.memberships[chain]]] + np.testing.assert_array_equal(world.answers[world.derived_ids[chain]], truth) + np.testing.assert_array_equal(np.sort(world.defaults[0]), np.sort(world.defaults[1])) + return { + "passed": True, + "world": world.seed, + "conditions": report, + "base_facts": world.n_base, + "queries": len(world.answers), + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "QA_train_per_chain": 1024, + "QA_heldout_per_chain": 1024, + } + + +def save_world(world, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + directory / "world.npz", + **{key: value for key, value in vars(world).items() if isinstance(value, np.ndarray)}, + ) + write_json( + directory / "metadata.json", + {"seed": world.seed, "n_base": world.n_base, "token_labels": world.token_labels}, + ) + write_json(directory / "audit.json", audit(world)) + + +def edit_pair(world, chain, support=0): + rng = rng_for(world.seed, 907, chain * 100 + support) + while True: + groups = rng.choice(64, 3, replace=False) + if len(set(world.defaults[chain, groups])) == 3: + break + coherent, exception = world.answers.copy(), world.answers.copy() + conflict_people = [] + for j, group in enumerate(groups): + new, alt = world.city_tokens[world.defaults[chain, groups[[(j + 1) % 3, (j + 2) % 3]]]] + root = world.root_ids[chain, group] + coherent[root] = exception[root] = new + members = rng.permutation( + np.flatnonzero((world.memberships[chain] == group) & ~world.exceptions[chain]) + ) + ids = world.actual_ids[chain, members] + coherent[ids] = new + exception[ids[:15]], exception[ids[15:]] = new, alt + conflict_people.extend(members[15:]) + derived = world.derived_ids[chain, world.memberships[chain] == group] + coherent[derived] = exception[derived] = new + changed = coherent != world.answers + np.testing.assert_array_equal(changed, exception != world.answers) + e, d = np.flatnonzero(changed[: world.n_base]), np.flatnonzero(changed & (world.relation >= 10)) + assert len(e) == 93 and len(d) == 96 + np.testing.assert_array_equal(np.sort(coherent[e]), np.sort(exception[e])) + # Disjoint retention strata: old exceptions, other facts of affected people, + # remaining task-chain facts, and remaining independent/cross-chain facts. + selected_people = np.isin(world.memberships[chain], groups) + selected_facts = (world.person >= 0) & selected_people[np.maximum(world.person, 0)] + old_exceptions = np.zeros(len(world.answers), dtype=bool) + old_exceptions[world.actual_ids[chain, selected_people & world.exceptions[chain]]] = True + relevant = np.isin(world.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(world.answers), -1, dtype=np.int64) + strata[~changed & old_exceptions] = 0 + strata[~changed & selected_facts & ~old_exceptions] = 1 + strata[~changed & ~selected_facts & relevant] = 2 + strata[~changed & ~selected_facts & ~relevant] = 3 + assert np.array_equal(strata >= 0, ~changed) + heldout, replay_pool = [], [] + for g in range(4): + ids = rng.permutation(np.flatnonzero((strata == g) & (world.relation < 10))) + n = max(1, int(np.ceil(0.2 * len(ids)))) + heldout.extend(ids[:n]) + replay_pool.extend(ids[n:]) + heldout.extend(np.flatnonzero((strata >= 0) & (world.relation >= 10))) + replay = rng.choice(replay_pool, min(4096, len(replay_pool)), replace=False) + return { + "coherent": coherent, + "exception": exception, + "E": e, + "D": d, + "conflict_D": world.derived_ids[chain, conflict_people], + "strata": strata, + "heldout": np.array(sorted(heldout)), + "replay": replay, + "groups": groups, + } diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_cross_continue.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_cross_continue.py new file mode 100644 index 0000000000000000000000000000000000000000..df0a21278c640164306e05b7465e24cc0e6d0df8 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_cross_continue.py @@ -0,0 +1,627 @@ +"""Protocol v2.8 P2: audited continuation of frozen crossover checkpoints.""" + +import argparse +import copy +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CHAINS, + audit, + documents, + edit_pair, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_cross_train import edit_metrics as original_edit_metrics +from .bios_cross_train import evaluate, learning_metrics, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +PARENT_STEP = 15360 +FINAL_STEP = 30720 +CHECKPOINTS = (15360, 20480, 25600, 30720) +EDIT_CHECKPOINTS = (0, 32, 128, 512) + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def continuation_sources(): + return {**source_hashes(), Path(__file__).name: file_hash(__file__)} + + +def tree_hash(value): + """Stable audit hash for nested optimizer/RNG states, without pickle metadata.""" + digest = hashlib.sha256() + + def visit(item): + if isinstance(item, torch.Tensor): + item = item.detach().cpu().contiguous() + digest.update(f"tensor:{item.dtype}:{tuple(item.shape)}:".encode()) + digest.update(item.reshape(-1).view(torch.uint8).numpy().tobytes()) + elif isinstance(item, np.ndarray): + digest.update(f"numpy:{item.dtype}:{item.shape}:".encode()) + digest.update(np.ascontiguousarray(item).tobytes()) + elif isinstance(item, dict): + digest.update(b"dict[") + for key in sorted(item, key=lambda key: (type(key).__name__, str(key))): + visit(key) + visit(item[key]) + digest.update(b"]") + elif isinstance(item, (list, tuple)): + digest.update(type(item).__name__.encode() + b"[") + for child in item: + visit(child) + digest.update(b"]") + else: + digest.update(f"{type(item).__name__}:{item!r};".encode()) + + visit(value) + return digest.hexdigest() + + +def continuation_lr(base_lr, absolute_step): + """Use the original absolute epoch; never restart warmup at a branch point.""" + return base_lr * min((absolute_step // 128 + 1) / 16, 1) + + +def validate_optimizer(optimizer_state, step, learning_rate): + states = optimizer_state["state"] + groups = optimizer_state["param_groups"] + if not states or sum(len(group["params"]) for group in groups) != len(states): + raise ValueError("Missing parent optimizer moments") + for state in states.values(): + if not {"step", "exp_avg", "exp_avg_sq"} <= state.keys(): + raise ValueError("Incomplete AdamW state") + if int(state["step"]) != step: + raise ValueError("Optimizer update count differs from checkpoint step") + for group in groups: + if group["lr"] != learning_rate or group["weight_decay"] != 0.1: + raise ValueError("Parent optimizer learning rate or decay changed") + + +def expected_exposure(world, docs, schedule, step, base_lr): + """Reconstruct original full-epoch exposure, positions, and LR-weighted exposure.""" + epochs, remainder = divmod(step, 128) + if remainder: + raise ValueError("Parent must end on a complete document epoch") + occurrence = np.bincount(docs.ravel(), minlength=world.n_base) + counts = np.bincount(schedule[:step].ravel(), minlength=len(world.answers)) + counts[: world.n_base] += epochs * occurrence + slots = np.repeat((occurrence * (epochs // 10))[:, None], 10, axis=1) + for epoch in range(epochs % 10): + arranged = np.roll(docs, epoch, axis=1) + np.add.at(slots, (arranged, np.arange(10)[None, :]), 1) + weighted = np.zeros(len(world.answers), dtype=np.float64) + weighted[: world.n_base] = occurrence * sum( + continuation_lr(base_lr, epoch * 128) for epoch in range(epochs) + ) + rates = np.repeat([continuation_lr(base_lr, i) for i in range(step)], 40) + np.add.at(weighted, schedule[:step].ravel(), rates) + return counts, slots, weighted + + +def validate_parent(parent, world, new_lr): + """Verify immutable parent provenance and the longer stream before any updates.""" + parent = Path(parent).resolve() + config = json.loads((parent / "config.json").read_text()) + study = config["study"] + if study["width"] not in (128, 256) or config["world"] not in (0, 1): + raise ValueError("P2 includes only the two declared sizes and development worlds") + if config["seed"] not in (0, 1) or config["condition"] not in ("company", "project", "neither"): + raise ValueError("Unexpected P2 initialization or organization") + if new_lr not in (0.0001, 0.0003) or (new_lr == 0.0003 and config["seed"] != 0): + raise ValueError("The sensitivity branch contains only initialization zero") + if study["steps"] != PARENT_STEP or study["lr"] != 0.0001: + raise ValueError("P2 must fork the original 15360-step, 1e-4 trajectory") + if config["sources"] != source_hashes(): + raise ValueError("Frozen parent training sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent Torch/NumPy versions differ from continuation") + if config["world"] != world.seed or config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent world/truth mismatch") + if config["prompts_sha256"] != array_hash(world.prompts): + raise ValueError("Parent query prompts changed") + for name, expected in { + "layers": 8, + "heads": study["width"] // 64, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "edit_steps": 512, + "edit_lr": 0.00003, + "retention_kl": 1.0, + }.items(): + if study[name] != expected: + raise ValueError(f"Unexpected frozen parent setting: {name}") + docs, schedule = documents(world, config["condition"]), qa_schedule(world, FINAL_STEP) + with np.load(parent / "schedule.npz") as old: + np.testing.assert_array_equal(docs, old["documents"]) + np.testing.assert_array_equal(schedule[:PARENT_STEP], old["qa"]) + if array_hash(docs) != config["documents_sha256"]: + raise ValueError("Parent document hash mismatch") + if array_hash(schedule[:PARENT_STEP]) != config["qa_sha256"]: + raise ValueError("Extended QA stream does not preserve the original prefix") + resume = torch.load(parent / "resume.pt", map_location="cpu", weights_only=False) + if resume["step"] != PARENT_STEP or resume["config_sha256"] != file_hash( + parent / "config.json" + ): + raise ValueError("Parent resume step/config mismatch") + validate_optimizer(resume["optimizer"], PARENT_STEP, study["lr"]) + saved_model = torch.load( + parent / f"model-{PARENT_STEP}.pt", map_location="cpu", weights_only=False + ) + completed = json.loads((parent / "learning-complete.json").read_text()) + model_hash = state_hash(resume["model"]) + if ( + model_hash != state_hash(saved_model["model"]) + or model_hash != completed["model_sha256"] + or saved_model["step"] != PARENT_STEP + or saved_model["config"] != config["model"] + ): + raise ValueError("Parent final model and resume state disagree") + expected = expected_exposure(world, docs, schedule, PARENT_STEP, study["lr"]) + with np.load(parent / f"predictions-{PARENT_STEP}.npz") as predictions: + for key, wanted in zip(("counts", "slots", "weighted"), expected, strict=True): + if key == "weighted": + np.testing.assert_allclose(resume[key], wanted, rtol=0, atol=1e-10) + else: + np.testing.assert_array_equal(resume[key], wanted) + stored_key = "exposure" if key == "counts" else key + np.testing.assert_array_equal(resume[key], predictions[stored_key]) + if resume["timeline"][-1]["step"] != PARENT_STEP: + raise ValueError("Parent learning history lacks the final checkpoint") + if not isinstance(resume["torch_rng"], torch.Tensor): + raise ValueError("Parent torch RNG is missing") + files = ( + "config.json", + "resume.pt", + f"model-{PARENT_STEP}.pt", + "schedule.npz", + f"predictions-{PARENT_STEP}.npz", + "learning-complete.json", + ) + provenance = { + "directory": str(parent), + "files_sha256": {name: file_hash(parent / name) for name in files}, + "model_sha256": model_hash, + "optimizer_sha256": tree_hash(resume["optimizer"]), + "torch_rng_sha256": tree_hash(resume["torch_rng"]), + "cuda_rng_sha256": tree_hash(resume["cuda_rng"]), + "qa_prefix_verified": True, + "exposure_reconstruction_verified": True, + } + return config, resume, docs, schedule, provenance + + +def restore_state(model, optimizer, saved, device): + model.load_state_dict(saved["model"]) + # load_state_dict may alias CPU tensors; branch updates must not mutate the parent. + optimizer.load_state_dict(copy.deepcopy(saved["optimizer"])) + torch.set_rng_state(saved["torch_rng"].cpu()) + if device.type == "cuda": + if saved["cuda_rng"] is None: + raise ValueError("CUDA parent/resume RNG state is missing") + torch.cuda.set_rng_state(saved["cuda_rng"].cpu(), device) + + +def capture_state(model, optimizer, device, **metadata): + return { + **metadata, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + } + + +def learning_update(model, optimizer, cache, data, qa, start, end, lr, device): + """The original arithmetic/gradient order, with an absolute-step learning rate.""" + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(cache["tokens"][start:end], cache["positions"][start:end]) + doc_loss = F.cross_entropy( + logits.float().flatten(0, 1), cache["labels"][start:end].flatten() + ) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(data["tokens"][qa], data["positions"][qa]) + qa_loss = F.cross_entropy(logits.float().flatten(0, 1), data["labels"][qa].flatten()) + (0.2 * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1) + if not torch.isfinite(doc_loss + qa_loss + norm): + raise FloatingPointError("Nonfinite continuation update") + optimizer.step() + + +def learning(parent, out, world, base_lr, device): + old_config, parent_resume, docs, schedule, provenance = validate_parent(parent, world, base_lr) + study = { + **old_config["study"], + "protocol": "v2.8-development-p2-continuation", + "steps": FINAL_STEP, + "checkpoints": list(CHECKPOINTS), + "lr": base_lr, + "edit_scopes": ["mlp"], + "seeds": [0] if base_lr == 0.0003 else [0, 1], + "learning_runs": 6 if base_lr == 0.0003 else 12, + "edit_cases": 24 if base_lr == 0.0003 else 48, + "edit_cases_per_run": 4, + "parent_step": PARENT_STEP, + "warmup": "original absolute epoch; no restart", + "primary_learning": ( + "heldout full-answer accuracy at 30720 absolute steps; " + "preserve all prespecified earlier checkpoints" + ), + "aggregation": ( + "pair organizations within world/initialization; " + "development worlds are not confirmatory replications" + ), + } + identity = { + "world": old_config["world"], + "seed": old_config["seed"], + "condition": old_config["condition"], + "study": study, + "sources": continuation_sources(), + "parent": provenance, + "model": old_config["model"], + "initial_sha256": old_config["initial_sha256"], + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + "torch": torch.__version__, + "numpy": np.__version__, + "device_type": device.type, + "cuda": torch.version.cuda, + "gpu_type": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + } + config_path = out / "config.json" + if config_path.exists(): + existing = json.loads(config_path.read_text()) + if any(existing.get(key) != value for key, value in identity.items()): + raise ValueError("Continuation identity, parent, software or sources changed") + else: + write_json( + config_path, + { + **identity, + "python": platform.python_version(), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast; FP32 weights and optimizer", + "parameters": old_config["parameters"], + }, + ) + atomic_numpy_save(out / "schedule.npz", documents=docs, qa=schedule) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + model_config = ModelConfig(**old_config["model"]) + model = CausalLM(model_config).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=base_lr, weight_decay=0.1, fused=device.type == "cuda" + ) + if (out / "resume.pt").exists(): + saved = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if saved["config_sha256"] != file_hash(config_path): + raise ValueError("Continuation resume configuration mismatch") + else: + saved = {**parent_resume, "timeline": [], "config_sha256": file_hash(config_path)} + restore_state(model, optimizer, saved, device) + first, seconds = saved["step"], saved["seconds"] + timeline = saved["timeline"] + counts, slots, weighted = saved["counts"], saved["slots"], saved["weighted"] + if not PARENT_STEP <= first <= FINAL_STEP: + raise ValueError("Continuation resume step is outside its frozen interval") + data = tensor_queries(world, device) + + def save_resume(step): + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + counts=counts, + slots=slots, + weighted=weighted, + config_sha256=file_hash(config_path), + ), + out / "resume.pt", + ) + + epoch_cached = -1 + for step in range(first, FINAL_STEP + 1): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + if step == PARENT_STEP: + with np.load(Path(parent) / f"predictions-{PARENT_STEP}.npz") as old: + arrays = { + key: old[key] for key in ("prediction", "ended", "correct", "value_nll") + } + else: + arrays = evaluate(model, data, world.answers) + point = { + "step": step, + **learning_metrics(world, arrays), + "train_seconds": seconds, + "exposure_sha256": array_hash(counts), + "slots_sha256": array_hash(slots), + "weighted_sha256": array_hash(weighted), + "train_matmul_flops_estimate": step + * (matmul_flops(model_config, 16, 60, 20) + matmul_flops(model_config, 40, 6, 2)), + } + timeline.append(point) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slots=slots, + weighted=weighted, + ) + atomic_torch_save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + write_json(out / "learning.json", timeline) + save_resume(step) + print(json.dumps({"event": "checkpoint", **point}), flush=True) + if step == FINAL_STEP: + break + epoch, offset = divmod(step, 128) + if epoch != epoch_cached: + arranged = epoch_documents(docs, world.seed, epoch) + cache = { + key: torch.as_tensor(value, device=device) + for key, value in render(world, arranged).items() + } + epoch_cached = epoch + start, end = offset * 16, (offset + 1) * 16 + qa = torch.as_tensor(schedule[step], device=device) + lr = continuation_lr(base_lr, step) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + learning_update(model, optimizer, cache, data, qa, start, end, lr, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + fact_ids = arranged[start:end] + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, schedule[step], 1) + np.add.at(slots, (fact_ids, np.arange(10)[None, :]), 1) + np.add.at(weighted, fact_ids.ravel(), lr) + np.add.at(weighted, schedule[step], lr) + if (step + 1) % 256 == 0 and step + 1 not in CHECKPOINTS: + save_resume(step + 1) + print( + json.dumps({"event": "progress", "step": step + 1, "seconds": seconds}), flush=True + ) + write_json( + out / "learning-complete.json", + { + "status": "complete", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + return model, data, study + + +def edit_metrics(world, pair, arrays, old_correct): + metrics = original_edit_metrics(world, pair, arrays, old_correct) + heldout = np.intersect1d(pair["conflict_D"], world.heldout_ids.ravel()) + metrics["D_conflict_heldout_n"] = len(heldout) + metrics["D_conflict_heldout"] = ( + float(arrays["correct"][heldout].mean()) if len(heldout) else None + ) + for label, ids in (("default", world.root_ids.ravel()), ("actual", world.actual_ids.ravel())): + subset = np.intersect1d(pair["E"], ids) + metrics[f"E_{label}_n"] = len(subset) + metrics[f"E_{label}"] = float(arrays["correct"][subset].mean()) + return metrics + + +def edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device): + model.train() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce = F.cross_entropy(logits.flatten(0, 1), new_data["labels"][ei].flatten()) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite continuation edit") + optimizer.step() + + +def edits(world, model, data, out, study, device): + baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()} + old_arrays = evaluate(model, data, world.answers) + config_sha = file_hash(out / "config.json") + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + e_choices = rng.integers(len(pair["E"]), size=(512, 128)) + r_choices = rng.integers(len(pair["replay"]), size=(512, 128)) + for kind in ("coherent", "exception"): + dest = out / "edits" / f"{name}-{kind}-mlp" + if (dest / "complete.json").exists(): + continue + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + target = pair[kind] + new_data = tensor_queries(world, device, target) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline, seconds, first = [], 0.0, 0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["config_sha256"] != config_sha or saved["case"] != dest.name: + raise ValueError("Editing resume identity mismatch") + restore_state(model, optimizer, saved, device) + timeline, seconds, first = saved["timeline"], saved["seconds"], saved["step"] + for step in range(first, 513): + if step in EDIT_CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, data, target) + point = { + "step": step, + **edit_metrics(world, pair, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + config_sha256=config_sha, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update( + model, optimizer, selected, data, new_data, references, ei, ri, choices, device + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict()}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "chain": name, + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + }, + ) + print( + json.dumps( + { + "event": "edit_complete", + "case": dest.name, + "E": timeline[-1]["E"], + "D": timeline[-1]["D"], + } + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--lr", type=float, choices=(0.0001, 0.0003), default=0.0001) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + parser.add_argument("--learning-only", action="store_true") + args = parser.parse_args() + parent, out = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == out or parent in out.parents or out in parent.parents: + raise ValueError("Continuation output must be separate from its immutable parent") + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + world = make_cross_world(json.loads((parent / "config.json").read_text())["world"]) + audit(world) + device = torch.device(args.device) + try: + model, data, study = learning(parent, out, world, args.lr, device) + if not args.learning_only: + edits(world, model, data, out, study, device) + write_json( + out / "complete.json", + { + "status": "complete", + "learning_steps": FINAL_STEP, + "edit_cases": 4, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_cross_scale.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_cross_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..af5c92edca554475a9bdf9dee9b46438455b1f96 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_cross_scale.py @@ -0,0 +1,51 @@ +"""Contracts and denominator-aware summaries for the frozen crossover size extension.""" + +from itertools import product + +import numpy as np + + +def validate_size_study(reference, study, width, heads): + expected = {**reference, "width": width, "heads": heads} + if study != expected: + changed = sorted(k for k in set(expected) | set(study) if expected.get(k) != study.get(k)) + raise ValueError(f"Non-size study changes: {changed}") + if width // heads != 64 or study["layers"] != 8: + raise ValueError("Expected eight layers and head dimension 64") + + +def validate_run_grid(configs, study, require_complete): + expected = set(product(study["worlds"], study["seeds"], study["conditions"])) + keys = [(c["world"], c["seed"], c["condition"]) for c in configs] + if len(keys) != len(set(keys)) or set(keys) - expected: + raise ValueError("Duplicate or unexpected experimental units") + if require_complete and set(keys) != expected: + raise ValueError("Missing experimental units") + + +def retention_coverage(pair, old_correct, row): + """Keep unknown facts outside the damage denominator and expose their coverage.""" + result = {} + for pool_name, pool in ( + ("full", np.arange(len(old_correct))), + ("heldout", pair["heldout"]), + ): + totals, knowns, brokens = [], [], [] + for group in range(4): + ids = np.intersect1d(pool, np.flatnonzero(pair["strata"] == group)) + prefix = f"U_{pool_name}_{group}" + total, known, broken = len(ids), int(old_correct[ids].sum()), row[f"{prefix}_broken"] + if known != row[f"{prefix}_known"] or not 0 <= broken <= known: + raise ValueError("Retention denominator or broken count mismatch") + totals.append(total) + knowns.append(known) + brokens.append(broken) + result[f"{prefix}_total"] = total + result[f"{prefix}_coverage"] = known / total if total else None + total, known, broken = sum(totals), sum(knowns), sum(brokens) + result[f"U_{pool_name}_total"] = total + result[f"U_{pool_name}_coverage"] = known / total if total else None + result[f"U_{pool_name}_micro_damage"] = broken / known if known else None + result["E_old_accuracy"] = float(old_correct[pair["E"]].mean()) + result["D_old_accuracy"] = float(old_correct[pair["D"]].mean()) + return result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_cross_train.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_cross_train.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5f3f45a169e643c408f1044eaa766b79a595fd --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_cross_train.py @@ -0,0 +1,474 @@ +"""Frozen learning and editing runs for the two-relation crossover.""" + +import argparse +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CHAINS, + CONDITIONS, + audit, + documents, + edit_pair, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + + +def tensor_queries(world, device, answers=None): + answers = world.answers if answers is None else answers + prompts = torch.as_tensor(world.prompts, device=device) + lengths = torch.as_tensor(world.lengths, device=device) + targets = torch.as_tensor(answers, device=device) + tokens = torch.zeros((len(answers), 6), device=device, dtype=torch.long) + tokens[:, :5] = prompts + tokens[torch.arange(len(answers), device=device), lengths] = targets + tokens[lengths == 4, 5] = EOS + return { + "prompts": prompts, + "lengths": lengths, + "tokens": tokens, + "positions": torch.stack([lengths - 1, lengths], -1), + "labels": torch.stack([targets, torch.full_like(targets, EOS)], -1), + } + + +@torch.no_grad() +def evaluate(model, data, answers, batch_size=512): + model.eval() + device = data["tokens"].device + predictions, ended, nll = [], [], [] + for begin in range(0, len(answers), batch_size): + end = min(begin + batch_size, len(answers)) + lengths = data["lengths"][begin:end] + with precision(device): + logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float() + first = logits.argmax(-1) + continuation = torch.zeros((end - begin, 6), device=device, dtype=torch.long) + continuation[:, :5] = data["prompts"][begin:end] + continuation[torch.arange(end - begin, device=device), lengths] = first + second = model(continuation, lengths[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + targets = torch.as_tensor(answers[begin:end], device=device) + nll.append(F.cross_entropy(logits, targets, reduction="none").cpu().numpy()) + prediction, ended = np.concatenate(predictions), np.concatenate(ended) + return { + "prediction": prediction, + "ended": ended, + "correct": (prediction == answers) & ended, + "value_nll": np.concatenate(nll), + } + + +def learning_metrics(world, arrays): + correct = arrays["correct"] + result = { + "base_accuracy": float(correct[: world.n_base].mean()), + "base_nll": float(arrays["value_nll"][: world.n_base].mean()), + } + for chain, name in enumerate(CHAINS): + for split, ids in ( + ("trained", world.train_ids[chain]), + ("heldout", world.heldout_ids[chain]), + ): + result[f"{name}_{split}"] = float(correct[ids].mean()) + result[f"{name}_{split}_nll"] = float(arrays["value_nll"][ids].mean()) + for label, ids in ( + ("membership", world.membership_ids[chain]), + ("default", world.root_ids[chain]), + ("actual", world.actual_ids[chain]), + ): + result[f"{name}_{label}"] = float(correct[ids].mean()) + # A conditional diagnostic, never a replacement for the whole test pool. + prerequisites = ( + correct[world.membership_ids[chain]] + & correct[world.root_ids[chain, world.memberships[chain]]] + ) + known_ids = np.intersect1d( + world.heldout_ids[chain], world.derived_ids[chain, prerequisites] + ) + result[f"{name}_known_heldout_n"] = len(known_ids) + result[f"{name}_known_heldout"] = ( + float(correct[known_ids].mean()) if len(known_ids) else None + ) + result["mean_heldout"] = (result["company_heldout"] + result["project_heldout"]) / 2 + return result + + +def source_hashes(): + root = Path(__file__).parent + return { + name: hashlib.sha256((root / name).read_bytes()).hexdigest() + for name in ( + "bios_cross.py", + "bios_cross_train.py", + "bios_model.py", + "bios_data.py", + "bios_train.py", + "bios_organization_train.py", + ) + } + + +def learning(args, world, out, study, device): + torch.manual_seed(args.seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + config = ModelConfig(world.vocab_size, study["width"], study["layers"], study["heads"]) + model = CausalLM(config).to(device) + initial_hash = state_hash(model.state_dict()) + docs, schedule = documents(world, args.condition), qa_schedule(world, study["steps"]) + identity = { + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "study": study, + "sources": source_hashes(), + "model": model.config_dict(), + "initial_sha256": initial_hash, + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + } + config_path = out / "config.json" + if config_path.exists(): + saved = json.loads(config_path.read_text()) + if any(saved[k] != v for k, v in identity.items()): + raise ValueError("Frozen run identity or sources changed") + else: + write_json( + config_path, + { + **identity, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "python": platform.python_version(), + "numpy": np.__version__, + "device": str(device), + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "precision": "BF16 autocast; FP32 weights and optimizer", + "parameters": sum(p.numel() for p in model.parameters()), + }, + ) + atomic_numpy_save(out / "schedule.npz", documents=docs, qa=schedule) + data = tensor_queries(world, device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=study["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline, first, seconds = [], 0, 0.0 + counts = np.zeros(len(world.answers), dtype=np.int64) + slots = np.zeros((world.n_base, 10), dtype=np.int64) + weighted = np.zeros(len(world.answers), dtype=np.float64) + if (out / "resume.pt").exists(): + resume = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if resume["config_sha256"] != hashlib.sha256(config_path.read_bytes()).hexdigest(): + raise ValueError("Resume configuration mismatch") + model.load_state_dict(resume["model"]) + optimizer.load_state_dict(resume["optimizer"]) + first, timeline, seconds = resume["step"], resume["timeline"], resume["seconds"] + counts, slots, weighted = resume["counts"], resume["slots"], resume["weighted"] + torch.set_rng_state(resume["torch_rng"]) + if device.type == "cuda": + torch.cuda.set_rng_state(resume["cuda_rng"], device) + epoch_cached, cache = -1, None + for step in range(first, study["steps"] + 1): + if step in study["checkpoints"] and (not timeline or step != first): + arrays = evaluate(model, data, world.answers) + point = { + "step": step, + **learning_metrics(world, arrays), + "train_seconds": seconds, + "exposure_sha256": array_hash(counts), + "slots_sha256": array_hash(slots), + "weighted_sha256": array_hash(weighted), + "train_matmul_flops_estimate": step + * (matmul_flops(config, 16, 60, 20) + matmul_flops(config, 40, 6, 2)), + } + timeline.append(point) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slots=slots, + weighted=weighted, + ) + atomic_torch_save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + write_json(out / "learning.json", timeline) + atomic_torch_save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "timeline": timeline, + "seconds": seconds, + "counts": counts, + "slots": slots, + "weighted": weighted, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), + }, + out / "resume.pt", + ) + print(json.dumps({"event": "checkpoint", **point}), flush=True) + if step == study["steps"]: + break + epoch, offset = divmod(step, 128) + if epoch != epoch_cached: + arranged = epoch_documents(docs, world.seed, epoch) + cache = { + k: torch.as_tensor(v, device=device) for k, v in render(world, arranged).items() + } + epoch_cached = epoch + start, end = offset * 16, (offset + 1) * 16 + fact_ids = arranged[start:end] + qa = torch.as_tensor(schedule[step], device=device) + lr = study["lr"] * min((epoch + 1) / 16, 1) + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(cache["tokens"][start:end], cache["positions"][start:end]) + doc_loss = F.cross_entropy( + logits.float().flatten(0, 1), cache["labels"][start:end].flatten() + ) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(data["tokens"][qa], data["positions"][qa]) + qa_loss = F.cross_entropy(logits.float().flatten(0, 1), data["labels"][qa].flatten()) + (0.2 * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1) + if not torch.isfinite(doc_loss + qa_loss + norm): + raise FloatingPointError("Nonfinite learning update") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, schedule[step], 1) + np.add.at(slots, (fact_ids, np.arange(10)[None, :]), 1) + np.add.at(weighted, fact_ids.ravel(), lr) + np.add.at(weighted, schedule[step], lr) + if (step + 1) % 256 == 0: + print( + json.dumps({"event": "progress", "step": step + 1, "seconds": seconds}), flush=True + ) + write_json( + out / "learning-complete.json", + { + "status": "complete", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + return model, data + + +def edit_metrics(world, pair, arrays, old_correct): + correct = arrays["correct"] + metrics = { + "E": float(correct[pair["E"]].mean()), + "D": float(correct[pair["D"]].mean()), + "D_conflict": float(correct[pair["conflict_D"]].mean()), + } + for split, ids in ( + ("trained", world.train_ids.ravel()), + ("heldout", world.heldout_ids.ravel()), + ): + subset = np.intersect1d(pair["D"], ids) + metrics[f"D_{split}_n"] = len(subset) + metrics[f"D_{split}"] = float(correct[subset].mean()) if len(subset) else None + for name, pool in (("full", np.arange(len(correct))), ("heldout", pair["heldout"])): + strata = {} + for group in range(4): + ids = np.intersect1d(pool, np.flatnonzero((pair["strata"] == group) & old_correct)) + strata[str(group)] = { + "known": len(ids), + "broken": int((~correct[ids]).sum()), + "rate": float((~correct[ids]).mean()) if len(ids) else None, + } + metrics[f"U_{name}"] = strata + return metrics + + +def edits(args, world, model, data, out, study, device): + baseline = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()} + old_arrays = evaluate(model, data, world.answers) + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + e_choices = rng.integers(len(pair["E"]), size=(study["edit_steps"], 128)) + r_choices = rng.integers(len(pair["replay"]), size=(study["edit_steps"], 128)) + for kind in ("coherent", "exception"): + target = pair[kind] + new_data = tensor_queries(world, device, target) + for scope in ("mlp", "all"): + dest = out / "edits" / f"{name}-{kind}-{scope}" + if (dest / "complete.json").exists(): + continue + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, scope, 3) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append( + model(data["tokens"][ids], data["positions"][ids]).detach() + ) + references = torch.cat(references) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline = [] + seconds = 0.0 + for step in range(study["edit_steps"] + 1): + if step in study["edit_checkpoints"]: + arrays = evaluate(model, data, target) + point = { + "step": step, + **edit_metrics(world, pair, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step == study["edit_steps"]: + break + model.train() + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce = F.cross_entropy(logits.flatten(0, 1), new_data["labels"][ei].flatten()) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + study["retention_kl"] * kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite edit") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict()}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "chain": name, + "kind": kind, + "scope": scope, + "final": timeline[-1], + }, + ) + print( + json.dumps( + { + "event": "edit_complete", + "case": dest.name, + "E": timeline[-1]["E"], + "D": timeline[-1]["D"], + } + ), + flush=True, + ) + del references, optimizer + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--config", default="configs/bios-cross-development-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + args = parser.parse_args() + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + study = json.loads(Path(args.config).read_text()) + torch.set_num_threads(args.threads) + device = torch.device(args.device) + world = make_cross_world(args.world) + audit(world) + try: + model, data = learning(args, world, out, study, device) + edits(args, world, model, data, out, study, device) + write_json( + out / "complete.json", + { + "status": "complete", + "learning_steps": study["steps"], + "edit_cases": 8, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_data.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3acf9b51a11985eb747a2c2565bc551ae803fd9b --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_data.py @@ -0,0 +1,367 @@ +"""bioS-Work-v1 truth, equal-exposure curricula and paired counterfactual worlds. + +Official files remain unmodified in data/bios-source; this is a new adapter. +The symbolic experiment does not imply that the natural-language audit is complete. +""" + +import calendar +import hashlib +import json +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +REVISION = "211b28f2e9d453114ca5a1cbbb2d5a632ac60fcf" +SOURCE_FOLDER = "data-synthetic-pretrain/Capo-bioS-bioR" +RELATIONS = ( + "employer", + "default_city", + "actual_city", + "birth_date", + "birth_city", + "university", + "major", +) +N_PEOPLE, N_COMPANIES, N_BASE, N_QUERIES = 2048, 64, 12352, 14400 +PAD, BOS, ANS, EOS = range(4) + + +def rng_for(seed, purpose, index=0): + return np.random.default_rng(np.random.SeedSequence([seed, purpose, index])) + + +def array_hash(array): + return hashlib.sha256(np.ascontiguousarray(array).tobytes()).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, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temporary.replace(path) + + +@dataclass +class World: + seed: int + prompts: np.ndarray + lengths: np.ndarray + answers: np.ndarray + relation: np.ndarray + person: np.ndarray + company: np.ndarray + employers: np.ndarray + defaults: np.ndarray + actual: np.ndarray + exceptions: np.ndarray + city_tokens: np.ndarray + token_labels: list + names: dict + + @property + def vocab_size(self): + return len(self.token_labels) + + def save(self, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + arrays = {k: v for k, v in vars(self).items() if isinstance(v, np.ndarray)} + np.savez_compressed(directory / "world.npz", **arrays) + write_json( + directory / "metadata.json", + {"seed": self.seed, "token_labels": self.token_labels, "names": self.names}, + ) + write_json(directory / "audit.json", audit_world(self)) + + +def load_world(directory): + directory = Path(directory) + metadata = json.loads((directory / "metadata.json").read_text()) + with np.load(directory / "world.npz", allow_pickle=False) as arrays: + return World(**metadata, **dict(arrays)) + + +def make_world(seed, source_root="data/bios-source"): + source_root = Path(source_root) + manifest = json.loads((source_root / "manifest.json").read_text()) + if manifest["revision"] != REVISION: + raise ValueError("Unexpected official source revision") + for entry in manifest["files"]: + if ( + hashlib.sha256((source_root / entry["path"]).read_bytes()).hexdigest() + != entry["sha256"] + ): + raise ValueError("Source hash mismatch: " + entry["path"]) + + def field(name): + return (source_root / SOURCE_FOLDER / "fields" / (name + ".txt")).read_text().splitlines() + + cities, universities, majors = field("city"), field("university"), field("field") + first, middle, last = field("first_name"), field("middle_name"), field("last_name") + names_rng, group_rng, value_rng = (rng_for(seed, i) for i in (11, 12, 13)) + + def unique_names(count): + result, used = [], set() + while len(result) < count: + value = f"{names_rng.choice(first)} {names_rng.choice(middle)} {names_rng.choice(last)}" + if value.casefold() not in used: + result.append(value) + used.add(value.casefold()) + return result + + person_names = unique_names(2 * N_PEOPLE) + syllables = ("va", "ne", "ri", "lo", "sa", "tu", "mi", "ze", "ka", "po", "da", "fi") + company_names, used = [], set() + while len(company_names) < 2 * N_COMPANIES: + value = "".join(names_rng.choice(syllables, 4)).capitalize() + " Labs" + if value not in used: + used.add(value) + company_names.append(value) + employers = group_rng.permutation(np.repeat(np.arange(N_COMPANIES), 32)) + work_cities = value_rng.choice(len(cities), 32, replace=False) + defaults = value_rng.permutation(np.repeat(work_cities, 2)) + exceptions = np.zeros(N_PEOPLE, dtype=bool) + actual = defaults[employers].copy() + for c in range(N_COMPANIES): + selected = group_rng.choice(np.flatnonzero(employers == c), 2, replace=False) + exceptions[selected] = True + actual[selected] = value_rng.choice(work_cities[work_cities != defaults[c]], 2) + attributes_rng = rng_for(seed, 14) + years = attributes_rng.integers(1900, 2100, N_PEOPLE) + months = attributes_rng.integers(1, 13, N_PEOPLE) + days = attributes_rng.integers(1, 29, N_PEOPLE) + dates = [ + f"{calendar.month_name[m]} {d}, {y}" for y, m, d in zip(years, months, days, strict=True) + ] + birth_cities = attributes_rng.integers(0, len(cities), N_PEOPLE) + university = attributes_rng.integers(0, len(universities), N_PEOPLE) + major = attributes_rng.integers(0, len(majors), N_PEOPLE) + labels = ( + [f"person:{i}" for i in range(N_PEOPLE)] + + [f"company:{i}" for i in range(N_COMPANIES)] + + [f"city:{i}" for i in range(len(cities))] + + [f"date:{d}" for d in sorted(set(dates))] + + [f"university:{i}" for i in range(len(universities))] + + [f"major:{i}" for i in range(len(majors))] + + [f"relation:{r}" for r in RELATIONS] + ) + labels = list(rng_for(seed, 15).permutation(labels)) + token_labels = ["", "", "", ""] + labels + token = {label: i for i, label in enumerate(token_labels)} + city_tokens = np.array([token[f"city:{i}"] for i in range(len(cities))]) + prompts = np.full((N_QUERIES, 5), PAD, dtype=np.int64) + lengths = np.full(N_QUERIES, 4, dtype=np.int64) + answers = np.empty(N_QUERIES, dtype=np.int64) + relation = np.empty(N_QUERIES, dtype=np.int64) + person = np.full(N_QUERIES, -1, dtype=np.int64) + company = np.empty(N_QUERIES, dtype=np.int64) + values = [ + [token[f"company:{c}"] for c in employers], + city_tokens[defaults], + city_tokens[actual], + [token[f"date:{d}"] for d in dates], + city_tokens[birth_cities], + [token[f"university:{u}"] for u in university], + [token[f"major:{m}"] for m in major], + ] + offset = 0 + for rel, rel_values in enumerate(values): + for i, value in enumerate(rel_values): + q = offset + i + is_company = rel == 1 + subject = token[f"company:{i}" if is_company else f"person:{i}"] + prompts[q, :4] = [BOS, subject, token[f"relation:{RELATIONS[rel]}"], ANS] + answers[q], relation[q] = value, rel + company[q] = i if is_company else employers[i] + if not is_company: + person[q] = i + offset += len(rel_values) + for i in range(N_PEOPLE): + q = N_BASE + i + prompts[q] = [ + BOS, + token[f"person:{i}"], + token["relation:employer"], + token["relation:default_city"], + ANS, + ] + answers[q] = city_tokens[defaults[employers[i]]] + lengths[q], relation[q], person[q], company[q] = 5, 7, i, employers[i] + names = { + "people": person_names[:N_PEOPLE], + "people_aliases": person_names[N_PEOPLE:], + "companies": company_names[:N_COMPANIES], + "company_aliases": company_names[N_COMPANIES:], + "company_source_ids": names_rng.choice( + len(field("company")), N_COMPANIES, replace=False + ).tolist(), + "cities": cities, + "universities": universities, + "majors": majors, + "work_city_ids": work_cities.tolist(), + } + world = World( + seed, + prompts, + lengths, + answers, + relation, + person, + company, + employers, + defaults, + actual, + exceptions, + city_tokens, + token_labels, + names, + ) + audit_world(world) + return world + + +def curriculum(world, order, total_steps, batch_size=128): + if order not in {"SA", "AS"} or total_steps < 5280 or batch_size != 128: + raise ValueError("Protocol curriculum requires SA/AS, >=5280 steps and batch 128") + s = np.flatnonzero(np.isin(world.relation[:N_BASE], [0, 1])) + a = np.flatnonzero(~np.isin(world.relation[:N_BASE], [0, 1])) + parts = {} + for name, ids, repeats, purpose in (("S", s, 160, 21), ("A", a, 33, 22)): + rng = rng_for(world.seed, purpose) + parts[name] = np.concatenate([rng.permutation(ids) for _ in range(repeats)]) + assert len(parts[name]) == 337920 + rng = rng_for(world.seed, 23) + n_mix = (total_steps - 5280) * batch_size + # Exact 80:20 across each five-step block; final partial block is recorded. + n_derived = n_mix // 5 + n_atomic = n_mix - n_derived + atomic = np.concatenate([rng.permutation(N_BASE) for _ in range(n_atomic // N_BASE + 1)])[ + :n_atomic + ] + derived = N_BASE + np.tile(rng.permutation(N_PEOPLE), n_derived // N_PEOPLE + 1)[:n_derived] + mixed = np.empty(n_mix, dtype=np.int64) + derived_positions = np.arange(4, n_mix, 5) + mixed[derived_positions] = derived + is_atomic = np.ones(n_mix, dtype=bool) + is_atomic[derived_positions] = False + mixed[is_atomic] = atomic + return np.concatenate([parts[order[0]], parts[order[1]], mixed]).reshape( + total_steps, batch_size + ) + + +def paired_edit(world, support=0, k=1): + if k not in (1, 4, 16): + raise ValueError("Protocol scales are 1, 4 and 16") + rng = rng_for(world.seed, 31, support + 100 * k) + # Draw whole disjoint supports until every triple has three different defaults. + for _ in range(100000): + companies = rng.choice(N_COMPANIES, 3 * k, replace=False).reshape(k, 3) + if all(len(set(world.defaults[t])) == 3 for t in companies): + break + else: + raise RuntimeError("No valid support") + coherent, exception = world.answers.copy(), world.answers.copy() + for triple in companies: + old = world.defaults[triple] + for j, c in enumerate(triple): + next_city, alternate = old[(j + 1) % 3], old[(j + 2) % 3] + root = 2048 + c + coherent[root] = exception[root] = world.city_tokens[next_city] + members = rng.permutation(np.flatnonzero((world.employers == c) & ~world.exceptions)) + rows = 2112 + members + coherent[rows] = world.city_tokens[next_city] + exception[rows[:15]], exception[rows[15:]] = ( + world.city_tokens[next_city], + world.city_tokens[alternate], + ) + derived = N_BASE + np.flatnonzero(world.employers == c) + coherent[derived] = exception[derived] = world.city_tokens[next_city] + edit_mask = coherent != world.answers + assert np.array_equal(edit_mask, exception != world.answers) + e = np.flatnonzero(edit_mask & (np.arange(N_QUERIES) < N_BASE)) + d = np.flatnonzero(edit_mask & (np.arange(N_QUERIES) >= N_BASE)) + u = ~edit_mask + selected = np.isin(world.company, companies.ravel()) + old_exception = (world.relation == 2) & world.exceptions[np.maximum(world.person, 0)] + strata = np.full(N_QUERIES, -1, dtype=np.int64) + strata[u & selected & old_exception] = 0 + strata[u & selected & ~old_exception] = 1 + strata[u & ~selected & np.isin(world.relation, [1, 2, 7])] = 2 + strata[u & ~selected & np.isin(world.relation, [0, 3, 4, 5, 6])] = 3 + assert np.array_equal(strata >= 0, u) + assert len(e) == 93 * k and len(d) == 96 * k + assert np.array_equal( + np.bincount(coherent[e], minlength=world.vocab_size), + np.bincount(exception[e], minlength=world.vocab_size), + ) + split_rng = rng_for(world.seed, 32, support + 100 * k) + replay_pool, heldout = [], [] + for group in range(4): + ids = split_rng.permutation( + np.flatnonzero((strata == group) & (np.arange(N_QUERIES) < N_BASE)) + ) + n_test = max(1, int(np.ceil(0.2 * len(ids)))) + heldout.extend(ids[:n_test]) + replay_pool.extend(ids[n_test:]) + heldout.extend(np.flatnonzero(u & (np.arange(N_QUERIES) >= N_BASE))) + replay = split_rng.choice(replay_pool, min(4096, len(replay_pool)), replace=False) + return { + "companies": companies, + "coherent": coherent, + "exception": exception, + "E": e, + "D": d, + "strata": strata, + "replay": replay, + "heldout": np.array(sorted(heldout)), + "support": support, + "k": k, + "selection": "prespecified_unmatched", + } + + +def audit_world(world): + assert world.prompts.shape == (N_QUERIES, 5) + assert len(set(map(tuple, world.prompts))) == N_QUERIES + assert np.array_equal(np.bincount(world.employers), np.full(N_COMPANIES, 32)) + assert np.array_equal(np.unique(world.defaults, return_counts=True)[1], np.full(32, 2)) + assert world.exceptions.sum() == 128 + assert np.array_equal( + np.bincount(world.employers[world.exceptions], minlength=64), np.full(64, 2) + ) + assert np.array_equal(world.actual != world.defaults[world.employers], world.exceptions) + assert np.array_equal(world.answers[2112:4160], world.city_tokens[world.actual]) + assert np.array_equal( + world.answers[N_BASE:], world.city_tokens[world.defaults[world.employers]] + ) + for key, alias in (("people", "people_aliases"), ("companies", "company_aliases")): + names = world.names[key] + world.names[alias] + assert len(set(n.casefold().strip() for n in names)) == len(names) + baseline = {} + for relation in range(7): + values = world.answers[world.relation == relation] + answer = int(np.bincount(values, minlength=world.vocab_size).argmax()) + baseline[RELATIONS[relation]] = { + "answer_token": answer, + "accuracy": float(np.mean(values == answer)), + } + return { + "version": "bioS-Work-v1", + "world_seed": world.seed, + "source_revision": REVISION, + "base_facts": N_BASE, + "derived_queries": N_PEOPLE, + "people": N_PEOPLE, + "companies": N_COMPANIES, + "old_exceptions": 128, + "vocab_size": world.vocab_size, + "truth_sha256": array_hash(world.answers), + "queries_sha256": array_hash(world.prompts), + "majority_baseline": baseline, + "oracle_default_baseline": {"overall": 0.9375, "old_exception": 0.0, "nonexception": 1.0}, + "symbolic_truth_audit": "passed", + "natural_language_audit": "not_complete; not used in symbolic run", + } diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_direction.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_direction.py new file mode 100644 index 0000000000000000000000000000000000000000..15e8d1db07bd56a73048608a8d9dfb99e5737a7a --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_direction.py @@ -0,0 +1,617 @@ +"""Target-complete direction experiments; batched independent down-only editors. + +The randomized generalized Gauss--Newton sketch is a diagnostic solver, not +AlphaEdit/CrispEdit. Every finite hard-constraint proposal is checked against the +original parent. Training batches contain E/R only; evaluation has no gradients. +""" + +import hashlib +import itertools +import json +import time +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +NODES = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024) +ARMS = tuple( + "-".join(x) for x in itertools.product(("func", "repr"), ("soft", "hard"), ("adam", "gn")) +) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def stable_order(values, *key): + return sorted(values, key=lambda i: hashlib.sha256(f"{key}:{int(i)}".encode()).hexdigest()) + + +def load_parent(path, device): + saved = torch.load(path, map_location=device, weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])).to(device).eval() + model.load_state_dict(saved["model"]) + for parameter in model.parameters(): + parameter.requires_grad_(False) + return model + + +@dataclass +class Task: + name: str + tokens: torch.Tensor + positions: torch.Tensor + labels: torch.Tensor + old_labels: torch.Tensor + sets: dict + metadata: dict + + def manifest(self): + return { + "name": self.name, + "sets": self.sets, + "metadata": self.metadata, + "labels": self.labels.cpu().tolist(), + "old_labels": self.old_labels.cpu().tolist(), + "tokens_sha256": hashlib.sha256(self.tokens.cpu().numpy().tobytes()).hexdigest(), + } + + +def minimal_task(seed, person, kind, device, labels=None): + people = torch.arange(32, device=device).repeat_interleave(3) + relation = torch.arange(3, device=device).repeat(32) + tokens = torch.stack( + (torch.ones_like(people), 3 + people, 35 + relation, torch.full_like(people, 2)), -1 + ) + old = 38 + (people + (relation == 2)) % 3 if labels is None else labels.to(device) + old = old[:, None] + desired = old.clone() + first, second = (0, 1) if seed % 2 == 0 else (1, 0) + i, j, k = 3 * person + first, 3 * person + second, 3 * person + 2 + c = int(old[i, 0]) + assert int(old[j, 0]) == c + a, b = 38 + (c - 38 + 1) % 3, 38 + (c - 38 + 2) % 3 + desired[i] = a if kind == "coherent" else b + e, local = [i], [k] + if kind != "selective": + desired[j] = a + e.append(j) + else: + local.append(j) + remaining = stable_order([x for x in range(32) if x != person], "split", person, 271520) + + def expand(xs): + return [3 * p + r for p in xs for r in range(3)] + + sets = { + "E": e, + "R": local + expand(remaining[:15]), + "V": expand(remaining[15:23]), + "U": expand(remaining[23:]), + "local": local, + } + return Task( + f"seed-{seed}-person-{person}-{kind}", + tokens, + torch.full((96, 1), 3, device=device), + desired, + old, + sets, + {"seed": seed, "person": person, "kind": kind, "a": a, "b": b, "c": c, "pair": [i, j]}, + ) + + +class Suffix: + """Frozen prefix cached for independent weight matrices (batch axis zero).""" + + def __init__(self, model, layer, tokens, positions): + self.model, self.layer, self.positions = model, layer, positions + if tokens.ndim == 2: + tokens = tokens[None] + self.positions = positions[None] + self.n, self.q, self.t = tokens.shape + with torch.no_grad(): + flat = tokens.reshape(-1, self.t) + x = model.token(flat) + model.position(torch.arange(self.t, device=flat.device)) + for block in model.blocks[:layer]: + x = block(x) + block = model.blocks[layer] + x = x + block.attention(block.ln1(x)) + self.base = (x + block.mlp.down.bias).reshape(self.n, self.q, self.t, -1).detach() + self.z = ( + block.mlp.activation(block.mlp.up(block.ln2(x))) + .reshape(self.n, self.q, self.t, -1) + .detach() + ) + self.forward_calls = 0 + + def __call__(self, w): + self.forward_calls += 1 + n = w.shape[0] + x = self.base + torch.einsum("nqtk,ndk->nqtd", self.z.expand(n, -1, -1, -1), w) + x = x.reshape(n * self.q, self.t, -1) + for block in self.model.blocks[self.layer + 1 :]: + x = block(x) + x = self.model.ln_final(x).reshape(n, self.q, self.t, -1) + positions = self.positions.expand(n, -1, -1) + x = x.gather(2, positions[..., None].expand(-1, -1, -1, x.shape[-1])) + return F.linear(x, self.model.token.weight) + + +def candidate_configs(arm): + obj, form, solver = arm.split("-") + rates = (1e-4, 1e-3, 1e-2) if solver == "adam" else (0.1, 0.3, 1.0) + levels = ( + (0.0, 1.0, 10.0, 100.0) + if form == "soft" + else ((0.0, 1e-6, 1e-4, 1e-2) if obj == "repr" else (1e-6, 1e-4, 1e-2, 0.1)) + ) + return [ + dict(lr=lr, level=level, damping=0.01, rank=8, refresh=16, trust_fraction=0.05) + for lr, level in itertools.product(rates, levels) + ] + + +def gaussian_newton_sketch(logits, w, weights, rank, generator): + """E[U^T U] = weighted CE GGN; independent probes per example/logit. + + B = diag(sqrt(p)) - p sqrt(p)^T satisfies BB^T = diag(p)-pp^T. + Frozen probes are differentiated through logits only, never through p. + """ + probability = logits.detach().softmax(-1) + result = [] + for _ in range(rank): + noise = torch.randn(probability.shape, device=w.device, dtype=w.dtype, generator=generator) + raw = probability.sqrt() * noise + probe = raw - probability * raw.sum(-1, keepdim=True) + probe *= weights.sqrt()[..., None] / np.sqrt(rank) + result.append( + torch.autograd.grad(logits, w, probe, retain_graph=True)[0].detach().flatten(1) + ) + return torch.stack(result, 1) + + +def inverse_sketch(v, sketch, damping): + """(damping I + U^T U)^-1 v via an exact rank-r dual solve.""" + shape = v.shape + flat = v.flatten(1) + if sketch is None: + return v / damping + k = sketch @ sketch.transpose(-1, -2) + k.diagonal(dim1=-2, dim2=-1).add_(damping) + coeff = torch.linalg.solve(k.double(), (sketch @ flat[..., None]).double()).to(v.dtype) + return ((flat - (sketch.transpose(-1, -2) @ coeff)[..., 0]) / damping).reshape(shape) + + +def representation_geometry(suffix, rmask, w0): + z = suffix.z + mask = rmask[..., None].expand(-1, -1, z.shape[2]) + # Fixed sequence length; in cross tasks only positions <= last supervised index. + valid = ( + torch.arange(z.shape[2], device=z.device)[None, None, :] + <= suffix.positions.max(-1).values[..., None] + ) + mask = mask * valid + covariance = ( + torch.einsum("nqtk,nqtl,nqt->nkl", z.double(), z.double(), mask.double()) + / mask.sum((1, 2))[:, None, None] + ) + output = torch.einsum("nqtk,dk->nqtd", z, w0) + suffix.model.blocks[suffix.layer].mlp.down.bias + scale = (output.square().sum(-1) * mask).sum((1, 2)) / mask.sum((1, 2)) + covariance = covariance / scale[:, None, None].clamp_min(1e-12) + suffix.repr_factor = ( + z * (mask / (mask.sum((1, 2)) * scale).clamp_min(1e-12)[:, None, None]).sqrt()[..., None] + ) + vals, vecs = torch.linalg.eigh(covariance.double()) + threshold = vals[:, -1:] * 1e-10 + keep = vals > threshold + null = (vecs * (~keep)[:, None, :]) @ vecs.transpose(-1, -2) + return covariance.to(w0.dtype), null.to(w0.dtype), keep.sum(-1), vals + + +def batch_setup(model, layer, tasks, configs): + ids = [t.sets["E"] + t.sets["R"] for t in tasks] + assert len(set(map(len, ids))) == 1 + toks = torch.stack([t.tokens[i] for t, i in zip(tasks, ids, strict=True)]) + positions = torch.stack([t.positions[i] for t, i in zip(tasks, ids, strict=True)]) + labels = torch.stack([t.labels[i] for t, i in zip(tasks, ids, strict=True)]) + suffix = Suffix(model, layer, toks, positions) + n, q, o = labels.shape + ermask = torch.zeros((n, q), device=toks.device) + for row, task in enumerate(tasks): + ermask[row, : len(task.sets["E"])] = 1 + rmask = 1 - ermask + eweight, rweight = ermask / ermask.sum(-1, keepdim=True), rmask / rmask.sum(-1, keepdim=True) + w0 = model.blocks[layer].mlp.down.weight.detach().clone() + with torch.no_grad(): + ref = suffix(w0[None].expand(n, -1, -1)).double().log_softmax(-1) + covariance, null, ranks, spectrum = representation_geometry(suffix, rmask, w0) + return suffix, labels, eweight, rweight, ref, covariance, null, ranks, spectrum, w0 + + +def quantities(logits, w, w0, labels, eweight, rweight, ref, covariance, obj, repr_factor): + logp = logits.double().log_softmax(-1) + ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1) + le, lr = (ce * eweight).sum(-1), (ce * rweight).sum(-1) + if obj == "func": + distance = ((ref.exp() * (ref - logp)).sum(-1).mean(-1) * rweight).sum(-1).clamp_min(0) + else: + delta = w - w0 + change = torch.einsum("nqtk,ndk->nqtd", repr_factor, delta) + distance = change.double().square().sum((1, 2, 3)) + return le, lr, distance + + +@torch.no_grad() +def evaluate_weights(model, layer, tasks, weights): + result = [] + # One run at a time keeps evaluation memory bounded for the 8-layer model. + for task, w in zip(tasks, weights, strict=True): + suffix = Suffix(model, layer, task.tokens, task.positions) + logits = suffix(w[None])[0] + parent_logits = suffix(model.blocks[layer].mlp.down.weight[None])[0] + pred = logits.argmax(-1) + old_pred = parent_logits.argmax(-1) + correct = pred.eq(task.labels).all(-1) + old_correct = old_pred.eq(task.old_labels).all(-1) + if task.labels.shape[1] == 2: + # EOS must be generated after the model's own answer, not the target. + tokens = task.tokens.clone() + lengths = task.positions[:, 0] + 1 + tokens[torch.arange(len(tokens), device=tokens.device), lengths] = pred[:, 0] + generated = Suffix(model, layer, tokens, lengths[:, None])(w[None])[0, :, 0].argmax(-1) + tokens[torch.arange(len(tokens), device=tokens.device), lengths] = old_pred[:, 0] + old_generated = Suffix(model, layer, tokens, lengths[:, None])( + model.blocks[layer].mlp.down.weight[None] + )[0, :, 0].argmax(-1) + correct = pred[:, 0].eq(task.labels[:, 0]) & generated.eq(3) + old_correct = old_pred[:, 0].eq(task.old_labels[:, 0]) & old_generated.eq(3) + nll = -logits.log_softmax(-1).gather(-1, task.labels[..., None])[..., 0].mean(-1) + row = {"sets": {}, "prediction": pred[:, 0].cpu().tolist()} + for key, ids in task.sets.items(): + indices = torch.tensor(ids, device=w.device, dtype=torch.long) + known = old_correct[indices] + row["sets"][key] = { + "n": len(ids), + "correct": int(correct[indices].sum()), + "old_known": int(known.sum()), + "broken": int((known & ~correct[indices]).sum()), + "nll": float(nll[indices].mean()) if ids else None, + } + e, local, u = (row["sets"][x] for x in ("E", "local", "U")) + row["joint"] = e["correct"] == e["n"] and local["broken"] == 0 and u["broken"] == 0 + row["e_joint"] = e["correct"] == e["n"] + pair = task.metadata.get("pair", task.sets["E"][:2]) + a, b, c = (task.metadata[x] for x in ("a", "b", "c")) + row["margins"] = { + "ab": (logits[pair, 0, a] - logits[pair, 0, b]).cpu().tolist(), + "ac": (logits[pair, 0, a] - logits[pair, 0, c]).cpu().tolist(), + "bc": (logits[pair, 0, b] - logits[pair, 0, c]).cpu().tolist(), + } + result.append(row) + return result + + +def edit_batch(model, layer, tasks, arm, configs, steps, directory, evaluate=True): + """Each batch member is an independent run; no cross-run loss/normalization.""" + directory = Path(directory) + if (directory / "complete.json").exists(): + return json.loads((directory / "metrics.json").read_text()) + directory.mkdir(parents=True, exist_ok=True) + obj, form, solver = arm.split("-") + setup = batch_setup(model, layer, tasks, configs) + suffix, labels, ew, rw, ref, cov, null, ranks, spectrum, w0 = setup + device = w0.device + n = len(tasks) + w = w0[None].expand(n, -1, -1).clone().requires_grad_() + m, v = torch.zeros_like(w), torch.zeros_like(w) + lr = torch.tensor([c["lr"] for c in configs], device=device) + level = torch.tensor([c["level"] for c in configs], device=device) + damping = configs[0]["damping"] + rank, refresh = configs[0]["rank"], configs[0]["refresh"] + strict = (level == 0) & (form == "hard") & (obj == "repr") + age = torch.zeros(n, device=device, dtype=torch.long) + failed = torch.zeros_like(age) + active = torch.ones(n, device=device, dtype=torch.bool) + sketch = None + generator = torch.Generator(device=device).manual_seed(271521) + records = [ + dict(task=t.manifest(), config=c, arm=arm, timeline=[]) + for t, c in zip(tasks, configs, strict=True) + ] + traces, checkpoints = [], {} + pair_columns = torch.tensor( + [[(t.sets["E"] + t.sets["R"]).index(i) for i in t.metadata["pair"]] for t in tasks], + device=device, + ) + answers_a = torch.tensor([t.metadata["a"] for t in tasks], device=device) + answers_b = torch.tensor([t.metadata["b"] for t in tasks], device=device) + rows = torch.arange(n, device=device) + counters = dict( + forward_batches=0, + backward_batches=0, + ggn_vjps=0, + line_search_batches=0, + covariance_eigh=1, + train_examples_per_batch=labels.shape[1], + batch_runs=n, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.monotonic() + limit = 11 * steps + 10 + for attempt in range(limit + 1): + if ( + attempt == 0 + or (attempt in NODES and attempt <= steps) + or not active.any() + or attempt == limit + ): + if device.type == "cuda": + torch.cuda.synchronize(device) + metrics = ( + evaluate_weights(model, layer, tasks, w.detach()) + if evaluate + else [dict() for _ in tasks] + ) + for j, metric in enumerate(metrics): + records[j]["timeline"].append( + dict( + attempt=attempt, + accepted=int(age[j]), + seconds=time.monotonic() - start, + **metric, + ) + ) + checkpoints[str(attempt)] = w.detach().cpu().clone() + if attempt and (not active.any() or attempt == limit): + break + if attempt >= steps and torch.all((age >= steps) | ~active): + break + logits = suffix(w) + le, lretain, distance = quantities( + logits, w, w0, labels, ew, rw, ref, cov, obj, suffix.repr_factor + ) + pair_gradients = None + if attempt in NODES: + pair_margin = torch.stack( + [ + logits[rows, pair_columns[:, i], 0, answers_a] + - logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + pair_gradients = torch.stack( + [ + torch.autograd.grad(pair_margin[:, i].sum(), w, retain_graph=True)[0].detach() + for i in range(2) + ], + 1, + ) + counters["backward_batches"] += 2 + data_loss = le + lretain + objective = data_loss + level * distance if form == "soft" else data_loss + if solver == "gn" and (sketch is None or attempt % refresh == 0 or failed.any()): + weights = ((ew + rw) / labels.shape[2])[..., None].expand_as(labels) + if form == "soft" and obj == "func": + weights = ((ew + (1 + level[:, None]) * rw) / labels.shape[2])[..., None].expand_as( + labels + ) + sketch = gaussian_newton_sketch(logits, w, weights, rank, generator) + if strict.any(): + projected = (sketch.reshape(n, rank, *w0.shape) @ null[:, None]).flatten(2) + sketch = torch.where(strict[:, None, None], projected, sketch) + counters["ggn_vjps"] += rank + g = torch.autograd.grad(objective.sum(), w, retain_graph=form == "hard")[0] + counters["backward_batches"] += 1 + if form == "hard": + a = torch.autograd.grad(distance.sum(), w)[0] + counters["backward_batches"] += 1 + else: + a = None + if solver == "adam": + m_new = 0.9 * m + 0.1 * g + v_new = 0.999 * v + 0.001 * g.square() + t = (age + 1).float()[:, None, None] + raw = -(m_new / (1 - 0.9**t)) / ((v_new / (1 - 0.999**t)).sqrt() + 1e-8) + proposal = lr[:, None, None] * raw + else: + if strict.any(): + g = torch.where(strict[:, None, None], g @ null, g) + if obj == "repr" and form == "soft": + # Exact representation Hessian plus damped sketched data GGN, CG. + def hv(x, sketch=sketch): + flat = x.flatten(1) + return ( + damping * x + + (sketch.transpose(-1, -2) @ (sketch @ flat[..., None]))[ + ..., 0 + ].reshape_as(x) + + 2 * level[:, None, None] * (x @ cov) + ) + + direction = torch.zeros_like(g) + residual, search = -g.clone(), -g.clone() + rr = residual.square().sum((-1, -2)) + for _ in range(16): + hp = hv(search) + alpha = rr / (search * hp).sum((-1, -2)).clamp_min(1e-30) + direction += alpha[:, None, None] * search + residual -= alpha[:, None, None] * hp + new_rr = residual.square().sum((-1, -2)) + search = residual + (new_rr / rr.clamp_min(1e-30))[:, None, None] * search + rr = new_rr + proposal = lr[:, None, None] * direction + else: + proposal = -lr[:, None, None] * inverse_sketch(g, sketch, damping) + # Fixed Euclidean trust radius, no hidden per-run gradient scaling. + radius = configs[0]["trust_fraction"] * w0.norm() + proposal *= (radius / proposal.flatten(1).norm(dim=1).clamp_min(1e-12)).clamp(max=1)[ + :, None, None + ] + m_new, v_new = m, v + if form == "hard": + if strict.any(): + proposal = torch.where(strict[:, None, None], proposal @ null, proposal) + metric_a = a if solver == "adam" else inverse_sketch(a, sketch, damping) + # Sequential quadratic subproblem with a linearized ORIGINAL distance. + # Interior restoration avoids accumulating positive second-order drift. + slack = torch.where(distance > 0.8 * level, -0.05 * level, 0.8 * (level - distance)) + excess = (a * proposal).sum((-1, -2)) - slack + correction = excess.clamp_min(0) / (a * metric_a).sum((-1, -2)).clamp_min(1e-20) + adjusted = proposal - correction[:, None, None] * metric_a + proposal = torch.where(strict[:, None, None], proposal, adjusted).to(w.dtype) + proposal = torch.where(active[:, None, None], proposal, torch.zeros_like(proposal)) + accepted = torch.zeros_like(active) + chosen = w.detach().clone() + chosen_logits = logits.detach().clone() + picked_scale = torch.zeros(n, device=device) + actual_d = distance.detach().clone() + for backtrack in range(10): + with torch.no_grad(): + candidate = w.detach() + (0.5**backtrack) * proposal + if strict.any(): + exact = w0 + (candidate - w0) @ null + candidate = torch.where(strict[:, None, None], exact, candidate) + candidate_logits = suffix(candidate) + cle, clr, cd = quantities( + candidate_logits, + candidate, + w0, + labels, + ew, + rw, + ref, + cov, + obj, + suffix.repr_factor, + ) + co = cle + clr + level * cd if form == "soft" else cle + clr + tolerance = torch.where(strict, torch.full_like(level, 1e-10), 1e-8 + 1e-5 * level) + feasible = torch.ones_like(active) if form == "soft" else cd <= level + tolerance + descent = co <= objective.detach() + 1e-7 if solver == "gn" else torch.isfinite(co) + if form == "hard" and solver == "gn": + restoration = ( + (distance.detach() > 0.8 * level) + & (cd < distance.detach() - 1e-4 * level) + & (co <= 1.05 * objective.detach() + 1e-6) + & ~strict + ) + descent = descent | restoration + good = feasible & descent & active & ~accepted & torch.isfinite(co) + chosen[good] = candidate[good] + chosen_logits[good] = candidate_logits[good] + actual_d[good] = cd[good] + picked_scale[good] = 0.5**backtrack + accepted |= good + counters["line_search_batches"] += 1 + if torch.all(accepted | ~active): + break + delta = chosen - w.detach() + if pair_gradients is not None: + predicted = (pair_gradients * delta[:, None]).sum((-1, -2)) + updated_margin = torch.stack( + [ + chosen_logits[rows, pair_columns[:, i], 0, answers_a] + - chosen_logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + observed = updated_margin - pair_margin.detach() + flat = pair_gradients.flatten(2) + kernel = flat @ flat.transpose(-1, -2) + for j in range(n): + records[j]["timeline"][-1]["local_step"] = { + "kernel": kernel[j].cpu().tolist(), + "predicted_margin_change": predicted[j].cpu().tolist(), + "observed_margin_change": observed[j].cpu().tolist(), + "actual_delta_norm": float(delta[j].norm()), + } + + with torch.no_grad(): + w.copy_(chosen) + m.copy_(torch.where(accepted[:, None, None], m_new, m)) + v.copy_(torch.where(accepted[:, None, None], v_new, v)) + age += accepted + failed = torch.where(accepted, torch.zeros_like(failed), failed + 1) + active = (age < steps) & (failed < 10) + traces.append( + torch.stack( + ( + le.detach(), + lretain.detach(), + distance.detach(), + actual_d, + delta.flatten(1).norm(dim=1), + picked_scale, + accepted.float(), + age.float(), + ), + -1, + ).cpu() + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start + counters["forward_batches"] = suffix.forward_calls + counters["elapsed_seconds_including_evaluation"] = elapsed + for j, record in enumerate(records): + record.update( + accepted=int(age[j]), + failed=bool(failed[j] >= 10), + elapsed_batch_seconds=elapsed, + representation_rank=int(ranks[j]), + representation_spectrum=spectrum[j].cpu().tolist(), + ) + write_json(directory / "metrics.json", records) + torch.save( + dict( + weights=w.detach().cpu(), + parent=w0.cpu(), + checkpoints=checkpoints, + m=m.cpu(), + v=v.cpu(), + age=age.cpu(), + sketch=None if sketch is None else sketch.cpu(), + generator_state=generator.get_state(), + arm=arm, + configs=configs, + ), + directory / "state.pt", + ) + np.savez_compressed( + directory / "steps.npz", + values=torch.stack(traces).numpy(), + columns=np.array( + [ + "E_CE", + "R_CE", + "distance_before", + "distance_after", + "delta_norm", + "backtrack_scale", + "accepted", + "accepted_count", + ] + ), + ) + write_json(directory / "cost.json", counters) + write_json( + directory / "complete.json", + dict( + files={ + name: digest(directory / name) + for name in ("metrics.json", "state.pt", "steps.npz", "cost.json") + } + ), + ) + return records diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_direction_cross.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_direction_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..27051c00db64d66676d95dc16a1351dff5d797a6 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_direction_cross.py @@ -0,0 +1,149 @@ +"""Target-complete edits on the original two-chain, eight-layer task.""" + +import numpy as np +import torch + +from .bios_cross import edit_pair, make_cross_world +from .bios_cross_train import tensor_queries +from .bios_direction import ROOT, Task, stable_order + +CROSS_ARMS = ("func-soft-adam", "repr-hard-adam", "func-hard-gn", "func-soft-gn") + + +def cross_tasks(world_id, seed, device): + world = make_cross_world(world_id, ROOT / "data/bios-organization-v1") + tasks = [] + for chain in (0, 1): + edits = edit_pair(world, chain) + for group_index, group in enumerate(edits["groups"]): + members = np.flatnonzero(world.memberships[chain] == group) + eligible = [ + int(p) + for p in members + if not world.exceptions[chain, p] + and world.derived_ids[chain, p] in world.heldout_ids[chain] + ] + person = stable_order(eligible, "focal", world_id, chain, int(group))[0] + root, actual = int(world.root_ids[chain, group]), int(world.actual_ids[chain, person]) + c = int(world.answers[root]) + a = int( + world.city_tokens[world.defaults[chain, edits["groups"][(group_index + 1) % 3]]] + ) + b = int( + world.city_tokens[world.defaults[chain, edits["groups"][(group_index + 2) % 3]]] + ) + assert len({a, b, c}) == 3 and int(world.answers[actual]) == c + e = [root, actual] + d = world.derived_ids[chain, members].tolist() + focal = int(world.derived_ids[chain, person]) + assert focal in world.heldout_ids[chain] + membership = int(world.membership_ids[chain, person]) + local = np.flatnonzero( + (world.person == person) & (np.arange(len(world.answers)) < world.n_base) + ).tolist() + local = [i for i in local if i not in e + [membership]] + # Near facts exclude all direct edits and all affected compositions. + near_pool = list( + set( + world.actual_ids[chain, members].tolist() + + world.membership_ids[chain, members].tolist() + ) + - set(e + [membership] + local) + ) + near = stable_order(near_pool, "near", world_id, chain, int(group))[:48] + reserved = set(e + d + local + near + [membership]) + base_pool = stable_order( + [i for i in range(world.n_base) if i not in reserved], + "base", + world_id, + chain, + int(group), + ) + r = [membership] + base_pool[:47] + v = base_pool[47:95] + far_base = base_pool[95:175] + other_d = stable_order( + [int(i) for i in world.heldout_ids.flatten() if i not in reserved], + "far-d", + world_id, + chain, + int(group), + )[:16] + far = far_base + other_d + u = local + near + far + included = e + r + v + u + d + assert len(included) == len(set(included)) + mapping = {old: new for new, old in enumerate(included)} + sets = { + "E": e, + "R": r, + "V": v, + "U": u, + "local": local, + "U_near": near, + "U_far": far, + "D": d, + "D_heldout": [i for i in d if i in world.heldout_ids[chain]], + "D_focal": [focal], + } + for kind in ("coherent", "independent"): + truth = world.answers.copy() + truth[root], truth[actual], truth[d] = a, a if kind == "coherent" else b, a + assert set(np.flatnonzero(truth != world.answers)) == set(e + d) + data = tensor_queries(world, device, truth) + old = torch.stack( + [ + torch.as_tensor(world.answers[included], device=device), + torch.full((len(included),), 3, device=device), + ], + -1, + ) + tasks.append( + Task( + f"world-{world_id}-seed-{seed}-chain-{chain}-group-{int(group)}-{kind}", + data["tokens"][included], + data["positions"][included], + data["labels"][included], + old, + {k: [mapping[i] for i in ids] for k, ids in sets.items()}, + dict( + world=world_id, + seed=seed, + chain=chain, + group=int(group), + group_index=group_index, + person=person, + kind=kind, + a=a, + b=b, + c=c, + pair=[mapping[actual], mapping[root]], + original_ids=included, + ), + ) + ) + return tasks + + +def bounded_representation_geometry(suffix, rmask, w0): + """Same FP64 covariance as the core; avoid a huge four-axis outer product.""" + z = suffix.z + mask = rmask[..., None].expand(-1, -1, z.shape[2]) + valid = ( + torch.arange(z.shape[2], device=z.device)[None, None, :] + <= suffix.positions.max(-1).values[..., None] + ) + mask = mask * valid + flat = z.double().flatten(1, 2) + covariance = flat.transpose(-1, -2) @ (flat * mask.flatten(1)[..., None]) + covariance = covariance / mask.sum((1, 2))[:, None, None] + output = torch.einsum("nqtk,dk->nqtd", z, w0) + suffix.model.blocks[suffix.layer].mlp.down.bias + scale = (output.square().sum(-1) * mask).sum((1, 2)) / mask.sum((1, 2)) + covariance = covariance / scale[:, None, None].clamp_min(1e-12) + suffix.repr_factor = ( + z * (mask / (mask.sum((1, 2)) * scale).clamp_min(1e-12)[:, None, None]).sqrt()[..., None] + ) + vals, vecs = torch.linalg.eigh(covariance) + keep = vals > vals[:, -1:] * 1e-10 + null = (vecs * (~keep)[:, None, :]) @ vecs.transpose(-1, -2) + return covariance.to(w0.dtype), null.to(w0.dtype), keep.sum(-1), vals diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_direction_formation.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_direction_formation.py new file mode 100644 index 0000000000000000000000000000000000000000..96a3aa141c344b0fea47995c861792eb5d95398a --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_direction_formation.py @@ -0,0 +1,241 @@ +"""Prospective learning-rate interventions and factor measurements on new worlds.""" + +import copy +import json +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_direction import ROOT, digest, edit_batch, minimal_task +from .bios_direction_cross import CROSS_ARMS +from .bios_model import CausalLM, ModelConfig + +TRAIN_NODES = (0, 8, 32, 128, 256, 512, 1024) +TRAIN_ARMS = ("baseline", "qk-0.25", "qk-4", "up-0.25", "up-4", "post-0.25", "post-4") + + +def world_labels(world): + rng = np.random.default_rng(np.random.SeedSequence([271523, world])) + r1 = np.r_[ + np.arange(3), rng.permutation(np.r_[np.repeat(0, 10), np.repeat(1, 10), np.repeat(2, 9)]) + ] + exceptions = np.concatenate( + [ + rng.choice(np.flatnonzero((r1 == v) & (np.arange(32) >= 3)), n, replace=False) + for v, n in enumerate((3, 3, 2)) + ] + ) + r2 = r1.copy() + r2[exceptions] = np.roll(r1[exceptions], -3) + r3 = rng.permutation(np.arange(32) % 3) + labels = np.stack((r1, r2, r3), -1) + assert (r1 == r2).sum() == 24 and np.all(r1[:3] == r2[:3]) + for col in labels.T: + assert np.ptp(np.bincount(col, minlength=3)) <= 1 + return torch.tensor(labels.flatten() + 38, dtype=torch.long) + + +def optimizer_views(model): + """Separate Q/K and V learning rates without changing forward computation. + + Optimizer leaf views share parameter storage; their gradients are assigned + from the original model's autograd gradients. A frozen view gets grad=None, + so its optimizer moments and step count genuinely stop. + """ + groups = {k: [] for k in ("qk", "up", "post", "other")} + mapping = [] + for name, p in model.named_parameters(): + if name.startswith("blocks.0.attention.qkv."): + pieces = [("qk", slice(0, 128)), ("other", slice(128, None))] + else: + group = ( + "up" + if name.startswith("blocks.0.mlp.up.") + else ("post" if name.startswith("blocks.1.") else "other") + ) + pieces = [(group, slice(None))] + for group, region in pieces: + view = nn.Parameter(p.detach()[region]) + groups[group].append(view) + mapping.append((group, p, region, view)) + optimizer = torch.optim.AdamW( + [dict(params=params, lr=0.001, name=name) for name, params in groups.items()], + weight_decay=0.1, + foreach=True, + ) + return optimizer, mapping + + +def multiplier(arm, step): + if arm == "baseline": + return None, 1.0 + group, mode = arm.split("-") + if mode == "freezeearly": + return group, 0.0 if step < 256 else 1.0 + if mode == "freezelate": + return group, 0.0 if step >= 768 else 1.0 + if mode == "freezeall": + return group, 0.0 + return group, float(mode) if step < 256 else 1.0 + + +def factor_measure(model, seed, labels, device): + records = [] + for person in (0, 1, 2): + task = minimal_task(seed, person, "independent", device, labels) + ids = task.metadata["pair"] + captured = {} + + def capture(module, inputs, output, captured=captured): + captured.update(z=inputs[0], h=output) + + handle = model.blocks[0].mlp.down.register_forward_hook(capture) + tokens = task.tokens[ids] + logits = model(tokens)[:, -1] + handle.remove() + a, b, c = (task.metadata[x] for x in ("a", "b", "c")) + margin = logits[:, a] - logits[:, b] + gradients = [] + deltas = [] + for i in range(2): + g, d = torch.autograd.grad( + margin[i], (model.blocks[0].mlp.down.weight, captured["h"]), retain_graph=True + ) + gradients.append(g.detach()) + deltas.append(d[i].detach()) + g = torch.stack(gradients).flatten(1) + kernel = g @ g.T + z = captured["z"].detach() + d = torch.stack(deltas) + rebuilt = torch.einsum("itd,itk->idk", d, z).flatten(1) + error = (rebuilt - g).norm() / g.norm().clamp_min(1e-20) + common = float((kernel[0, 0] + kernel[1, 1] + 2 * kernel[0, 1]) / 2) + difference = float((kernel[0, 0] + kernel[1, 1] - 2 * kernel[0, 1]) / 2) + # Actual GELU slope at the preactivation, not a binary activation mask. + pre = model.blocks[0].mlp.up + activations = {} + + def pre_hook(module, inputs, output, activations=activations): + activations.update(input=inputs[0], pre=output) + + handle = pre.register_forward_hook(pre_hook) + model(tokens) + handle.remove() + y = activations["pre"] + gate = torch.autograd.grad(model.blocks[0].mlp.activation(y).sum(), y)[0].detach() + + def cosine(x): + return float(F.cosine_similarity(x[0].flatten(), x[1].flatten(), dim=0)) + + records.append( + dict( + person=person, + common=common, + difference=difference, + ratio=difference / max(common, 1e-20), + mixing=float((kernel[0, 0] - kernel[1, 1]) / 2), + eigenvalues=torch.linalg.eigvalsh(kernel.double()).tolist(), + feature_cos=cosine(z), + downstream_cos=cosine(d), + gate_cos=cosine(gate), + relation_input_difference=float( + (activations["input"][0] - activations["input"][1]).detach().norm() + ), + feature_difference=float((z[0] - z[1]).norm()), + gate_difference=float((gate[0] - gate[1]).norm()), + reconstruction_error=float(error), + new_target_nll=float(F.cross_entropy(logits, task.labels[ids, 0]).detach()), + margin_ab=margin.detach().tolist(), + kernel=kernel.detach().cpu().tolist(), + ) + ) + return records + + +def train(world, seed, arm, device, out): + out = Path(out) + if (out / "complete.json").exists(): + return + out.mkdir(parents=True, exist_ok=True) + labels = world_labels(world).to(device) + torch.manual_seed(seed) + model = CausalLM(ModelConfig(41, width=64, layers=2, heads=2, context=8)).to(device) + tokens = minimal_task(seed, 0, "independent", device, labels).tokens + opt, mapping = optimizer_views(model) + timeline = [] + for step in range(1025): + if step in TRAIN_NODES: + with torch.no_grad(): + logits = model(tokens)[:, -1] + acc = float(logits.argmax(-1).eq(labels).float().mean()) + loss = float(F.cross_entropy(logits, labels)) + factors = factor_measure(model, seed, labels, device) + timeline.append(dict(step=step, accuracy=acc, loss=loss, factors=factors)) + torch.save( + dict( + model={k: v.detach().cpu() for k, v in model.state_dict().items()}, + config=model.config_dict(), + optimizer=opt.state_dict(), + step=step, + world=world, + seed=seed, + arm=arm, + labels=labels.cpu(), + ), + out / f"model-{step}.pt", + ) + if step == 1024: + break + model.zero_grad(set_to_none=True) + opt.zero_grad(set_to_none=True) + loss = F.cross_entropy(model(tokens)[:, -1], labels) + loss.backward() + selected, factor = multiplier(arm, step) + for group in opt.param_groups: + group["lr"] = 0.001 * (factor if group["name"] == selected else 1.0) + for group, p, region, view in mapping: + view.grad = None if group == selected and factor == 0 else p.grad[region] + opt.step() + write_json(out / "learning.json", timeline) + write_json( + out / "complete.json", + dict( + world=world, + seed=seed, + arm=arm, + files={p.name: digest(p) for p in out.iterdir() if p.suffix in (".json", ".pt")}, + ), + ) + + +def edit_parent(world, seed, train_arm, device, out, edit_arms=CROSS_ARMS, steps=1024): + from .bios_direction import load_parent + + out = Path(out) + saved = torch.load(out / "model-1024.pt", map_location="cpu", weights_only=False) + labels = saved["labels"].to(device) + model = load_parent(out / "model-1024.pt", device) + selected = json.loads( + (ROOT / "docs/development-artifacts/direction-v1/selected.json").read_text() + )["choices"] + tasks = [ + minimal_task(seed, p, k, device, labels) + for p in (0, 1, 2) + for k in ("coherent", "independent") + ] + for task in tasks: + task.metadata.update(world=world, train_arm=train_arm) + for arm in edit_arms: + edit_batch( + model, + 0, + tasks, + arm, + [copy.deepcopy(selected[arm]) for _ in tasks], + steps, + out / "edits" / arm, + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_direction_refresh.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_direction_refresh.py new file mode 100644 index 0000000000000000000000000000000000000000..5f48462e2c66886ef8e483fa7e48986d075ad3fb --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_direction_refresh.py @@ -0,0 +1,355 @@ +"""V1 numerical audit: refresh curvature per trajectory and freeze idle counters. + +This keeps the original randomized batched probe stream, finite objectives, +constraints and solver settings. Unused fresh probe rows are discarded rather +than changing another trajectory's sketch. Frozen v1 artifacts are untouched. +""" + +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_data import write_json +from .bios_direction import ( + NODES, + batch_setup, + digest, + evaluate_weights, + gaussian_newton_sketch, + inverse_sketch, + quantities, +) + + +def refresh_mask(active, failed, attempt, refresh, missing): + due = missing or attempt % refresh == 0 + return active & (torch.full_like(active, due) | (failed > 0)) + + +def update_failure_counts(active, accepted, failed): + return torch.where(active, torch.where(accepted, torch.zeros_like(failed), failed + 1), failed) + + +def edit_batch(model, layer, tasks, arm, configs, steps, directory, evaluate=True): + """Each batch member is an independent run; no cross-run loss/normalization.""" + directory = Path(directory) + if (directory / "complete.json").exists(): + return json.loads((directory / "metrics.json").read_text()) + directory.mkdir(parents=True, exist_ok=True) + obj, form, solver = arm.split("-") + setup = batch_setup(model, layer, tasks, configs) + suffix, labels, ew, rw, ref, cov, null, ranks, spectrum, w0 = setup + device = w0.device + n = len(tasks) + w = w0[None].expand(n, -1, -1).clone().requires_grad_() + m, v = torch.zeros_like(w), torch.zeros_like(w) + lr = torch.tensor([c["lr"] for c in configs], device=device) + level = torch.tensor([c["level"] for c in configs], device=device) + damping = configs[0]["damping"] + rank, refresh = configs[0]["rank"], configs[0]["refresh"] + strict = (level == 0) & (form == "hard") & (obj == "repr") + age = torch.zeros(n, device=device, dtype=torch.long) + failed = torch.zeros_like(age) + active = torch.ones(n, device=device, dtype=torch.bool) + sketch = None + generator = torch.Generator(device=device).manual_seed(271521) + records = [ + dict(task=t.manifest(), config=c, arm=arm, timeline=[]) + for t, c in zip(tasks, configs, strict=True) + ] + traces, checkpoints = [], {} + pair_columns = torch.tensor( + [[(t.sets["E"] + t.sets["R"]).index(i) for i in t.metadata["pair"]] for t in tasks], + device=device, + ) + answers_a = torch.tensor([t.metadata["a"] for t in tasks], device=device) + answers_b = torch.tensor([t.metadata["b"] for t in tasks], device=device) + rows = torch.arange(n, device=device) + counters = dict( + forward_batches=0, + backward_batches=0, + ggn_vjps=0, + line_search_batches=0, + covariance_eigh=1, + train_examples_per_batch=labels.shape[1], + batch_runs=n, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.monotonic() + limit = 11 * steps + 10 + for attempt in range(limit + 1): + if ( + attempt == 0 + or (attempt in NODES and attempt <= steps) + or not active.any() + or attempt == limit + ): + if device.type == "cuda": + torch.cuda.synchronize(device) + metrics = ( + evaluate_weights(model, layer, tasks, w.detach()) + if evaluate + else [dict() for _ in tasks] + ) + for j, metric in enumerate(metrics): + records[j]["timeline"].append( + dict( + attempt=attempt, + accepted=int(age[j]), + seconds=time.monotonic() - start, + **metric, + ) + ) + checkpoints[str(attempt)] = w.detach().cpu().clone() + if attempt and (not active.any() or attempt == limit): + break + if attempt >= steps and torch.all((age >= steps) | ~active): + break + logits = suffix(w) + le, lretain, distance = quantities( + logits, w, w0, labels, ew, rw, ref, cov, obj, suffix.repr_factor + ) + pair_gradients = None + if attempt in NODES: + pair_margin = torch.stack( + [ + logits[rows, pair_columns[:, i], 0, answers_a] + - logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + pair_gradients = torch.stack( + [ + torch.autograd.grad(pair_margin[:, i].sum(), w, retain_graph=True)[0].detach() + for i in range(2) + ], + 1, + ) + counters["backward_batches"] += 2 + data_loss = le + lretain + objective = data_loss + level * distance if form == "soft" else data_loss + refresh_rows = refresh_mask(active, failed, attempt, refresh, sketch is None) + if solver == "gn" and refresh_rows.any(): + weights = ((ew + rw) / labels.shape[2])[..., None].expand_as(labels) + if form == "soft" and obj == "func": + weights = ((ew + (1 + level[:, None]) * rw) / labels.shape[2])[..., None].expand_as( + labels + ) + fresh = gaussian_newton_sketch(logits, w, weights, rank, generator) + if strict.any(): + projected = (fresh.reshape(n, rank, *w0.shape) @ null[:, None]).flatten(2) + fresh = torch.where(strict[:, None, None], projected, fresh) + sketch = ( + fresh if sketch is None else torch.where(refresh_rows[:, None, None], fresh, sketch) + ) + counters["ggn_vjps"] += rank + g = torch.autograd.grad(objective.sum(), w, retain_graph=form == "hard")[0] + counters["backward_batches"] += 1 + if form == "hard": + a = torch.autograd.grad(distance.sum(), w)[0] + counters["backward_batches"] += 1 + else: + a = None + if solver == "adam": + m_new = 0.9 * m + 0.1 * g + v_new = 0.999 * v + 0.001 * g.square() + t = (age + 1).float()[:, None, None] + raw = -(m_new / (1 - 0.9**t)) / ((v_new / (1 - 0.999**t)).sqrt() + 1e-8) + proposal = lr[:, None, None] * raw + else: + if strict.any(): + g = torch.where(strict[:, None, None], g @ null, g) + if obj == "repr" and form == "soft": + # Exact representation Hessian plus damped sketched data GGN, CG. + def hv(x, sketch=sketch): + flat = x.flatten(1) + return ( + damping * x + + (sketch.transpose(-1, -2) @ (sketch @ flat[..., None]))[ + ..., 0 + ].reshape_as(x) + + 2 * level[:, None, None] * (x @ cov) + ) + + direction = torch.zeros_like(g) + residual, search = -g.clone(), -g.clone() + rr = residual.square().sum((-1, -2)) + for _ in range(16): + hp = hv(search) + alpha = rr / (search * hp).sum((-1, -2)).clamp_min(1e-30) + direction += alpha[:, None, None] * search + residual -= alpha[:, None, None] * hp + new_rr = residual.square().sum((-1, -2)) + search = residual + (new_rr / rr.clamp_min(1e-30))[:, None, None] * search + rr = new_rr + proposal = lr[:, None, None] * direction + else: + proposal = -lr[:, None, None] * inverse_sketch(g, sketch, damping) + # Fixed Euclidean trust radius, no hidden per-run gradient scaling. + radius = configs[0]["trust_fraction"] * w0.norm() + proposal *= (radius / proposal.flatten(1).norm(dim=1).clamp_min(1e-12)).clamp(max=1)[ + :, None, None + ] + m_new, v_new = m, v + if form == "hard": + if strict.any(): + proposal = torch.where(strict[:, None, None], proposal @ null, proposal) + metric_a = a if solver == "adam" else inverse_sketch(a, sketch, damping) + # Sequential quadratic subproblem with a linearized ORIGINAL distance. + # Interior restoration avoids accumulating positive second-order drift. + slack = torch.where(distance > 0.8 * level, -0.05 * level, 0.8 * (level - distance)) + excess = (a * proposal).sum((-1, -2)) - slack + correction = excess.clamp_min(0) / (a * metric_a).sum((-1, -2)).clamp_min(1e-20) + adjusted = proposal - correction[:, None, None] * metric_a + proposal = torch.where(strict[:, None, None], proposal, adjusted).to(w.dtype) + proposal = torch.where(active[:, None, None], proposal, torch.zeros_like(proposal)) + accepted = torch.zeros_like(active) + chosen = w.detach().clone() + chosen_logits = logits.detach().clone() + picked_scale = torch.zeros(n, device=device) + actual_d = distance.detach().clone() + for backtrack in range(10): + with torch.no_grad(): + candidate = w.detach() + (0.5**backtrack) * proposal + if strict.any(): + exact = w0 + (candidate - w0) @ null + candidate = torch.where(strict[:, None, None], exact, candidate) + candidate_logits = suffix(candidate) + cle, clr, cd = quantities( + candidate_logits, + candidate, + w0, + labels, + ew, + rw, + ref, + cov, + obj, + suffix.repr_factor, + ) + co = cle + clr + level * cd if form == "soft" else cle + clr + tolerance = torch.where(strict, torch.full_like(level, 1e-10), 1e-8 + 1e-5 * level) + feasible = torch.ones_like(active) if form == "soft" else cd <= level + tolerance + descent = co <= objective.detach() + 1e-7 if solver == "gn" else torch.isfinite(co) + if form == "hard" and solver == "gn": + restoration = ( + (distance.detach() > 0.8 * level) + & (cd < distance.detach() - 1e-4 * level) + & (co <= 1.05 * objective.detach() + 1e-6) + & ~strict + ) + descent = descent | restoration + good = feasible & descent & active & ~accepted & torch.isfinite(co) + chosen[good] = candidate[good] + chosen_logits[good] = candidate_logits[good] + actual_d[good] = cd[good] + picked_scale[good] = 0.5**backtrack + accepted |= good + counters["line_search_batches"] += 1 + if torch.all(accepted | ~active): + break + delta = chosen - w.detach() + if pair_gradients is not None: + predicted = (pair_gradients * delta[:, None]).sum((-1, -2)) + updated_margin = torch.stack( + [ + chosen_logits[rows, pair_columns[:, i], 0, answers_a] + - chosen_logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + observed = updated_margin - pair_margin.detach() + flat = pair_gradients.flatten(2) + kernel = flat @ flat.transpose(-1, -2) + for j in range(n): + records[j]["timeline"][-1]["local_step"] = { + "kernel": kernel[j].cpu().tolist(), + "predicted_margin_change": predicted[j].cpu().tolist(), + "observed_margin_change": observed[j].cpu().tolist(), + "actual_delta_norm": float(delta[j].norm()), + } + + with torch.no_grad(): + w.copy_(chosen) + m.copy_(torch.where(accepted[:, None, None], m_new, m)) + v.copy_(torch.where(accepted[:, None, None], v_new, v)) + age += accepted + failed = update_failure_counts(active, accepted, failed) + active = (age < steps) & (failed < 10) + traces.append( + torch.stack( + ( + le.detach(), + lretain.detach(), + distance.detach(), + actual_d, + delta.flatten(1).norm(dim=1), + picked_scale, + accepted.float(), + age.float(), + ), + -1, + ).cpu() + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start + counters["forward_batches"] = suffix.forward_calls + counters["elapsed_seconds_including_evaluation"] = elapsed + for j, record in enumerate(records): + record.update( + accepted=int(age[j]), + failed=bool(failed[j] >= 10 and age[j] < steps), + elapsed_batch_seconds=elapsed, + representation_rank=int(ranks[j]), + representation_spectrum=spectrum[j].cpu().tolist(), + ) + write_json(directory / "metrics.json", records) + torch.save( + dict( + weights=w.detach().cpu(), + parent=w0.cpu(), + checkpoints=checkpoints, + m=m.cpu(), + v=v.cpu(), + age=age.cpu(), + sketch=None if sketch is None else sketch.cpu(), + generator_state=generator.get_state(), + arm=arm, + configs=configs, + ), + directory / "state.pt", + ) + np.savez_compressed( + directory / "steps.npz", + values=torch.stack(traces).numpy(), + columns=np.array( + [ + "E_CE", + "R_CE", + "distance_before", + "distance_after", + "delta_norm", + "backtrack_scale", + "accepted", + "accepted_count", + ] + ), + ) + write_json(directory / "cost.json", counters) + write_json( + directory / "complete.json", + dict( + files={ + name: digest(directory / name) + for name in ("metrics.json", "state.pt", "steps.npz", "cost.json") + } + ), + ) + return records diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_edit.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..685a33d6157d090f0afdfaa38b5c2d731eda4d0e --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_edit.py @@ -0,0 +1,381 @@ +"""Fixed-budget development edits with held-out retention and full-answer scoring.""" + +import argparse +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_branch import attach_branch, build_bases, remove_branch +from .bios_data import N_BASE, N_QUERIES, load_world, paired_edit, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_train import code_fingerprint, evaluate, precision, tensor_data + +EDIT_CHECKPOINTS = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512) + + +def score_edit(world, pair, target, arrays, old_correct): + correct = arrays["correct"] + e, d = pair["E"], pair["D"] + root = e[world.relation[e] == 1] + members = e[world.relation[e] == 2] + unseen = np.zeros(N_QUERIES, dtype=bool) + unseen[pair["heldout"]] = True + retention, full_retention = {}, {} + for g in range(4): + ids = (pair["strata"] == g) & old_correct + full_retention[str(g)] = { + "known": int(ids.sum()), + "broken": int((ids & ~correct).sum()), + "rate": float((~correct[ids]).mean()) if ids.any() else None, + } + held = ids & unseen + retention[str(g)] = { + "known": int(held.sum()), + "broken": int((held & ~correct).sum()), + "rate": float((~correct[held]).mean()) if held.any() else None, + } + for name, base in (("2_base", True), ("2_derived", False)): + ids = ( + (pair["strata"] == 2) & old_correct & unseen & ((np.arange(N_QUERIES) < N_BASE) == base) + ) + retention[name] = { + "known": int(ids.sum()), + "broken": int((ids & ~correct).sum()), + "rate": float((~correct[ids]).mean()) if ids.any() else None, + } + rates = [v["rate"] for v in retention.values()] + root_acc, member_acc, d_acc = (float(correct[ids].mean()) for ids in (root, members, d)) + joint = ( + None + if any(rate is None for rate in rates) + else bool( + root_acc == 1 + and member_acc >= 0.95 + and d_acc >= 0.95 + and all(rate <= 0.01 for rate in rates) + ) + ) + return { + "E": float(correct[e].mean()), + "E_root": root_acc, + "E_member": member_acc, + "D": d_acc, + "U_accuracy": float(correct[pair["strata"] >= 0].mean()), + "U_heldout_destruction": retention, + "U_full_destruction": full_retention, + "joint_pass": joint, + "E_target_value_nll": float(arrays["value_nll"][e].mean()), + } + + +def reference_logits(model, data, ids, device): + result = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(ids), 256): + subset = torch.as_tensor(ids[begin : begin + 256], device=device) + result.append(model(data["tokens"][subset], data["positions"][subset]).detach()) + return torch.cat(result) + + +@torch.no_grad() +def capture_down(model, tokens, positions, layer): + captured = {} + + def capture(module, inputs, output): + captured.update( + z=inputs[0].float().clone(), + h=output.float().clone(), + weight=module.weight.detach().float().clone(), + ) + + handle = model.blocks[layer].mlp.down.register_forward_hook(capture) + try: + model(tokens, positions) + finally: + handle.remove() + return captured + + +def edit_case( + model, + baseline, + world, + data_old, + pair, + kind, + scope, + args, + old_correct, + branch_kind=None, + basis=None, +): + suffix = "" if branch_kind is None else f"-{branch_kind}-branch" + out = Path(args.output) / f"support-{pair['support']}-{kind}-{scope}{suffix}" + if (out / "complete.json").exists(): + return json.loads((out / "complete.json").read_text()) + out.mkdir(parents=True, exist_ok=True) + device = data_old["tokens"].device + model.load_state_dict(baseline) + selected = select_parameters(model, scope, args.window) + branch, handles, zero_error = None, [], None + if basis is not None: + probe = torch.as_tensor(pair["E"][:32], device=device) + with torch.no_grad(), precision(device): + before = model(data_old["tokens"][probe], data_old["positions"][probe]) + branch, handles = attach_branch(model, basis, layer=args.window + 1) + selected.extend(branch.parameters()) + with torch.no_grad(), precision(device): + after = model(data_old["tokens"][probe], data_old["positions"][probe]) + zero_error = (before - after).abs().max().item() + if zero_error != 0: + raise ValueError("Branch was not function-preserving at initialization") + target = pair[kind] + data_new = tensor_data(world, device, target) + if device.type == "cuda": + torch.cuda.synchronize(device) + setup_start = time.perf_counter() + calibration = None + if scope == "down": + calibration_ids = torch.as_tensor( + np.concatenate([pair["E"][:32], pair["replay"][:32]]), device=device + ) + calibration = capture_down( + model, + data_old["tokens"][calibration_ids], + data_old["positions"][calibration_ids], + args.window + 1, + ) + old_logits = reference_logits(model, data_old, pair["replay"], device) + if device.type == "cuda": + torch.cuda.synchronize(device) + setup_seconds = time.perf_counter() - setup_start + basis_seconds = getattr(args, "branch_preparation_seconds", 0.0) if basis else 0.0 + setup_flops = matmul_flops(model.config, len(pair["replay"]), backward=False) + optimizer = torch.optim.AdamW( + selected, lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + sample_rng = rng_for(world.seed, 41, pair["support"]) + e_choices = sample_rng.integers(0, len(pair["E"]), size=(args.steps, 128)) + r_choices = sample_rng.integers(0, len(pair["replay"]), size=(args.steps, 128)) + timeline, train_seconds = [], 0.0 + case_config = { + "scope": scope, + "branch": branch_kind, + "branch_parameters": sum(p.numel() for p in branch.parameters()) if branch else 0, + "branch_zero_initialization_max_logit_difference": zero_error, + "kind": kind, + "support": pair["support"], + "selection": pair["selection"], + "steps": args.steps, + "lr": args.lr, + "retention_kl_weight": args.retention, + "window_zero_based": list(range(args.window, args.window + 3)), + "trainable_parameters": sum(p.numel() for p in selected), + "setup_seconds": setup_seconds, + "shared_basis_preparation_seconds": basis_seconds, + "preparation_accounting": ( + "Basis construction is executed once per old checkpoint. Standalone cold-start time " + "below charges that entire common construction; do not sum it across reused branches." + ), + "setup_matmul_flops_estimate": setup_flops, + "flops_limitation": ( + "backward dense matmul upper approximation; not exact frozen-scope operation count" + ), + } + write_json(out / "config.json", case_config) + np.savez_compressed( + out / "sets.npz", + E=pair["E"], + D=pair["D"], + strata=pair["strata"], + replay=pair["replay"], + heldout=pair["heldout"], + target=target, + old_correct=old_correct, + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + checkpoints = sorted({s for s in EDIT_CHECKPOINTS if s <= args.steps} | {args.steps}) + for step in range(args.steps + 1): + if step in checkpoints: + eval_start = time.perf_counter() + _, arrays = evaluate(model, data_old, world, answers=target) + metrics = score_edit(world, pair, target, arrays, old_correct) + np.savez_compressed(out / f"predictions-{step}.npz", **arrays) + point = { + "step": step, + **metrics, + "edit_seconds": train_seconds, + "setup_plus_edit_seconds": setup_seconds + train_seconds, + "cold_start_including_basis_seconds": basis_seconds + setup_seconds + train_seconds, + "setup_plus_edit_matmul_flops_estimate": setup_flops + + step * matmul_flops(model.config, 256), + "target_supervised_tokens": step * 256, + "replay_supervised_tokens": step * 256, + "eval_seconds": time.perf_counter() - eval_start, + } + if calibration is not None: + current = capture_down( + model, + data_old["tokens"][calibration_ids], + data_old["positions"][calibration_ids], + args.window + 1, + ) + observed = current["h"] - calibration["h"] + predicted = F.linear(calibration["z"], current["weight"] - calibration["weight"]) + point["down_calibration"] = { + "feature_max_change": (current["z"] - calibration["z"]).abs().max().item(), + "delta_h_max_error": (observed - predicted).abs().max().item(), + "delta_h_rms_error": (observed - predicted).square().mean().sqrt().item(), + "fixed_prefix_tokens": int( + calibration["z"].shape[0] * calibration["z"].shape[1] + ), + } + timeline.append(point) + write_json(out / "trajectory.json", timeline) + print( + json.dumps( + { + "event": "edit", + "case": out.name, + "step": step, + "E": metrics["E"], + "D": metrics["D"], + "joint": metrics["joint_pass"], + } + ), + flush=True, + ) + if step == args.steps: + break + model.train() + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + reference = old_logits[torch.as_tensor(r_choices[step], device=device)].float() + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits_e = model(data_new["tokens"][ei], data_new["positions"][ei]).float() + logits_r = model(data_old["tokens"][ri], data_old["positions"][ri]).float() + ce = F.cross_entropy( + logits_e.reshape(-1, world.vocab_size), data_new["labels"][ei].reshape(-1) + ) + kl = ( + F.kl_div( + F.log_softmax(logits_r, dim=-1), F.softmax(reference, dim=-1), reduction="none" + ) + .sum(-1) + .mean() + ) + loss = ce + args.retention * kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1.0) + if not torch.isfinite(loss) or not torch.isfinite(norm): + write_json(out / "failure.json", {"step": step, "reason": "nonfinite loss or gradient"}) + raise FloatingPointError("Nonfinite edit") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - start + passed = [p for p in timeline if p["joint_pass"] is True] + result = { + **case_config, + "status": "complete", + "final": timeline[-1], + "first_observed_joint_step": passed[0]["step"] if passed else None, + "budget_censored": (not bool(passed) if timeline[-1]["joint_pass"] is not None else None), + "joint_evaluable": timeline[-1]["joint_pass"] is not None, + } + write_json(out / "complete.json", result) + if handles: + remove_branch(model, handles) + return result + + +def run(args): + torch.set_num_threads(args.threads) + torch.manual_seed(0) + device = torch.device(args.device) + world = load_world(args.world) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_data(world, device) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + write_json( + out / "run.json", {**vars(args), "world_step": checkpoint["step"], **code_fingerprint()} + ) + _, old_arrays = evaluate(model, data, world) + bases = None + if args.branches: + bases, operation_checks = build_bases(model, world, data, layer=args.window + 1) + write_json(out / "branch-operation-checks.json", operation_checks) + args.branch_preparation_seconds = operation_checks.get("construction_seconds", 0.0) + results = [] + for support in args.supports: + pair = paired_edit(world, support=support, k=1) + scopes = getattr(args, "scopes", None) + if scopes is None: + scopes = ["mlp", "all"] + (["down"] if support == 0 else []) + for scope in scopes: + for kind in ("coherent", "exception"): + results.append( + edit_case( + model, + checkpoint["model"], + world, + data, + pair, + kind, + scope, + args, + old_arrays["correct"], + ) + ) + if support == 0 and bases is not None: + for branch_kind, basis in bases.items(): + for kind in ("coherent", "exception"): + results.append( + edit_case( + model, + checkpoint["model"], + world, + data, + pair, + kind, + "mlp", + args, + old_arrays["correct"], + branch_kind, + basis, + ) + ) + write_json(out / "complete.json", {"status": "complete", "cases": results}) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--supports", type=int, nargs="+", default=[0, 1]) + parser.add_argument("--scopes", choices=["mlp", "all", "down"], nargs="+") + parser.add_argument("--steps", type=int, default=512) + parser.add_argument("--window", type=int, default=3) + parser.add_argument("--lr", type=float, default=3e-5) + parser.add_argument("--retention", type=float, default=1.0) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--branches", action="store_true") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_followup.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..c90b76331ad0bbd37276b4a9fe14b865360e7a60 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_followup.py @@ -0,0 +1,381 @@ +"""Small, paired follow-ups using frozen editing and gradient implementations. + +Historical source files are left intact. A process-local, scoped adapter supplies +only a new supervised weight vector to the established P1 training loop. +""" + +import argparse +import fcntl +import itertools +import json +import os +import subprocess +import sys +import time +from contextlib import contextmanager +from pathlib import Path +from types import MethodType + +import numpy as np +import torch + +from . import bios_context_gradient as gradient +from . import bios_mechanism_edit as editing +from .bios_cross import make_cross_world +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = "configs/bios-followup-v1.json" +ROOT_MASSES = {"root125": 0.125, "root250": 0.25, "root500": 0.5} +ORIGINAL_MAKE_ARM = editing.make_arm +ORIGINAL_SOURCE_HASHES = editing.source_hashes + + +def mixture_spec(world, chain, arm, pair=None): + if "-root" not in arm: + return ORIGINAL_MAKE_ARM(world, chain, arm, pair) + kind, tag = arm.split("-", 1) + if kind not in ("coherent", "exception") or tag not in ROOT_MASSES: + raise ValueError("Unknown mixture arm") + spec = ORIGINAL_MAKE_ARM(world, chain, kind, pair) + mass = ROOT_MASSES[tag] + mask = spec["S_root_mask"] + spec["S_weights"] = np.where( + mask, mass * len(mask) / mask.sum(), (1 - mass) * len(mask) / (~mask).sum() + ) + return spec + + +def production_hashes(): + return {**ORIGINAL_SOURCE_HASHES(), Path(__file__).name: editing.file_hash(__file__)} + + +@contextmanager +def mixture_adapter(): + old_make, old_hash = editing.make_arm, editing.source_hashes + editing.make_arm, editing.source_hashes = mixture_spec, production_hashes + try: + yield + finally: + editing.make_arm, editing.source_hashes = old_make, old_hash + + +def uniform_forward(self, x): + """First-layer uniform causal attention, with the full value/projection path.""" + width = x.shape[-1] + value = self.qkv(x)[..., 2 * width :] + mask = gradient.allowed_mask(x.shape[1], False, x.device).to(x.dtype) + mask = mask / mask.sum(-1, keepdim=True) + return self.proj(mask @ value) + + +@contextmanager +def uniform_first_layer(model): + attention = model.blocks[0].attention + original = attention.forward + attention.forward = MethodType(uniform_forward, attention) + try: + yield + finally: + attention.forward = original + + +def load_config(): + config = json.loads((ROOT / CONFIG).read_text()) + if config["root_mass"] != {"uniform": 1 / 31, **ROOT_MASSES}: + raise ValueError("The declared mixture weights differ from the implementation") + return config + + +def frozen_paths(config): + paths = [ + ROOT / CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_followup.py", + ROOT / "tests/test_bios_followup.py", + ROOT / "src/llm_memory_editability/bios_context_gradient.py", + ROOT / "src/llm_memory_editability/bios_mechanism_edit.py", + ROOT / "scripts/run_bios_mechanism_edit.py", + ROOT / config["gradient_config"], + ROOT / "docs/development-artifacts/context-gradient-v1/preregistration-lock.json", + ] + paths += [ROOT / "src/llm_memory_editability" / name for name in editing.parent_source_hashes()] + for world, seed, condition in itertools.product( + config["worlds"], config["seeds"], config["conditions"] + ): + name = f"world-{world}-seed-{seed}-{condition}" + paths += [ROOT / config["parent_root"] / name / "config.json"] + paths += [ROOT / config["balanced_root"] / name / "contract.json"] + return sorted(set(paths)) + + +def freeze(config): + artifacts = ROOT / config["artifacts"] + artifacts.mkdir(parents=True, exist_ok=True) + lock = artifacts / "preregistration-lock.json" + if lock.exists(): + raise FileExistsError("Existing prospective lock cannot be replaced") + protocol = (ROOT / "docs/experimental-protocol.md").read_text().split("## 17. ", 1)[1] + (artifacts / "preregistration.md").write_text("## 17. " + protocol) + sources = {} + for path in frozen_paths(config): + relative = path.relative_to(ROOT) + sources[str(relative)] = editing.file_hash(path) + if relative.parts[0] not in ("results", "data"): + destination = artifacts / "frozen-files" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(path.read_bytes()) + write_json( + lock, + { + "created_at": gradient.stamp(), + "config": config, + "sources": sources, + "protocol_sha256": editing.file_hash(artifacts / "preregistration.md"), + "torch": torch.__version__, + "numpy": np.__version__, + }, + ) + return {"lock": str(lock), "sha256": editing.file_hash(lock)} + + +def verify_lock(config): + artifacts = ROOT / config["artifacts"] + path = artifacts / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Frozen configuration/runtime mismatch") + for source, digest in lock["sources"].items(): + if editing.file_hash(ROOT / source) != digest: + raise ValueError("Frozen source mismatch: " + source) + if editing.file_hash(artifacts / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Frozen protocol mismatch") + return editing.file_hash(path) + + +def run_edit(config, world, seed, condition, device): + verify_lock(config) + if (world, seed, condition) not in itertools.product( + config["worlds"], config["seeds"], config["conditions"] + ): + raise ValueError("Edit worker is outside the frozen matrix") + name = f"world-{world}-seed-{seed}-{condition}" + destination = ROOT / config["output"] / "editing" / name + destination.mkdir(parents=True, exist_ok=True) + with (destination / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + with mixture_adapter(): + editing.run_model( + ROOT / config["parent_root"] / name, destination, config["edit"], device + ) + + +def verify_receipt(path): + receipt = json.loads((path / "receipt.json").read_text()) + for name, digest in receipt["files"].items(): + if editing.file_hash(path / name) != digest: + raise ValueError("Gradient receipt mismatch: " + str(path / name)) + + +def run_gradient(config, world_seed, seed, device): + lock_hash = verify_lock(config) + if world_seed not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("Gradient worker is outside the frozen matrix") + original = json.loads((ROOT / config["gradient_config"]).read_text()) + gradient.verify_lock(ROOT, original) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + world = make_cross_world(world_seed, ROOT / original["source_world_root"]) + name = f"world-{world_seed}-seed-{seed}" + source = ROOT / config["gradient_parent"] / name + destination = ROOT / config["output"] / "gradient" / name + destination.mkdir(parents=True, exist_ok=True) + seal = json.loads((source / "complete.json").read_text()) + consumed = {"complete.json": editing.file_hash(source / "complete.json")} + with (destination / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if (destination / "complete.json").exists(): + raise FileExistsError("Completed gradient worker cannot be overwritten") + for step in config["gradient"]["states"]: + checkpoint = source / f"state-{step}.pt" + digest = editing.file_hash(checkpoint) + if digest != seal["files"][checkpoint.name]: + raise ValueError("Archived common state hash mismatch") + consumed[checkpoint.name] = digest + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + if saved["step"] != step: + raise ValueError("Common state step mismatch") + model = CausalLM(ModelConfig(**saved["config"])).to(device) + model.load_state_dict(saved["model"]) + sham = config["gradient"]["sham"] + if (world_seed, seed, step) == (sham["world"], sham["seed"], sham["step"]): + path = destination / "sham" + if not (path / "receipt.json").exists(): + gradient.measure_arm( + model, world, sham["condition"], False, original, device, path + ) + verify_receipt(path) + before = source / f"step-{step}-open-{sham['condition']}" + verify_receipt(before) + errors = {} + for kind in ("answer", "eos"): + with np.load(before / f"{kind}.npz") as a, np.load(path / f"{kind}.npz") as b: + for parameter in a.files: + reference = np.linalg.norm(a[parameter].astype(np.float64)) + difference = np.linalg.norm( + b[parameter].astype(np.float64) - a[parameter] + ) + error = ( + float(difference / reference) if reference else float(difference) + ) + errors[f"{kind}/{parameter}"] = error + if max(errors.values()) > config["gradient"]["sham_relative_tolerance"]: + raise ValueError("Historical-gradient sham failed") + write_json(destination / "sham-check.json", errors) + for condition in config["conditions"]: + path = destination / f"step-{step}-uniform-{condition}" + if not (path / "receipt.json").exists(): + with uniform_first_layer(model): + gradient.measure_arm(model, world, condition, False, original, device, path) + verify_receipt(path) + print(json.dumps({"event": "gradient_arm_complete", "path": str(path)}), flush=True) + del model, saved + verify_lock(config) + write_json( + destination / "complete.json", + { + "complete": True, + "created_at": gradient.stamp(), + "lock_sha256": lock_hash, + "parent": str(source), + "consumed": consumed, + "world": world_seed, + "seed": seed, + "device": str(device), + "gpu": torch.cuda.get_device_name(device), + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "new_uniform_arms": 9, + "files": { + str(p.relative_to(destination)): editing.file_hash(p) + for p in sorted(destination.rglob("*")) + if p.is_file() and p.suffix in ("npz", ".npz", ".json") + }, + }, + ) + + +def jobs(config): + result = [] + for world, seed in itertools.product(config["worlds"], config["seeds"]): + name = f"world-{world}-seed-{seed}" + result.append(("gradient/" + name, ["run-gradient", "--world", world, "--seed", seed])) + for condition in config["conditions"]: + result.append( + ( + "editing/" + name + "-" + condition, + ["run-edit", "--world", world, "--seed", seed, "--condition", condition], + ) + ) + return result + + +def dispatch(config, gpus, slots): + if not gpus or len(set(gpus)) != len(gpus) or slots < 1 or 0 in gpus: + raise ValueError( + "Unique healthy GPUs and positive concurrency required; GPU0 has ECC errors" + ) + lock_hash = verify_lock(config) + destination = ROOT / config["output"] + destination.mkdir(parents=True, exist_ok=True) + with (destination / ".dispatcher.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + pending, complete, failed, active = [], [], [], [] + for name, arguments in jobs(config): + if (destination / name / "complete.json").exists(): + complete.append(name) + else: + pending.append((name, arguments)) + while pending or active: + for item in active[:]: + code = item["process"].poll() + if code is None: + continue + item["log"].close() + good = code == 0 and (destination / item["name"] / "complete.json").exists() + (complete if good else failed).append(item["name"]) + active.remove(item) + if not failed: + for gpu in gpus: + while pending and sum(i["gpu"] == gpu for i in active) < slots: + name, arguments = pending.pop(0) + out = destination / name + out.mkdir(parents=True, exist_ok=True) + command = [sys.executable, "-m", "llm_memory_editability.bios_followup"] + command += [str(a) for a in arguments] + log = (out / "run.log").open("a") + env = { + **os.environ, + "PYTHONPATH": str(ROOT / "src"), + "CUDA_VISIBLE_DEVICES": str(gpu), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + process = subprocess.Popen( + command, cwd=ROOT, env=env, stdout=log, stderr=log + ) + write_json( + out / "launch.json", + { + "pid": process.pid, + "gpu": gpu, + "command": command, + "started": gradient.stamp(), + }, + ) + active.append({"name": name, "gpu": gpu, "process": process, "log": log}) + write_json( + destination / "status.json", + { + "state": "failed" if failed else "running" if active or pending else "complete", + "lock_sha256": lock_hash, + "complete": complete, + "failed": failed, + "pending": len(pending), + "active": [ + {"name": i["name"], "gpu": i["gpu"], "pid": i["process"].pid} + for i in active + ], + "updated": gradient.stamp(), + }, + ) + if failed and not active: + raise RuntimeError("Worker failure; unstarted jobs retained") + if pending or active: + time.sleep(5) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=("freeze", "dispatch", "run-edit", "run-gradient")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--condition") + parser.add_argument("--gpus", type=int, nargs="+") + parser.add_argument("--slots-per-gpu", type=int, default=1) + parser.add_argument("--device", default="cuda:0") + args = parser.parse_args() + torch.set_num_threads(2) + config = load_config() + if args.mode == "freeze": + print(json.dumps(freeze(config))) + elif args.mode == "dispatch": + dispatch(config, args.gpus, args.slots_per_gpu) + elif args.mode == "run-edit": + run_edit(config, args.world, args.seed, args.condition, torch.device(args.device)) + else: + run_gradient(config, args.world, args.seed, torch.device(args.device)) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_measure.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_measure.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf7c45f10b2be179635d21d0f3a7fde2ee6ca6c --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_measure.py @@ -0,0 +1,286 @@ +"""Pre-edit activation geometry and controlled mean-component interventions. + +Company means are candidate shared components, not assumed learned mechanisms. +All donors, recipients and controls depend only on the old world and fixed seeds. +""" + +import argparse +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import EOS, load_world, rng_for, write_json +from .bios_model import CausalLM, ModelConfig +from .bios_train import code_fingerprint, precision, tensor_data + + +@torch.no_grad() +def activation_summary(model, world, data): + device = data["tokens"].device + collected = [[] for _ in model.blocks] + detailed = {} + first_batch = [True] + handles = [] + # Actual-city atomic queries have final prompt position 3. + for layer, block in enumerate(model.blocks): + + def capture(_module, _inputs, output, layer=layer): + collected[layer].append(output[:, 3].float().cpu()) + if first_batch[0]: + detailed[f"z_positions_layer_{layer}"] = ( + output[:128, [1, 2, 3]].float().cpu().numpy() + ) + + handles.append(block.mlp.activation.register_forward_hook(capture)) + + def capture_mlp(_module, inputs, output, layer=layer): + if first_batch[0]: + detailed[f"x_positions_layer_{layer}"] = ( + inputs[0][:128, [1, 2, 3]].float().cpu().numpy() + ) + detailed[f"h_positions_layer_{layer}"] = ( + output[:128, [1, 2, 3]].float().cpu().numpy() + ) + + handles.append(block.mlp.register_forward_hook(capture_mlp)) + with precision(device): + for begin in range(2112, 4160, 256): + model( + data["prompts"][begin : begin + 256], data["lengths"][begin : begin + 256, None] - 1 + ) + first_batch[0] = False + for handle in handles: + handle.remove() + activations = [torch.cat(parts) for parts in collected] + summaries, means = [], [] + for layer, z in enumerate(activations): + mu = torch.stack([z[world.employers == c].mean(0) for c in range(64)]) + centered = mu - z.mean(0) + residual = z - mu[world.employers] + shared_variance = centered.square().mean().item() + individual_variance = residual.square().mean().item() + cosine = F.cosine_similarity(z, mu[world.employers], dim=-1) + summaries.append( + { + "layer": layer, + "mean_norm": z.norm(dim=-1).mean().item(), + "company_mean_variance": shared_variance, + "within_company_variance": individual_variance, + "shared_variance_fraction": shared_variance + / (shared_variance + individual_variance + 1e-20), + "member_to_company_cosine": cosine.mean().item(), + } + ) + means.append(mu) + detailed["query_ids"] = np.arange(2112, 2240) + detailed["token_positions"] = np.array([1, 2, 3]) + return summaries, means, activations, detailed + + +def probe_plan(world): + rng = rng_for(world.seed, 51) + recipients = rng.permutation(64)[:8] + result = [] + for c in recipients: + same = np.flatnonzero((world.defaults == world.defaults[c]) & (np.arange(64) != c))[0] + donor = rng.choice(np.flatnonzero(world.defaults != world.defaults[c])) + wrong = rng.choice( + np.flatnonzero(~np.isin(world.defaults, [world.defaults[c], world.defaults[donor]])) + ) + unrelated = rng.choice(np.flatnonzero(~np.isin(np.arange(64), [c, donor, same, wrong]))) + members = np.flatnonzero(world.employers == c) + other = np.flatnonzero(world.employers == unrelated) + ids = np.concatenate([2112 + members, 6208 + members, 2112 + other]) + # 6208 is the first birth-city row: employer 2048 + defaults 64 + actual/date 4096. + group = np.concatenate( + [np.where(world.exceptions[members], 1, 0), np.full(32, 2), np.full(32, 3)] + ) + result.append( + { + "recipient": int(c), + "donor": int(donor), + "same_answer": int(same), + "wrong_donor": int(wrong), + "unrelated": int(unrelated), + "ids": ids, + "group": group, + } + ) + return result + + +@torch.no_grad() +def causal_probes(model, world, data, means, behavior=False): + device = data["tokens"].device + results = [] + for plan_index, plan in enumerate(probe_plan(world)): + ids = torch.as_tensor(plan["ids"], device=device) + tokens = data["prompts"][ids] + positions = data["lengths"][ids, None] - 1 + donor_answer = int(world.city_tokens[world.defaults[plan["donor"]]]) + + def observe( + tokens=tokens, positions=positions, donor_answer=donor_answer, ids=ids, plan=plan + ): + with precision(device): + logits = model(tokens, positions)[:, 0].float() + probability = logits.softmax(-1)[:, donor_answer] + if not behavior: + return probability, None + first = logits.argmax(-1) + continuation = torch.zeros((len(ids), 6), dtype=torch.long, device=device) + continuation[:, :5] = tokens + rows = torch.arange(len(ids), device=device) + lengths = data["lengths"][ids] + continuation[rows, lengths] = first + ended = model(continuation, lengths[:, None])[:, 0].argmax(-1).eq(EOS) + truth = torch.as_tensor(world.answers[plan["ids"]], device=device) + return probability, { + "old_correct": (first.eq(truth) & ended).cpu().numpy(), + "donor_generated": (first.eq(donor_answer) & ended).cpu().numpy(), + "ended": ended.cpu().numpy(), + } + + baseline, baseline_behavior = observe() + for layer, mu_cpu in enumerate(means): + mu = mu_cpu.to(device) + c = plan["recipient"] + desired = mu[plan["donor"]] - mu[c] + generator = torch.Generator(device=device).manual_seed( + world.seed * 10000 + 100 * plan_index + layer + ) + random = torch.randn(desired.shape, generator=generator, device=device) + random = random * (desired.norm() / random.norm().clamp_min(1e-20)) + shifts = { + "donor": desired, + "same_answer_donor": mu[plan["same_answer"]] - mu[c], + "wrong_donor": mu[plan["wrong_donor"]] - mu[c], + "random_equal_norm": random, + "ablation": -(mu[c] - mu.mean(0)), + } + for kind, shift in shifts.items(): + + def patch(_module, _inputs, output, shift=shift): + edited = output.clone() + edited[:, 3] = edited[:, 3] + shift.to(output.dtype) + return edited + + handle = model.blocks[layer].mlp.activation.register_forward_hook(patch) + try: + changed, changed_behavior = observe() + finally: + handle.remove() + delta = (changed - baseline).cpu().numpy() + by_group = { + name: float(delta[plan["group"] == group].mean()) + for group, name in enumerate( + ( + "same_company_nonexception", + "old_exception", + "independent_attribute", + "unrelated_company", + ) + ) + } + result = { + "recipient": c, + "donor": plan["donor"], + "layer": layer, + "intervention": kind, + "shift_norm": shift.norm().item(), + **by_group, + "selective_shared_score": by_group["same_company_nonexception"] + - (by_group["independent_attribute"] + by_group["unrelated_company"]) / 2, + } + if behavior: + result["generation"] = {} + for group, name in enumerate(by_group): + mask = plan["group"] == group + known = mask & baseline_behavior["old_correct"] + result["generation"][name] = { + "n": int(mask.sum()), + "baseline_old_accuracy": float( + baseline_behavior["old_correct"][mask].mean() + ), + "changed_old_accuracy": float( + changed_behavior["old_correct"][mask].mean() + ), + "donor_generated_delta": float( + changed_behavior["donor_generated"][mask].mean() + - baseline_behavior["donor_generated"][mask].mean() + ), + "old_known": int(known.sum()), + "old_broken": int((known & ~changed_behavior["old_correct"]).sum()), + "nontermination_rate": float((~changed_behavior["ended"][mask]).mean()), + } + results.append(result) + return results + + +def run(args): + started = time.perf_counter() + torch.set_num_threads(4) + device = torch.device(args.device) + world = load_world(args.world) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + model.eval() + data = tensor_data(world, device) + summary, means, activations, detailed = activation_summary(model, world, data) + probes = causal_probes(model, world, data, means, behavior=args.behavior) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + out / "actual-city-activations.npz", + **{f"z_{i}": z.numpy() for i, z in enumerate(activations)}, + ) + np.savez_compressed(out / "input-activation-output-position-sample.npz", **detailed) + write_json( + out / "measurements.json", + { + "step": checkpoint["step"], + "device": str(device), + "precision": "BF16 autocast" if device.type == "cuda" else "FP32 CPU diagnostic", + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": hashlib.sha256(Path(args.checkpoint).read_bytes()).hexdigest(), + "measurement_seconds": time.perf_counter() - started, + "torch_version": torch.__version__, + "hardware": torch.cuda.get_device_name(device) if device.type == "cuda" else "CPU", + "behavior": args.behavior, + **code_fingerprint(), + "geometry": summary, + "probes": probes, + "scope": ( + "candidate company-mean components at final query token; " + "exploratory development measurement" + ), + }, + ) + print( + json.dumps( + {"event": "measurement_complete", "step": checkpoint["step"], "probes": len(probes)} + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument( + "--behavior", action="store_true", help="Also score complete generated answers" + ) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_mechanism_causal.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_mechanism_causal.py new file mode 100644 index 0000000000000000000000000000000000000000..8ac824d1ef628725bf1ee9ca778d381516508a80 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_mechanism_causal.py @@ -0,0 +1,969 @@ +"""Locked P4 necessity and downstream restoration diagnostics. + +Q is fitted only on actual queries in an archived exception case's S union R, +grouped by the model's own membership predictions. Truth-matched donor queries +are a subsequent diagnostic, never calibration. Restoring a same-query clean +downstream signal tests recovery from an artificial lesion, not edit repair. +""" + +import csv +import json +from pathlib import Path + +import numpy as np +import torch + +from .bios_causal_paths import make_donor_plan +from .bios_cross import CHAINS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_mechanism_interventions import ( + Site, + attach_state_operation, + calibration_plan, + downstream_routing_site, + fit_predicted_group_bases, + match_delta_norm, + projection_component, + query_site_roles, + remove_projection, + restore_projection, + valid_predicted_groups, +) +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import file_sha256 +from .bios_train import precision + +SOURCE = Site(0, 2) +DOWNSTREAM = Site(1, 2) +RANK = 32 +FAMILIES = ( + "default", + "actual", + "other_chain_default", + "attribute_3", + "attribute_4", + "attribute_5", + "attribute_6", + "membership", + "other_chain_actual", + "group_root", +) +ARMS = ( + "clean", + "sham", + "target_remove", + "random_remove", + "complement_remove", + "rescue_only", + "remove_rescue", + "remove_wrong_source_rescue", + "remove_random_rescue", +) +TRANSFER_TYPES = ( + "different_group_same_actual_different_default", + "different_group_same_default", + "different_group_same_default_same_actual", +) +TRANSFER_ARMS = ( + "sham", + "full_donor", + "full_norm_random", + "projected_target", + "projected_random", + "projected_complement", +) + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen diagnostic contract changed: {path}") + else: + write_json(path, value) + + +def _same_arrays(path, arrays): + if path.exists(): + with np.load(path) as existing: + if set(existing.files) != set(arrays) or any( + not np.array_equal(existing[key], value) for key, value in arrays.items() + ): + raise ValueError(f"Diagnostic plan changed: {path}") + else: + atomic_numpy_save(path, **arrays) + + +def _sources(): + directory = Path(__file__).parent + names = ( + "bios_mechanism_causal.py", + "bios_mechanism_interventions.py", + "bios_causal_paths.py", + "bios_cross.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_path_diagnostics.py", + ) + sources = {name: file_sha256(directory / name) for name in names} + runner = directory.parents[1] / "scripts/analyze_bios_mechanism_causal.py" + sources["runner"] = file_sha256(runner) + return sources + + +def validate_lock(lock): + if (lock.get("mechanism"), lock.get("layer"), lock.get("position")) != ("default_path", 0, 2): + raise ValueError("This runner only instantiates the locked default_path L0/pos2 candidate") + if lock.get("known_only") is not False or not lock.get("locked_at_utc"): + raise ValueError("An all-eligible, timestamped candidate lock is required") + + +def make_probe_plan(world, chain, recipients): + """Same people and fixed queries in every intervention, without knowledge filtering.""" + recipients = np.asarray(recipients, dtype=np.int64) + ids = [ + world.derived_ids[chain, recipients], + world.actual_ids[chain, recipients], + world.derived_ids[1 - chain, recipients], + ] + for relation in (3, 4, 5, 6): + candidates = np.flatnonzero(world.relation == relation) + by_person = np.full(len(world.actual_ids[chain]), -1, dtype=np.int64) + by_person[world.person[candidates]] = candidates + if (by_person[recipients] < 0).any(): + raise ValueError("An independent control query is missing") + ids.append(by_person[recipients]) + ids.extend([world.membership_ids[chain, recipients], world.actual_ids[1 - chain, recipients]]) + person_families = len(ids) + roots = world.root_ids[chain] + query_ids = np.concatenate([*ids, roots]) + return { + "query_id": query_ids, + "person": np.r_[np.tile(recipients, person_families), np.full(len(roots), -1)], + "family": np.r_[ + np.repeat(np.arange(person_families), len(recipients)), + np.full(len(roots), person_families), + ], + # -1 means not applicable; root facts are not ordinary people. + "recipient_old_exception": np.r_[ + np.tile(world.exceptions[chain, recipients].astype(np.int8), person_families), + np.full(len(roots), -1, dtype=np.int8), + ], + "answer": world.answers[query_ids], + } + + +def wrong_source_indices(families): + """Fixed one-person cyclic shift within each family, never chosen by answers.""" + families = np.asarray(families) + index = np.arange(len(families)) + for family in np.unique(families): + selected = np.flatnonzero(families == family) + if len(selected) < 2: + raise ValueError("Wrong-source controls require at least two queries per family") + index[selected] = np.roll(selected, 1) + return index + + +def make_transfer_plan(world, chain, per_population=64): + """Truth matching is restricted to this explicitly labeled offline diagnostic.""" + old = make_donor_plan(world, chain, per_population) + original = old["pair_type"] == 1 + recipients = old["recipient"][original] + train = world.person[world.train_ids[chain]] + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + rng = rng_for(world.seed, 978, chain) + donor_rows = [old["donor"][original]] + count_rows = [old["candidate_count"][original]] + for same_actual in (False, True): + donors, counts = [], [] + for recipient in recipients: + mask = (group[train] != group[recipient]) & (default[train] == default[recipient]) + if same_actual: + mask &= actual[train] == actual[recipient] + candidates = train[mask] + donors.append(rng.choice(candidates) if len(candidates) else -1) + counts.append(len(candidates)) + donor_rows.append(np.asarray(donors)) + count_rows.append(np.asarray(counts)) + donor = np.concatenate(donor_rows).astype(np.int64) + recipient = np.tile(recipients, len(TRANSFER_TYPES)) + safe = np.maximum(donor, 0) + return { + "case_id": np.arange(len(donor)), + "recipient": recipient, + "donor": donor, + "pair_type": np.repeat(np.arange(len(TRANSFER_TYPES)), len(recipients)), + "candidate_count": np.concatenate(count_rows), + "recipient_old_exception": world.exceptions[chain, recipient], + "same_actual": (actual[safe] == actual[recipient]) & (donor >= 0), + "same_default": (default[safe] == default[recipient]) & (donor >= 0), + "recipient_default": default[recipient], + "recipient_actual": actual[recipient], + "donor_default": np.where(donor >= 0, default[safe], -1), + "donor_actual": np.where(donor >= 0, actual[safe], -1), + } + + +def generate_queries( + model, prompts, lengths, device, batch_size=256, *, operations=None, capture_sites=() +): + """Two free generation passes with identical pre-answer operations, no answer input. + + operations(begin,end) returns (label, site, operation) triples. Every operation + returns its intended delta and availability; realized post-cast norms are + measured separately. Both passes are retained so norm matching is auditable. + """ + if len(prompts) == 0 or batch_size < 1: + raise ValueError("Generation needs nonempty queries and a positive batch size") + lengths = np.asarray(lengths) + if prompts.shape != (len(lengths), 5) or not np.isin(lengths, [4, 5]).all(): + raise ValueError("Unexpected symbolic query shape") + arrays = {"prediction": [], "ended": []} + for site in capture_sites: + query_site_roles(lengths, site.position) + arrays[f"state_{site.layer}_{site.position}"] = [] + calls = 0 + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + end = min(begin + batch_size, len(prompts)) + p = torch.as_tensor(prompts[begin:end], device=device) + n = torch.as_tensor(lengths[begin:end], device=device) + hooks, traces, captures = [], {}, {} + try: + for label, site, operation in () if operations is None else operations(begin, end): + query_site_roles(lengths[begin:end], site.position) + + def measured(value, operation=operation): + changed, trace = operation(value) + return changed, {**trace, "realized_delta": changed.float() - value.float()} + + hook, trace = attach_state_operation(model, site, measured) + hooks.append(hook) + traces[label] = trace + for site in capture_sites: + key = f"state_{site.layer}_{site.position}" + captures[key] = [] + + def capture( + _module, _inputs, output, key=key, position=site.position, captures=captures + ): + captures[key].append(output[:, position].detach().float()) + + hooks.append(model.blocks[site.layer].register_forward_hook(capture)) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + calls += 2 + arrays["prediction"].append(first.cpu().numpy()) + arrays["ended"].append(second.eq(EOS).cpu().numpy()) + for key, states in captures.items(): + arrays[key].append(states[0].cpu().numpy()) + drift = torch.linalg.vector_norm(states[1] - states[0], dim=-1) + arrays.setdefault(f"{key}_pass_drift", []).append(drift.cpu().numpy()) + for label, trace in traces.items(): + if len(trace) != 2: + raise ValueError( + "Every intervention must occur in both free-generation passes" + ) + for kind in ("delta", "realized_delta"): + norms = torch.stack( + [torch.linalg.vector_norm(t[kind].float(), dim=-1) for t in trace], + dim=1, + ) + arrays.setdefault(f"{label}_{kind}_norm", []).append(norms.cpu().numpy()) + valid = torch.stack([t["valid"] for t in trace], dim=1) + arrays.setdefault(f"{label}_valid", []).append(valid.cpu().numpy()) + finally: + for hook in hooks: + hook.remove() + result = {key: np.concatenate(value) for key, value in arrays.items()} + result.update( + forward_calls=np.asarray(calls), + forward_examples=np.asarray(2 * len(prompts)), + padded_token_positions=np.asarray(11 * len(prompts)), + logical_token_positions=np.asarray(int((2 * lengths + 1).sum())), + ) + return result + + +def _identity_trace(value): + return value, { + "delta": torch.zeros_like(value, dtype=torch.float32), + "valid": torch.ones(len(value), dtype=torch.bool, device=value.device), + } + + +def lesion_operations( + arm, source_bases, downstream_bases, clean_downstream, wrong_index, seed, device +): + """Return a deterministic batch factory. Wrong-source choice never sees truth.""" + if arm not in ARMS: + raise ValueError("Unknown necessity/restoration arm") + if arm == "clean": + return lambda _begin, _end: [] + if arm == "sham": + return lambda _begin, _end: [("source", SOURCE, _identity_trace)] + source = {key: basis.tensors(device) for key, basis in source_bases.items()} + downstream = ( + None + if downstream_bases is None + else {key: basis.tensors(device) for key, basis in downstream_bases.items()} + ) + needs_downstream = "rescue" in arm + if needs_downstream and downstream is None: + raise ValueError("Downstream basis is unavailable; recovery cannot be estimated") + wrong_index = np.asarray(wrong_index) + if len(wrong_index) != len(clean_downstream): + raise ValueError("Wrong-source plan length mismatch") + coefficients = ( + np.random.default_rng(seed) + .standard_normal((len(clean_downstream), source_bases["random"].rank)) + .astype(np.float32) + ) + + def factory(begin, end): + ops = [] + if arm == "clean": + return ops + if arm == "sham": + return [("source", SOURCE, _identity_trace)] + if arm != "rescue_only": + kind = ( + arm.removesuffix("_remove") + if arm in ("random_remove", "complement_remove") + else "target" + ) + q, mean, _ = source[kind] + tq, tm, _ = source["target"] + + def remove(value): + reference = ( + None + if kind == "target" + else torch.linalg.vector_norm(projection_component(value, tq, tm), dim=-1) + ) + return remove_projection(value, q, mean, reference) + + ops.append(("source", SOURCE, remove)) + if needs_downstream: + clean = torch.as_tensor(clean_downstream[begin:end], device=device) + wrong = torch.as_tensor(clean_downstream[wrong_index[begin:end]], device=device) + tq = downstream["target"][0] + rq = downstream["random"][0] + noise = torch.as_tensor(coefficients[begin:end], device=device) @ rq.T + + def recover(value): + _, same_query_trace = restore_projection(value, clean, tq) + correct_delta = same_query_trace["delta"] + reference = torch.linalg.vector_norm(correct_delta, dim=-1) + if arm == "remove_wrong_source_rescue": + return restore_projection(value, wrong, tq, reference) + if arm == "remove_random_rescue": + delta, valid = match_delta_norm(noise, reference) + return value + delta.to(value.dtype), {"delta": delta, "valid": valid} + return restore_projection(value, clean, tq) + + ops.append(("downstream", DOWNSTREAM, recover)) + return ops + + return factory + + +def transfer_operations(arm, bases, recipient, donor, seed, device): + """A locked-basis manipulation check, never a basis-fitting input.""" + if arm not in TRANSFER_ARMS or recipient.shape != donor.shape: + raise ValueError("Invalid donor manipulation") + if arm.startswith("projected_") and bases is None: + raise ValueError("Projected donor diagnostic requires an available source basis") + full_delta = donor.astype(np.float32) - recipient.astype(np.float32) + if arm == "sham": + delta, valid = np.zeros_like(full_delta), np.ones(len(donor), dtype=bool) + elif arm == "full_donor": + delta, valid = full_delta, np.ones(len(donor), dtype=bool) + else: + if arm == "full_norm_random": + raw = np.random.default_rng(seed).standard_normal(full_delta.shape).astype(np.float32) + reference = np.linalg.norm(full_delta, axis=-1) + else: + tq = bases["target"].q + target_delta = (full_delta @ tq) @ tq.T + reference = np.linalg.norm(target_delta, axis=-1) + q = bases[arm.removeprefix("projected_")].q + raw = (full_delta @ q) @ q.T + matched, available = match_delta_norm(torch.from_numpy(raw), torch.from_numpy(reference)) + delta, valid = matched.numpy(), available.numpy() + + def factory(begin, end): + change = torch.as_tensor(delta[begin:end], device=device) + available = torch.as_tensor(valid[begin:end], device=device) + + def operation(value): + return value + change.to(value.dtype), {"delta": change, "valid": available} + + return [("source", SOURCE, operation)] + + return factory + + +def _availability(arrays): + valid = np.ones(len(arrays["prediction"]), dtype=bool) + for key, value in arrays.items(): + if key.endswith("_valid"): + valid &= value.all(axis=1) + return valid + + +def score_rows(arrays, baseline, plan, arm, labels=FAMILIES, label_key="family"): + """All eligible rows first; original-correct strata remain descriptive only.""" + base_correct = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + correct = (arrays["prediction"] == plan["answer"]) & arrays["ended"] + available = _availability(arrays) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available + n, nb = int(chosen.sum()), int((chosen & base_correct).sum()) + before, after = int((chosen & base_correct).sum()), int((chosen & correct).sum()) + row = { + "arm": arm, + "family": family, + "population": population, + "requested": int(requested.sum()), + "available": n, + "unavailable": int((requested & ~available).sum()), + "baseline_correct": before, + "correct": after, + "accuracy": after / n if n else None, + "delta_accuracy": (after - before) / n if n else None, + "known_became_wrong": int((chosen & base_correct & ~correct).sum()), + "wrong_became_correct": int((chosen & ~base_correct & correct).sum()), + "known_denominator": nb, + "known_retention": int((chosen & base_correct & correct).sum()) / nb + if nb + else None, + "termination_error": int((chosen & ~arrays["ended"]).sum()), + "prediction_changed": int( + ( + chosen + & ( + (arrays["prediction"] != baseline["prediction"]) + | (arrays["ended"] != baseline["ended"]) + ) + ).sum() + ), + } + for label in ("source", "downstream"): + for kind in ("delta", "realized_delta"): + key = f"{label}_{kind}_norm" + row[f"mean_{key}"] = ( + float(arrays[key][chosen, 0].mean()) if n and key in arrays else None + ) + rows.append(row) + return rows + + +def paired_score_rows( + left, right, baseline, plan, left_name, right_name, labels=FAMILIES, label_key="family" +): + """Contrasts use a common availability mask, never unmatched denominators.""" + correct_left = (left["prediction"] == plan["answer"]) & left["ended"] + correct_right = (right["prediction"] == plan["answer"]) & right["ended"] + correct_clean = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + available_left, available_right = _availability(left), _availability(right) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available_left & available_right + n = int(chosen.sum()) + nl, nr = int((chosen & correct_left).sum()), int((chosen & correct_right).sum()) + known_right_wrong = chosen & correct_clean & ~correct_right + denominator = int(known_right_wrong.sum()) + rows.append( + { + "left": left_name, + "right": right_name, + "family": family, + "population": population, + "requested": int(requested.sum()), + "common_available": n, + "left_unavailable": int((requested & ~available_left).sum()), + "right_unavailable": int((requested & ~available_right).sum()), + "left_correct": nl, + "right_correct": nr, + "accuracy_difference": (nl - nr) / n if n else None, + "right_wrong_left_correct": int((chosen & ~correct_right & correct_left).sum()), + "right_correct_left_wrong": int((chosen & correct_right & ~correct_left).sum()), + "original_known_right_wrong": denominator, + "original_known_right_wrong_left_recovered": int( + (known_right_wrong & correct_left).sum() + ), + "conditional_recovery_auxiliary": int((known_right_wrong & correct_left).sum()) + / denominator + if denominator + else None, + } + ) + return rows + + +def _check_predictions(generated, archived, ids): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], archived[key][ids]): + raise ValueError(f"Clean frozen-model generation differs from archive: {key}") + + +def _cost(arrays): + return { + key: int(arrays[key]) + for key in ( + "forward_calls", + "forward_examples", + "padded_token_positions", + "logical_token_positions", + ) + } + + +def _cached_generate(path, model, world, ids, device, batch_size, **kwargs): + if path.exists(): + with np.load(path) as stored: + result = dict(stored) + if not np.array_equal(result.pop("query_id"), ids): + raise ValueError("Cached generation query plan differs") + return result + result = generate_queries( + model, world.prompts[ids], world.lengths[ids], device, batch_size, **kwargs + ) + atomic_numpy_save(path, query_id=ids, **result) + return result + + +def _fit_chain(model, world, chain, pair, dest, device, batch_size, archived): + plan = calibration_plan( + world.actual_ids[chain], + world.person, + world.membership_ids[chain], + pair["E"], + pair["replay"], + ) + _same_arrays( + dest / "calibration-plan.npz", {key: np.asarray(value) for key, value in plan.items()} + ) + actual = _cached_generate( + dest / "calibration-actual.npz", + model, + world, + plan["actual_query_ids"], + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + membership = _cached_generate( + dest / "calibration-membership.npz", + model, + world, + plan["membership_query_ids"], + device, + batch_size, + ) + _check_predictions(actual, archived, plan["actual_query_ids"]) + _check_predictions(membership, archived, plan["membership_query_ids"]) + prefix = f"{CHAINS[chain]}:" + allowed = np.array( + [i for i, label in enumerate(world.token_labels) if label.startswith(prefix)] + ) + groups, valid = valid_predicted_groups(membership["prediction"], membership["ended"], allowed) + _same_arrays(dest / "self-predicted-groups.npz", {"prediction": groups, "valid": valid}) + bases, reports, basis_arrays = {}, {}, {} + for label, site in (("source", SOURCE), ("downstream", DOWNSTREAM)): + basis, report = fit_predicted_group_bases( + actual[f"state_{site.layer}_{site.position}"], groups, valid, rank=RANK, seed=74 + chain + ) + bases[label], reports[label] = basis, report + if basis is not None: + for kind, value in basis.items(): + for field in ("q", "mean", "scale"): + basis_arrays[f"{label}_{kind}_{field}"] = getattr(value, field) + _same_arrays(dest / "bases.npz", basis_arrays) + information = { + "S_count": len(pair["E"]), + "R_count": len(pair["replay"]), + "actual_queries": len(plan["actual_query_ids"]), + "additional_membership_queries": len(plan["membership_query_ids"]), + "derived_calibration_queries": 0, + "true_memberships_supplied": False, + "membership_syntax_rule": prefix, + "invalid_groups_never_replaced": True, + "calibration_cost": {"actual": _cost(actual), "membership": _cost(membership)}, + "basis_reports": reports, + "variant": "group_means", + "basis_sha256": file_sha256(dest / "bases.npz"), + } + _freeze_json(dest / "calibration.json", information) + # Truth is read only after Q and its information contract are frozen. These + # labels score calibration quality; they never select rows or alter Q. + membership_correct = ( + membership["prediction"] == world.answers[plan["membership_query_ids"]] + ) & membership["ended"] + _freeze_json( + dest / "calibration-diagnostics.json", + { + "role": "offline scoring after frozen Q; never fitting or row selection", + "queries": len(groups), + "valid_predictions": int(valid.sum()), + "valid_rate": float(valid.mean()), + "correct_predictions": int(membership_correct.sum()), + "accuracy": float(membership_correct.mean()), + "accuracy_given_valid_auxiliary": float(membership_correct[valid].mean()) + if valid.any() + else None, + "basis_sha256": information["basis_sha256"], + }, + ) + return bases + + +def run_chain(model, world, chain, pair, dest, device, batch_size, per_population, archived): + dest.mkdir(parents=True, exist_ok=True) + bases = _fit_chain(model, world, chain, pair, dest, device, batch_size, archived) + transfer = make_transfer_plan(world, chain, per_population) + _same_arrays(dest / "transfer-plan.npz", transfer) + recipients = transfer["recipient"][transfer["pair_type"] == 0] + plan = make_probe_plan(world, chain, recipients) + plan["wrong_source_index"] = wrong_source_indices(plan["family"]) + plan["wrong_source_query_id"] = plan["query_id"][plan["wrong_source_index"]] + plan["wrong_source_same_answer"] = plan["answer"] == plan["answer"][plan["wrong_source_index"]] + _same_arrays(dest / "probe-plan.npz", plan) + ids = plan["query_id"] + query_site_roles(world.lengths[ids], SOURCE.position) + if downstream_routing_site(SOURCE, len(model.blocks), world.lengths[ids] - 1) != DOWNSTREAM: + raise ValueError("Candidate/downstream site mismatch") + clean = _cached_generate( + dest / "clean.npz", + model, + world, + ids, + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + _check_predictions(clean, archived, ids) + rows, states, costs, arm_arrays = [], {}, {"clean": _cost(clean)}, {} + clean_down = clean[f"state_{DOWNSTREAM.layer}_{DOWNSTREAM.position}"] + for arm in ARMS: + if arm not in ("clean", "sham") and bases["source"] is None: + states[arm] = "unavailable_source_rank" + continue + if "rescue" in arm and bases["downstream"] is None: + states[arm] = "unavailable_downstream_rank" + continue + if arm == "clean": + generated = clean + else: + operations = lesion_operations( + arm, + bases["source"], + bases["downstream"], + clean_down, + plan["wrong_source_index"], + [world.seed, 979, chain], + device, + ) + generated = _cached_generate( + dest / f"{arm}.npz", model, world, ids, device, batch_size, operations=operations + ) + if arm in ("sham", "rescue_only"): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], clean[key]): + raise ValueError(f"No-lesion control changed output: {arm}/{key}") + rows.extend(score_rows(generated, clean, plan, arm)) + costs[arm], states[arm] = _cost(generated), "complete" + arm_arrays[arm] = generated + comparisons = [ + (arm, "clean") + for arm in ("sham", "target_remove", "random_remove", "complement_remove", "rescue_only") + ] + comparisons += [("target_remove", arm) for arm in ("random_remove", "complement_remove")] + comparisons += [ + (arm, "target_remove") + for arm in ("remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue") + ] + comparisons += [ + ("remove_rescue", arm) for arm in ("remove_wrong_source_rescue", "remove_random_rescue") + ] + paired_rows = [] + for left, right in comparisons: + if left in arm_arrays and right in arm_arrays: + paired_rows.extend( + paired_score_rows(arm_arrays[left], arm_arrays[right], clean, plan, left, right) + ) + # Donor activations are read only after both bases and their provenance are frozen. + valid = transfer["donor"] >= 0 + selected = {key: value[valid] for key, value in transfer.items()} + people = np.unique(np.r_[selected["recipient"], selected["donor"]]) + donor_ids = world.derived_ids[chain, people] + donor_clean = _cached_generate( + dest / "transfer-clean.npz", + model, + world, + donor_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + _check_predictions(donor_clean, archived, donor_ids) + ri, di = ( + np.searchsorted(people, selected["recipient"]), + np.searchsorted(people, selected["donor"]), + ) + source_state = donor_clean[f"state_{SOURCE.layer}_{SOURCE.position}"] + donor_baseline = {key: donor_clean[key][ri] for key in ("prediction", "ended")} + donor_plan = {**selected, "answer": selected["recipient_default"]} + transfer_rows, transfer_status = [], {} + costs["transfer_clean"] = _cost(donor_clean) + for arm in TRANSFER_ARMS: + if arm.startswith("projected_") and bases["source"] is None: + transfer_status[arm] = "unavailable_source_rank" + continue + ops = transfer_operations( + arm, + bases["source"], + source_state[ri], + source_state[di], + [world.seed, 980, chain], + device, + ) + generated = _cached_generate( + dest / f"transfer-{arm}.npz", + model, + world, + world.derived_ids[chain, selected["recipient"]], + device, + batch_size, + operations=ops, + ) + if arm == "sham": + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], donor_baseline[key]): + raise ValueError("Transfer sham changed output") + scored = score_rows( + generated, donor_baseline, donor_plan, arm, labels=TRANSFER_TYPES, label_key="pair_type" + ) + for row in scored: + code = TRANSFER_TYPES.index(row["family"]) + chosen = (selected["pair_type"] == code) & _availability(generated) + requested = transfer["pair_type"] == code + if row["population"] != "all": + exception = row["population"] == "old_exception" + chosen &= selected["recipient_old_exception"] == exception + requested &= transfer["recipient_old_exception"] == exception + row["plan_requested"] = int(requested.sum()) + row["missing_donors"] = int((requested & ~valid).sum()) + for role in ("recipient_actual", "donor_default", "donor_actual"): + matched = (generated["prediction"] == selected[role]) & generated["ended"] + base_matched = (donor_baseline["prediction"] == selected[role]) & donor_baseline[ + "ended" + ] + row[f"matches_{role}"] = int((chosen & matched).sum()) + row[f"baseline_matches_{role}"] = int((chosen & base_matched).sum()) + # Donor's own clean response is descriptive, not an eligibility filter. + row["donor_answered_default"] = int( + ( + chosen + & donor_clean["ended"][di] + & (donor_clean["prediction"][di] == selected["donor_default"]) + ).sum() + ) + transfer_rows.extend(scored) + transfer_status[arm], costs[f"transfer_{arm}"] = "complete", _cost(generated) + for filename, contents in ( + ("necessity.csv", rows), + ("paired-necessity.csv", paired_rows), + ("transfer.csv", transfer_rows), + ): + with (dest / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + dest / "status.json", + { + "arms": states, + "transfer_arms": transfer_status, + "evaluation_cost": costs, + "information_boundary": "truth-matched donor states are diagnostic only", + }, + ) + return {"chain": CHAINS[chain], "arms": states, "transfer_arms": transfer_status} + + +def scientific_outputs(output): + """Seal only producer-owned artifacts, excluding mutable queue logs and locks.""" + names = { + "calibration-plan.npz", + "calibration-actual.npz", + "calibration-membership.npz", + "self-predicted-groups.npz", + "bases.npz", + "calibration.json", + "calibration-diagnostics.json", + "transfer-plan.npz", + "probe-plan.npz", + "transfer-clean.npz", + "necessity.csv", + "paired-necessity.csv", + "transfer.csv", + "status.json", + } + names.update(f"{arm}.npz" for arm in ARMS) + names.update(f"transfer-{arm}.npz" for arm in TRANSFER_ARMS) + paths = [output / "contract.json"] + for chain in CHAINS: + paths.extend( + output / chain / name for name in sorted(names) if (output / chain / name).exists() + ) + return {str(path.relative_to(output)): file_sha256(path) for path in paths} + + +def run_model(run, output, lock_path, *, device="cuda", batch_size=256, per_population=64): + """One original pre-edit checkpoint, both chains; separate outputs, restartable nodes.""" + run, output, lock_path = Path(run).resolve(), Path(output).resolve(), Path(lock_path).resolve() + if output == run or run in output.parents: + raise ValueError("Never write diagnostics inside the frozen parent") + lock = json.loads(lock_path.read_text()) + validate_lock(lock) + config = json.loads((run / "config.json").read_text()) + if ( + config["world"] not in (0, 1) + or config["model"]["width"] not in (256, 768) + or config["seed"] not in (0, 1) + or config["condition"] not in (*CHAINS, "neither") + ): + raise ValueError("The original 24-model development matrix is required") + step = config["study"]["steps"] + if step != 15360 or per_population != 64: + raise ValueError("The parent step and 64+64 recipient budget are fixed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent runtime differs: {key}") + device = torch.device(device) + weights = run / f"model-{step}.pt" + contract = { + "run": str(run), + "step": step, + "world": config["world"], + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "parent_config_sha256": file_sha256(run / "config.json"), + "parent_weights_sha256": file_sha256(weights), + "lock": lock, + "lock_sha256": file_sha256(lock_path), + "sources": _sources(), + "source_site": [0, 2], + "downstream_site": [1, 2], + "rank": RANK, + "per_population": per_population, + "batch_size": batch_size, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": device.type, + "checkpoint_role": "pre_edit_clean_only", + "calibration": "S_union_R_actual_queries_with_self_predicted_membership_groups", + "families": list(FAMILIES), + "arms": list(ARMS), + "transfer_types": list(TRANSFER_TYPES), + "transfer_arms": list(TRANSFER_ARMS), + "wrong_source_rule": "cyclic_previous_query_within_family_no_truth_or_prediction_selection", + "cross_query_reference": "The actual-calibration mean is reused for all query families", + "recovery_source": "Same checkpoint and same query clean post-L1/pos2 target projection", + "rescue_only_role": "No-lesion downstream sham; cannot establish necessity", + "random_recovery": "Random rank32 downstream basis; same-query recovery delta norm", + "rank_failure": "Unavailable, never padded or replaced; report coverage by organization", + "interpretation": ( + "Artificial-lesion behavior recovery; no claim of edit repair " + "or organizational specificity" + ), + } + output.mkdir(parents=True, exist_ok=True) + _freeze_json(output / "contract.json", contract) + complete_path = output / "complete.json" + if complete_path.exists(): + complete = json.loads(complete_path.read_text()) + for name, digest in complete["outputs"].items(): + if file_sha256(output / name) != digest: + raise ValueError(f"Completed diagnostic artifact changed: {name}") + return complete + repository = Path(__file__).resolve().parents[2] + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent generated world changed") + saved = torch.load(weights, map_location="cpu", weights_only=False) + final = json.loads((run / "learning-complete.json").read_text()) + if ( + saved["config"] != config["model"] + or saved["step"] != step + or state_hash(saved["model"]) != final["model_sha256"] + ): + raise ValueError("Parent model identity mismatch") + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + with np.load(run / f"predictions-{step}.npz") as stored: + archived = {key: stored[key] for key in ("prediction", "ended")} + completed = [] + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + reference = run / "edits" / f"{name}-exception-mlp" + with np.load(reference / "sets.npz") as old: + for key in ("E", "replay", "exception"): + if not np.array_equal(old[key], pair[key]): + raise ValueError( + f"Original exception calibration permission changed: {name}/{key}" + ) + if not (reference / "complete.json").exists(): + raise ValueError("Original exception case is incomplete") + completed.append( + run_chain( + model, + world, + chain, + pair, + output / name, + device, + batch_size, + per_population, + archived, + ) + ) + print( + json.dumps({"event": "necessity_chain_complete", "run": str(run), "chain": name}), + flush=True, + ) + if _sources() != contract["sources"]: + raise ValueError("Diagnostic implementation changed during execution") + outputs = scientific_outputs(output) + complete = {"status": "complete", "chains": completed, "outputs": outputs} + write_json(complete_path, complete) + return complete diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..322ecd4a965475d9878cbb14cb7a3eee131cf9ca --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py @@ -0,0 +1,1082 @@ +"""P4 v2: unchanged interventions with explicit local numerical baselines. + +Q is fitted only on actual queries in an archived exception case's S union R, +grouped by the model's own membership predictions. Truth-matched donor queries +are a subsequent diagnostic, never calibration. Restoring a same-query clean +downstream signal tests recovery from an artificial lesion, not edit repair. +""" + +import csv +import json +from pathlib import Path + +import numpy as np +import torch + +from .bios_causal_paths import make_donor_plan +from .bios_cross import CHAINS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_mechanism_interventions import ( + Site, + attach_state_operation, + calibration_plan, + downstream_routing_site, + fit_predicted_group_bases, + match_delta_norm, + projection_component, + query_site_roles, + remove_projection, + restore_projection, + valid_predicted_groups, +) +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import file_sha256 +from .bios_train import precision + +SOURCE = Site(0, 2) +DOWNSTREAM = Site(1, 2) +RANK = 32 +NUMERICAL_POLICY = { + "version": "p4-numerical-policy-v2", + "original_identity_gate": "20608 queries; original order/batch512; exact archive values/EOS", + "subset_baseline": "Same query/order/batch local clean for every causal contrast", + "archive_subset_difference": "All queries and both outputs retained; no exclusions", + "donor_baseline": "Extra clean replay in duplicated recipient order and intervention batch", + "local_sham_and_rescue_only": "Strict exact value/EOS equality; never relaxed", + "restore_reference": "Unchanged v1 first-pass pre-answer source; pass drift remains recorded", + "scientific_design": "Candidate, rank, calibration, intervention, pairing, strata unchanged", + "precision": "Unchanged BF16 autocast; FP32 weights; TF32 allowed as in original training", +} +FAMILIES = ( + "default", + "actual", + "other_chain_default", + "attribute_3", + "attribute_4", + "attribute_5", + "attribute_6", + "membership", + "other_chain_actual", + "group_root", +) +ARMS = ( + "clean", + "sham", + "target_remove", + "random_remove", + "complement_remove", + "rescue_only", + "remove_rescue", + "remove_wrong_source_rescue", + "remove_random_rescue", +) +TRANSFER_TYPES = ( + "different_group_same_actual_different_default", + "different_group_same_default", + "different_group_same_default_same_actual", +) +TRANSFER_ARMS = ( + "sham", + "full_donor", + "full_norm_random", + "projected_target", + "projected_random", + "projected_complement", +) + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen diagnostic contract changed: {path}") + else: + write_json(path, value) + + +def _same_arrays(path, arrays): + if path.exists(): + with np.load(path) as existing: + if set(existing.files) != set(arrays) or any( + not np.array_equal(existing[key], value) for key, value in arrays.items() + ): + raise ValueError(f"Diagnostic plan changed: {path}") + else: + atomic_numpy_save(path, **arrays) + + +def _sources(): + directory = Path(__file__).parent + names = ( + "bios_mechanism_causal_v2.py", + "bios_mechanism_causal.py", + "bios_mechanism_interventions.py", + "bios_causal_paths.py", + "bios_cross.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_path_diagnostics.py", + ) + sources = {name: file_sha256(directory / name) for name in names} + runner = directory.parents[1] / "scripts/analyze_bios_mechanism_causal_v2.py" + sources["runner"] = file_sha256(runner) + return sources + + +def validate_lock(lock): + if (lock.get("mechanism"), lock.get("layer"), lock.get("position")) != ("default_path", 0, 2): + raise ValueError("This runner only instantiates the locked default_path L0/pos2 candidate") + if lock.get("known_only") is not False or not lock.get("locked_at_utc"): + raise ValueError("An all-eligible, timestamped candidate lock is required") + + +def make_probe_plan(world, chain, recipients): + """Same people and fixed queries in every intervention, without knowledge filtering.""" + recipients = np.asarray(recipients, dtype=np.int64) + ids = [ + world.derived_ids[chain, recipients], + world.actual_ids[chain, recipients], + world.derived_ids[1 - chain, recipients], + ] + for relation in (3, 4, 5, 6): + candidates = np.flatnonzero(world.relation == relation) + by_person = np.full(len(world.actual_ids[chain]), -1, dtype=np.int64) + by_person[world.person[candidates]] = candidates + if (by_person[recipients] < 0).any(): + raise ValueError("An independent control query is missing") + ids.append(by_person[recipients]) + ids.extend([world.membership_ids[chain, recipients], world.actual_ids[1 - chain, recipients]]) + person_families = len(ids) + roots = world.root_ids[chain] + query_ids = np.concatenate([*ids, roots]) + return { + "query_id": query_ids, + "person": np.r_[np.tile(recipients, person_families), np.full(len(roots), -1)], + "family": np.r_[ + np.repeat(np.arange(person_families), len(recipients)), + np.full(len(roots), person_families), + ], + # -1 means not applicable; root facts are not ordinary people. + "recipient_old_exception": np.r_[ + np.tile(world.exceptions[chain, recipients].astype(np.int8), person_families), + np.full(len(roots), -1, dtype=np.int8), + ], + "answer": world.answers[query_ids], + } + + +def wrong_source_indices(families): + """Fixed one-person cyclic shift within each family, never chosen by answers.""" + families = np.asarray(families) + index = np.arange(len(families)) + for family in np.unique(families): + selected = np.flatnonzero(families == family) + if len(selected) < 2: + raise ValueError("Wrong-source controls require at least two queries per family") + index[selected] = np.roll(selected, 1) + return index + + +def make_transfer_plan(world, chain, per_population=64): + """Truth matching is restricted to this explicitly labeled offline diagnostic.""" + old = make_donor_plan(world, chain, per_population) + original = old["pair_type"] == 1 + recipients = old["recipient"][original] + train = world.person[world.train_ids[chain]] + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + rng = rng_for(world.seed, 978, chain) + donor_rows = [old["donor"][original]] + count_rows = [old["candidate_count"][original]] + for same_actual in (False, True): + donors, counts = [], [] + for recipient in recipients: + mask = (group[train] != group[recipient]) & (default[train] == default[recipient]) + if same_actual: + mask &= actual[train] == actual[recipient] + candidates = train[mask] + donors.append(rng.choice(candidates) if len(candidates) else -1) + counts.append(len(candidates)) + donor_rows.append(np.asarray(donors)) + count_rows.append(np.asarray(counts)) + donor = np.concatenate(donor_rows).astype(np.int64) + recipient = np.tile(recipients, len(TRANSFER_TYPES)) + safe = np.maximum(donor, 0) + return { + "case_id": np.arange(len(donor)), + "recipient": recipient, + "donor": donor, + "pair_type": np.repeat(np.arange(len(TRANSFER_TYPES)), len(recipients)), + "candidate_count": np.concatenate(count_rows), + "recipient_old_exception": world.exceptions[chain, recipient], + "same_actual": (actual[safe] == actual[recipient]) & (donor >= 0), + "same_default": (default[safe] == default[recipient]) & (donor >= 0), + "recipient_default": default[recipient], + "recipient_actual": actual[recipient], + "donor_default": np.where(donor >= 0, default[safe], -1), + "donor_actual": np.where(donor >= 0, actual[safe], -1), + } + + +def generate_queries( + model, prompts, lengths, device, batch_size=256, *, operations=None, capture_sites=() +): + """Two free generation passes with identical pre-answer operations, no answer input. + + operations(begin,end) returns (label, site, operation) triples. Every operation + returns its intended delta and availability; realized post-cast norms are + measured separately. Both passes are retained so norm matching is auditable. + """ + if len(prompts) == 0 or batch_size < 1: + raise ValueError("Generation needs nonempty queries and a positive batch size") + lengths = np.asarray(lengths) + if prompts.shape != (len(lengths), 5) or not np.isin(lengths, [4, 5]).all(): + raise ValueError("Unexpected symbolic query shape") + arrays = {"prediction": [], "ended": []} + for site in capture_sites: + query_site_roles(lengths, site.position) + arrays[f"state_{site.layer}_{site.position}"] = [] + calls = 0 + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + end = min(begin + batch_size, len(prompts)) + p = torch.as_tensor(prompts[begin:end], device=device) + n = torch.as_tensor(lengths[begin:end], device=device) + hooks, traces, captures = [], {}, {} + try: + for label, site, operation in () if operations is None else operations(begin, end): + query_site_roles(lengths[begin:end], site.position) + + def measured(value, operation=operation): + changed, trace = operation(value) + return changed, {**trace, "realized_delta": changed.float() - value.float()} + + hook, trace = attach_state_operation(model, site, measured) + hooks.append(hook) + traces[label] = trace + for site in capture_sites: + key = f"state_{site.layer}_{site.position}" + captures[key] = [] + + def capture( + _module, _inputs, output, key=key, position=site.position, captures=captures + ): + captures[key].append(output[:, position].detach().float()) + + hooks.append(model.blocks[site.layer].register_forward_hook(capture)) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + calls += 2 + arrays["prediction"].append(first.cpu().numpy()) + arrays["ended"].append(second.eq(EOS).cpu().numpy()) + for key, states in captures.items(): + arrays[key].append(states[0].cpu().numpy()) + drift = torch.linalg.vector_norm(states[1] - states[0], dim=-1) + arrays.setdefault(f"{key}_pass_drift", []).append(drift.cpu().numpy()) + for label, trace in traces.items(): + if len(trace) != 2: + raise ValueError( + "Every intervention must occur in both free-generation passes" + ) + for kind in ("delta", "realized_delta"): + norms = torch.stack( + [torch.linalg.vector_norm(t[kind].float(), dim=-1) for t in trace], + dim=1, + ) + arrays.setdefault(f"{label}_{kind}_norm", []).append(norms.cpu().numpy()) + valid = torch.stack([t["valid"] for t in trace], dim=1) + arrays.setdefault(f"{label}_valid", []).append(valid.cpu().numpy()) + finally: + for hook in hooks: + hook.remove() + result = {key: np.concatenate(value) for key, value in arrays.items()} + result.update( + forward_calls=np.asarray(calls), + forward_examples=np.asarray(2 * len(prompts)), + padded_token_positions=np.asarray(11 * len(prompts)), + logical_token_positions=np.asarray(int((2 * lengths + 1).sum())), + ) + return result + + +def _identity_trace(value): + return value, { + "delta": torch.zeros_like(value, dtype=torch.float32), + "valid": torch.ones(len(value), dtype=torch.bool, device=value.device), + } + + +def lesion_operations( + arm, source_bases, downstream_bases, clean_downstream, wrong_index, seed, device +): + """Return a deterministic batch factory. Wrong-source choice never sees truth.""" + if arm not in ARMS: + raise ValueError("Unknown necessity/restoration arm") + if arm == "clean": + return lambda _begin, _end: [] + if arm == "sham": + return lambda _begin, _end: [("source", SOURCE, _identity_trace)] + source = {key: basis.tensors(device) for key, basis in source_bases.items()} + downstream = ( + None + if downstream_bases is None + else {key: basis.tensors(device) for key, basis in downstream_bases.items()} + ) + needs_downstream = "rescue" in arm + if needs_downstream and downstream is None: + raise ValueError("Downstream basis is unavailable; recovery cannot be estimated") + wrong_index = np.asarray(wrong_index) + if len(wrong_index) != len(clean_downstream): + raise ValueError("Wrong-source plan length mismatch") + coefficients = ( + np.random.default_rng(seed) + .standard_normal((len(clean_downstream), source_bases["random"].rank)) + .astype(np.float32) + ) + + def factory(begin, end): + ops = [] + if arm == "clean": + return ops + if arm == "sham": + return [("source", SOURCE, _identity_trace)] + if arm != "rescue_only": + kind = ( + arm.removesuffix("_remove") + if arm in ("random_remove", "complement_remove") + else "target" + ) + q, mean, _ = source[kind] + tq, tm, _ = source["target"] + + def remove(value): + reference = ( + None + if kind == "target" + else torch.linalg.vector_norm(projection_component(value, tq, tm), dim=-1) + ) + return remove_projection(value, q, mean, reference) + + ops.append(("source", SOURCE, remove)) + if needs_downstream: + clean = torch.as_tensor(clean_downstream[begin:end], device=device) + wrong = torch.as_tensor(clean_downstream[wrong_index[begin:end]], device=device) + tq = downstream["target"][0] + rq = downstream["random"][0] + noise = torch.as_tensor(coefficients[begin:end], device=device) @ rq.T + + def recover(value): + _, same_query_trace = restore_projection(value, clean, tq) + correct_delta = same_query_trace["delta"] + reference = torch.linalg.vector_norm(correct_delta, dim=-1) + if arm == "remove_wrong_source_rescue": + return restore_projection(value, wrong, tq, reference) + if arm == "remove_random_rescue": + delta, valid = match_delta_norm(noise, reference) + return value + delta.to(value.dtype), {"delta": delta, "valid": valid} + return restore_projection(value, clean, tq) + + ops.append(("downstream", DOWNSTREAM, recover)) + return ops + + return factory + + +def transfer_operations(arm, bases, recipient, donor, seed, device): + """A locked-basis manipulation check, never a basis-fitting input.""" + if arm not in TRANSFER_ARMS or recipient.shape != donor.shape: + raise ValueError("Invalid donor manipulation") + if arm.startswith("projected_") and bases is None: + raise ValueError("Projected donor diagnostic requires an available source basis") + full_delta = donor.astype(np.float32) - recipient.astype(np.float32) + if arm == "sham": + delta, valid = np.zeros_like(full_delta), np.ones(len(donor), dtype=bool) + elif arm == "full_donor": + delta, valid = full_delta, np.ones(len(donor), dtype=bool) + else: + if arm == "full_norm_random": + raw = np.random.default_rng(seed).standard_normal(full_delta.shape).astype(np.float32) + reference = np.linalg.norm(full_delta, axis=-1) + else: + tq = bases["target"].q + target_delta = (full_delta @ tq) @ tq.T + reference = np.linalg.norm(target_delta, axis=-1) + q = bases[arm.removeprefix("projected_")].q + raw = (full_delta @ q) @ q.T + matched, available = match_delta_norm(torch.from_numpy(raw), torch.from_numpy(reference)) + delta, valid = matched.numpy(), available.numpy() + + def factory(begin, end): + change = torch.as_tensor(delta[begin:end], device=device) + available = torch.as_tensor(valid[begin:end], device=device) + + def operation(value): + return value + change.to(value.dtype), {"delta": change, "valid": available} + + return [("source", SOURCE, operation)] + + return factory + + +def _availability(arrays): + valid = np.ones(len(arrays["prediction"]), dtype=bool) + for key, value in arrays.items(): + if key.endswith("_valid"): + valid &= value.all(axis=1) + return valid + + +def score_rows(arrays, baseline, plan, arm, labels=FAMILIES, label_key="family"): + """All eligible rows first; original-correct strata remain descriptive only.""" + base_correct = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + correct = (arrays["prediction"] == plan["answer"]) & arrays["ended"] + available = _availability(arrays) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available + n, nb = int(chosen.sum()), int((chosen & base_correct).sum()) + before, after = int((chosen & base_correct).sum()), int((chosen & correct).sum()) + row = { + "arm": arm, + "family": family, + "population": population, + "requested": int(requested.sum()), + "available": n, + "unavailable": int((requested & ~available).sum()), + "baseline_correct": before, + "correct": after, + "accuracy": after / n if n else None, + "delta_accuracy": (after - before) / n if n else None, + "known_became_wrong": int((chosen & base_correct & ~correct).sum()), + "wrong_became_correct": int((chosen & ~base_correct & correct).sum()), + "known_denominator": nb, + "known_retention": int((chosen & base_correct & correct).sum()) / nb + if nb + else None, + "termination_error": int((chosen & ~arrays["ended"]).sum()), + "prediction_changed": int( + ( + chosen + & ( + (arrays["prediction"] != baseline["prediction"]) + | (arrays["ended"] != baseline["ended"]) + ) + ).sum() + ), + } + for label in ("source", "downstream"): + for kind in ("delta", "realized_delta"): + key = f"{label}_{kind}_norm" + row[f"mean_{key}"] = ( + float(arrays[key][chosen, 0].mean()) if n and key in arrays else None + ) + rows.append(row) + return rows + + +def paired_score_rows( + left, right, baseline, plan, left_name, right_name, labels=FAMILIES, label_key="family" +): + """Contrasts use a common availability mask, never unmatched denominators.""" + correct_left = (left["prediction"] == plan["answer"]) & left["ended"] + correct_right = (right["prediction"] == plan["answer"]) & right["ended"] + correct_clean = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + available_left, available_right = _availability(left), _availability(right) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available_left & available_right + n = int(chosen.sum()) + nl, nr = int((chosen & correct_left).sum()), int((chosen & correct_right).sum()) + known_right_wrong = chosen & correct_clean & ~correct_right + denominator = int(known_right_wrong.sum()) + rows.append( + { + "left": left_name, + "right": right_name, + "family": family, + "population": population, + "requested": int(requested.sum()), + "common_available": n, + "left_unavailable": int((requested & ~available_left).sum()), + "right_unavailable": int((requested & ~available_right).sum()), + "left_correct": nl, + "right_correct": nr, + "accuracy_difference": (nl - nr) / n if n else None, + "right_wrong_left_correct": int((chosen & ~correct_right & correct_left).sum()), + "right_correct_left_wrong": int((chosen & correct_right & ~correct_left).sum()), + "original_known_right_wrong": denominator, + "original_known_right_wrong_left_recovered": int( + (known_right_wrong & correct_left).sum() + ), + "conditional_recovery_auxiliary": int((known_right_wrong & correct_left).sum()) + / denominator + if denominator + else None, + } + ) + return rows + + +def _check_predictions(generated, archived, ids): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], archived[key][ids]): + raise ValueError(f"Clean frozen-model generation differs from archive: {key}") + + +def record_archive_comparison(path, generated, archived, ids): + """Archive differences are audited, never used for calibration or row selection.""" + ids = np.asarray(ids) + if generated["prediction"].shape != ids.shape or generated["ended"].shape != ids.shape: + raise ValueError("Local generation shape differs from its declared query plan") + if generated["ended"].dtype != bool or archived["ended"].dtype != bool: + raise ValueError("Archive and local termination masks must be boolean") + _same_arrays( + path, + { + "query_id": ids, + "local_prediction": generated["prediction"], + "local_ended": generated["ended"], + "archive_prediction": archived["prediction"][ids], + "archive_ended": archived["ended"][ids], + "prediction_changed": generated["prediction"] != archived["prediction"][ids], + "ended_changed": generated["ended"] != archived["ended"][ids], + }, + ) + + +def verify_original_replay(model, world, archived, output, device): + """Strong identity/numerical gate; original query order and batch remain exact.""" + ids = np.arange(len(world.answers)) + replay = _cached_generate(output / "original-replay.npz", model, world, ids, device, 512) + _check_predictions(replay, archived, ids) + _freeze_json( + output / "original-replay.json", + { + "status": "exact_archive_value_and_EOS_replay", + "queries": len(ids), + "batch_size": 512, + "prediction_differences": 0, + "ended_differences": 0, + "extra_identity_gate_cost": _cost(replay), + "raw_sha256": file_sha256(output / "original-replay.npz"), + }, + ) + return replay + + +def _cost(arrays): + return { + key: int(arrays[key]) + for key in ( + "forward_calls", + "forward_examples", + "padded_token_positions", + "logical_token_positions", + ) + } + + +def _cached_generate(path, model, world, ids, device, batch_size, **kwargs): + if path.exists(): + with np.load(path) as stored: + result = dict(stored) + if not np.array_equal(result.pop("query_id"), ids): + raise ValueError("Cached generation query plan differs") + return result + result = generate_queries( + model, world.prompts[ids], world.lengths[ids], device, batch_size, **kwargs + ) + atomic_numpy_save(path, query_id=ids, **result) + return result + + +def _fit_chain(model, world, chain, pair, dest, device, batch_size, archived): + plan = calibration_plan( + world.actual_ids[chain], + world.person, + world.membership_ids[chain], + pair["E"], + pair["replay"], + ) + _same_arrays( + dest / "calibration-plan.npz", {key: np.asarray(value) for key, value in plan.items()} + ) + actual = _cached_generate( + dest / "calibration-actual.npz", + model, + world, + plan["actual_query_ids"], + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + membership = _cached_generate( + dest / "calibration-membership.npz", + model, + world, + plan["membership_query_ids"], + device, + batch_size, + ) + record_archive_comparison( + dest / "archive-calibration-actual.npz", actual, archived, plan["actual_query_ids"] + ) + record_archive_comparison( + dest / "archive-calibration-membership.npz", + membership, + archived, + plan["membership_query_ids"], + ) + prefix = f"{CHAINS[chain]}:" + allowed = np.array( + [i for i, label in enumerate(world.token_labels) if label.startswith(prefix)] + ) + groups, valid = valid_predicted_groups(membership["prediction"], membership["ended"], allowed) + _same_arrays(dest / "self-predicted-groups.npz", {"prediction": groups, "valid": valid}) + bases, reports, basis_arrays = {}, {}, {} + for label, site in (("source", SOURCE), ("downstream", DOWNSTREAM)): + basis, report = fit_predicted_group_bases( + actual[f"state_{site.layer}_{site.position}"], groups, valid, rank=RANK, seed=74 + chain + ) + bases[label], reports[label] = basis, report + if basis is not None: + for kind, value in basis.items(): + for field in ("q", "mean", "scale"): + basis_arrays[f"{label}_{kind}_{field}"] = getattr(value, field) + _same_arrays(dest / "bases.npz", basis_arrays) + information = { + "S_count": len(pair["E"]), + "R_count": len(pair["replay"]), + "actual_queries": len(plan["actual_query_ids"]), + "additional_membership_queries": len(plan["membership_query_ids"]), + "derived_calibration_queries": 0, + "true_memberships_supplied": False, + "membership_syntax_rule": prefix, + "invalid_groups_never_replaced": True, + "calibration_cost": {"actual": _cost(actual), "membership": _cost(membership)}, + "basis_reports": reports, + "variant": "group_means", + "basis_sha256": file_sha256(dest / "bases.npz"), + } + _freeze_json(dest / "calibration.json", information) + # Truth is read only after Q and its information contract are frozen. These + # labels score calibration quality; they never select rows or alter Q. + membership_correct = ( + membership["prediction"] == world.answers[plan["membership_query_ids"]] + ) & membership["ended"] + _freeze_json( + dest / "calibration-diagnostics.json", + { + "role": "offline scoring after frozen Q; never fitting or row selection", + "queries": len(groups), + "valid_predictions": int(valid.sum()), + "valid_rate": float(valid.mean()), + "correct_predictions": int(membership_correct.sum()), + "accuracy": float(membership_correct.mean()), + "accuracy_given_valid_auxiliary": float(membership_correct[valid].mean()) + if valid.any() + else None, + "basis_sha256": information["basis_sha256"], + }, + ) + return bases + + +def run_chain(model, world, chain, pair, dest, device, batch_size, per_population, archived): + dest.mkdir(parents=True, exist_ok=True) + bases = _fit_chain(model, world, chain, pair, dest, device, batch_size, archived) + transfer = make_transfer_plan(world, chain, per_population) + _same_arrays(dest / "transfer-plan.npz", transfer) + recipients = transfer["recipient"][transfer["pair_type"] == 0] + plan = make_probe_plan(world, chain, recipients) + plan["wrong_source_index"] = wrong_source_indices(plan["family"]) + plan["wrong_source_query_id"] = plan["query_id"][plan["wrong_source_index"]] + plan["wrong_source_same_answer"] = plan["answer"] == plan["answer"][plan["wrong_source_index"]] + _same_arrays(dest / "probe-plan.npz", plan) + ids = plan["query_id"] + query_site_roles(world.lengths[ids], SOURCE.position) + if downstream_routing_site(SOURCE, len(model.blocks), world.lengths[ids] - 1) != DOWNSTREAM: + raise ValueError("Candidate/downstream site mismatch") + clean = _cached_generate( + dest / "clean.npz", + model, + world, + ids, + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + record_archive_comparison(dest / "archive-probe-clean.npz", clean, archived, ids) + rows, states, costs, arm_arrays = [], {}, {"clean": _cost(clean)}, {} + clean_down = clean[f"state_{DOWNSTREAM.layer}_{DOWNSTREAM.position}"] + for arm in ARMS: + if arm not in ("clean", "sham") and bases["source"] is None: + states[arm] = "unavailable_source_rank" + continue + if "rescue" in arm and bases["downstream"] is None: + states[arm] = "unavailable_downstream_rank" + continue + if arm == "clean": + generated = clean + else: + operations = lesion_operations( + arm, + bases["source"], + bases["downstream"], + clean_down, + plan["wrong_source_index"], + [world.seed, 979, chain], + device, + ) + generated = _cached_generate( + dest / f"{arm}.npz", model, world, ids, device, batch_size, operations=operations + ) + if arm in ("sham", "rescue_only"): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], clean[key]): + raise ValueError(f"No-lesion control changed output: {arm}/{key}") + rows.extend(score_rows(generated, clean, plan, arm)) + costs[arm], states[arm] = _cost(generated), "complete" + arm_arrays[arm] = generated + comparisons = [ + (arm, "clean") + for arm in ("sham", "target_remove", "random_remove", "complement_remove", "rescue_only") + ] + comparisons += [("target_remove", arm) for arm in ("random_remove", "complement_remove")] + comparisons += [ + (arm, "target_remove") + for arm in ("remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue") + ] + comparisons += [ + ("remove_rescue", arm) for arm in ("remove_wrong_source_rescue", "remove_random_rescue") + ] + paired_rows = [] + for left, right in comparisons: + if left in arm_arrays and right in arm_arrays: + paired_rows.extend( + paired_score_rows(arm_arrays[left], arm_arrays[right], clean, plan, left, right) + ) + # Donor activations are read only after both bases and their provenance are frozen. + valid = transfer["donor"] >= 0 + selected = {key: value[valid] for key, value in transfer.items()} + people = np.unique(np.r_[selected["recipient"], selected["donor"]]) + donor_ids = world.derived_ids[chain, people] + donor_clean = _cached_generate( + dest / "transfer-clean.npz", + model, + world, + donor_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + record_archive_comparison(dest / "archive-transfer-cache.npz", donor_clean, archived, donor_ids) + ri, di = ( + np.searchsorted(people, selected["recipient"]), + np.searchsorted(people, selected["donor"]), + ) + source_state = donor_clean[f"state_{SOURCE.layer}_{SOURCE.position}"] + # v2: the causal baseline has exactly the intervention query order and batch shape. + # The donor/recipient source cache and intervention delta definitions stay unchanged. + local_ids = world.derived_ids[chain, selected["recipient"]] + transfer_local = _cached_generate( + dest / "transfer-local-clean.npz", + model, + world, + local_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + record_archive_comparison( + dest / "archive-transfer-local-clean.npz", transfer_local, archived, local_ids + ) + _same_arrays( + dest / "transfer-reference-drift.npz", + { + "query_id": local_ids, + "cache_vs_local_state_norm": np.linalg.norm( + source_state[ri] - transfer_local["state_0_2"], axis=1 + ), + "cache_prediction": donor_clean["prediction"][ri], + "cache_ended": donor_clean["ended"][ri], + "local_prediction": transfer_local["prediction"], + "local_ended": transfer_local["ended"], + }, + ) + donor_baseline = {key: transfer_local[key] for key in ("prediction", "ended")} + donor_plan = {**selected, "answer": selected["recipient_default"]} + transfer_rows, transfer_status = [], {} + costs["transfer_clean"] = _cost(donor_clean) + costs["transfer_local_clean"] = _cost(transfer_local) + for arm in TRANSFER_ARMS: + if arm.startswith("projected_") and bases["source"] is None: + transfer_status[arm] = "unavailable_source_rank" + continue + ops = transfer_operations( + arm, + bases["source"], + source_state[ri], + source_state[di], + [world.seed, 980, chain], + device, + ) + generated = _cached_generate( + dest / f"transfer-{arm}.npz", + model, + world, + world.derived_ids[chain, selected["recipient"]], + device, + batch_size, + operations=ops, + ) + if arm == "sham": + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], donor_baseline[key]): + raise ValueError("Transfer sham changed output") + scored = score_rows( + generated, donor_baseline, donor_plan, arm, labels=TRANSFER_TYPES, label_key="pair_type" + ) + for row in scored: + code = TRANSFER_TYPES.index(row["family"]) + chosen = (selected["pair_type"] == code) & _availability(generated) + requested = transfer["pair_type"] == code + if row["population"] != "all": + exception = row["population"] == "old_exception" + chosen &= selected["recipient_old_exception"] == exception + requested &= transfer["recipient_old_exception"] == exception + row["plan_requested"] = int(requested.sum()) + row["missing_donors"] = int((requested & ~valid).sum()) + for role in ("recipient_actual", "donor_default", "donor_actual"): + matched = (generated["prediction"] == selected[role]) & generated["ended"] + base_matched = (donor_baseline["prediction"] == selected[role]) & donor_baseline[ + "ended" + ] + row[f"matches_{role}"] = int((chosen & matched).sum()) + row[f"baseline_matches_{role}"] = int((chosen & base_matched).sum()) + # Donor's own clean response is descriptive, not an eligibility filter. + row["donor_answered_default"] = int( + ( + chosen + & donor_clean["ended"][di] + & (donor_clean["prediction"][di] == selected["donor_default"]) + ).sum() + ) + transfer_rows.extend(scored) + transfer_status[arm], costs[f"transfer_{arm}"] = "complete", _cost(generated) + for filename, contents in ( + ("necessity.csv", rows), + ("paired-necessity.csv", paired_rows), + ("transfer.csv", transfer_rows), + ): + with (dest / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + dest / "status.json", + { + "arms": states, + "transfer_arms": transfer_status, + "evaluation_cost": costs, + "information_boundary": "truth-matched donor states are diagnostic only", + }, + ) + archive_rows = {} + for path in sorted(dest.glob("archive-*.npz")): + with np.load(path) as comparison: + archive_rows[path.stem] = { + "queries": len(comparison["query_id"]), + "prediction_differences": int(comparison["prediction_changed"].sum()), + "ended_differences": int(comparison["ended_changed"].sum()), + "case_exclusion": False, + } + write_json(dest / "archive-discrepancies.json", archive_rows) + return {"chain": CHAINS[chain], "arms": states, "transfer_arms": transfer_status} + + +def scientific_outputs(output): + """Seal only producer-owned artifacts, excluding mutable queue logs and locks.""" + names = { + "archive-calibration-actual.npz", + "archive-calibration-membership.npz", + "archive-probe-clean.npz", + "archive-transfer-cache.npz", + "archive-transfer-local-clean.npz", + "archive-discrepancies.json", + "transfer-local-clean.npz", + "transfer-reference-drift.npz", + "calibration-plan.npz", + "calibration-actual.npz", + "calibration-membership.npz", + "self-predicted-groups.npz", + "bases.npz", + "calibration.json", + "calibration-diagnostics.json", + "transfer-plan.npz", + "probe-plan.npz", + "transfer-clean.npz", + "necessity.csv", + "paired-necessity.csv", + "transfer.csv", + "status.json", + } + names.update(f"{arm}.npz" for arm in ARMS) + names.update(f"transfer-{arm}.npz" for arm in TRANSFER_ARMS) + paths = [ + output / "contract.json", + output / "original-replay.npz", + output / "original-replay.json", + ] + for chain in CHAINS: + paths.extend( + output / chain / name for name in sorted(names) if (output / chain / name).exists() + ) + return {str(path.relative_to(output)): file_sha256(path) for path in paths} + + +def run_model(run, output, lock_path, *, device="cuda", batch_size=256, per_population=64): + """One original pre-edit checkpoint, both chains; separate outputs, restartable nodes.""" + run, output, lock_path = Path(run).resolve(), Path(output).resolve(), Path(lock_path).resolve() + if output == run or run in output.parents: + raise ValueError("Never write diagnostics inside the frozen parent") + lock = json.loads(lock_path.read_text()) + validate_lock(lock) + config = json.loads((run / "config.json").read_text()) + if ( + config["world"] not in (0, 1) + or config["model"]["width"] not in (256, 768) + or config["seed"] not in (0, 1) + or config["condition"] not in (*CHAINS, "neither") + ): + raise ValueError("The original 24-model development matrix is required") + step = config["study"]["steps"] + if step != 15360 or per_population != 64: + raise ValueError("The parent step and 64+64 recipient budget are fixed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent runtime differs: {key}") + device = torch.device(device) + weights = run / f"model-{step}.pt" + contract = { + "numerical_policy": NUMERICAL_POLICY, + "run": str(run), + "step": step, + "world": config["world"], + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "parent_config_sha256": file_sha256(run / "config.json"), + "parent_weights_sha256": file_sha256(weights), + "lock": lock, + "lock_sha256": file_sha256(lock_path), + "sources": _sources(), + "source_site": [0, 2], + "downstream_site": [1, 2], + "rank": RANK, + "per_population": per_population, + "batch_size": batch_size, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": device.type, + "checkpoint_role": "pre_edit_clean_only", + "calibration": "S_union_R_actual_queries_with_self_predicted_membership_groups", + "families": list(FAMILIES), + "arms": list(ARMS), + "transfer_types": list(TRANSFER_TYPES), + "transfer_arms": list(TRANSFER_ARMS), + "wrong_source_rule": "cyclic_previous_query_within_family_no_truth_or_prediction_selection", + "cross_query_reference": "The actual-calibration mean is reused for all query families", + "recovery_source": "Same checkpoint and same query clean post-L1/pos2 target projection", + "rescue_only_role": "No-lesion downstream sham; cannot establish necessity", + "random_recovery": "Random rank32 downstream basis; same-query recovery delta norm", + "rank_failure": "Unavailable, never padded or replaced; report coverage by organization", + "interpretation": ( + "Artificial-lesion behavior recovery; no claim of edit repair " + "or organizational specificity" + ), + } + output.mkdir(parents=True, exist_ok=True) + _freeze_json(output / "contract.json", contract) + complete_path = output / "complete.json" + if complete_path.exists(): + complete = json.loads(complete_path.read_text()) + for name, digest in complete["outputs"].items(): + if file_sha256(output / name) != digest: + raise ValueError(f"Completed diagnostic artifact changed: {name}") + return complete + repository = Path(__file__).resolve().parents[2] + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent generated world changed") + saved = torch.load(weights, map_location="cpu", weights_only=False) + final = json.loads((run / "learning-complete.json").read_text()) + if ( + saved["config"] != config["model"] + or saved["step"] != step + or state_hash(saved["model"]) != final["model_sha256"] + ): + raise ValueError("Parent model identity mismatch") + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + with np.load(run / f"predictions-{step}.npz") as stored: + archived = {key: stored[key] for key in ("prediction", "ended")} + verify_original_replay(model, world, archived, output, device) + completed = [] + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + reference = run / "edits" / f"{name}-exception-mlp" + with np.load(reference / "sets.npz") as old: + for key in ("E", "replay", "exception"): + if not np.array_equal(old[key], pair[key]): + raise ValueError( + f"Original exception calibration permission changed: {name}/{key}" + ) + if not (reference / "complete.json").exists(): + raise ValueError("Original exception case is incomplete") + completed.append( + run_chain( + model, + world, + chain, + pair, + output / name, + device, + batch_size, + per_population, + archived, + ) + ) + print( + json.dumps({"event": "necessity_chain_complete", "run": str(run), "chain": name}), + flush=True, + ) + if _sources() != contract["sources"]: + raise ValueError("Diagnostic implementation changed during execution") + outputs = scientific_outputs(output) + complete = {"status": "complete", "chains": completed, "outputs": outputs} + write_json(complete_path, complete) + return complete diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_mechanism_edit.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_mechanism_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..6e51c693528d73250f62b70686f96b42b7eb9e4f --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_mechanism_edit.py @@ -0,0 +1,611 @@ +"""P1 counterfactual edits with frozen parent models and exact restart state. + +The supervised pool S is fixed at 93 facts. E_changed, propagation D, and +unchanged U are recomputed from each arm's truth, independently of that pool. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_cross_train import evaluate, tensor_queries +from .bios_cross_train import source_hashes as parent_source_hashes +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +ARMS = ("old-fact-rehearsal", "root-only", "actual-only", "class-balanced-exception") +OPTIONAL_ARM = "all-freeze-embedding" +REFERENCE_ARMS = ("coherent", "exception") +DEFAULT_STUDY = { + "protocol": "v2.8-development-mechanism-P1", + "widths": [256, 768], + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "arms": list(ARMS), + "edit_steps": 512, + "edit_checkpoints": [0, 32, 128, 512], + "edit_lr": 3e-5, + "retention_kl": 1.0, + "batch_size": 128, + "save_every": 32, + "gradient_steps": [0, 31, 127, 511], +} + + +def load_study(path=None, arms=None): + study = json.loads(json.dumps(DEFAULT_STUDY)) + if path: + supplied = json.loads(Path(path).read_text()) + unknown = set(supplied) - set(study) + if unknown: + raise ValueError(f"Unknown P1 configuration keys: {sorted(unknown)}") + study.update(supplied) + if arms is not None: + study["arms"] = list(arms) + if not study["arms"] or len(set(study["arms"])) != len(study["arms"]): + raise ValueError("At least one unique arm is required") + if set(study["arms"]) - set((*ARMS, OPTIONAL_ARM)): + raise ValueError("Unknown P1 arm") + if study["edit_steps"] < 1 or study["batch_size"] != 128 or study["save_every"] < 1: + raise ValueError("Positive budgets and the original batch size 128 are required") + checkpoints = study["edit_checkpoints"] + if not checkpoints or checkpoints != sorted(set(checkpoints)) or checkpoints[0] != 0: + raise ValueError("Checkpoints must be unique, ordered, and include zero") + if checkpoints[-1] != study["edit_steps"]: + raise ValueError("The final checkpoint must equal the fixed edit budget") + if study["edit_lr"] <= 0 or study["retention_kl"] < 0: + raise ValueError("Invalid optimization settings") + for key in ("widths", "worlds", "seeds", "conditions"): + if not study[key] or len(set(study[key])) != len(study[key]): + raise ValueError(f"Nonempty, unique matrix entries required: {key}") + if set(study["conditions"]) - set(CONDITIONS): + raise ValueError("Unknown organization condition") + return study + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def source_hashes(): + result = parent_source_hashes() + result[Path(__file__).name] = file_hash(__file__) + runner = Path(__file__).resolve().parents[2] / "scripts/run_bios_mechanism_edit.py" + result[runner.name] = file_hash(runner) + return result + + +def sampling_streams(world, chain, steps=512, batch_size=128): + """Match the original generator, including the order of its two draws.""" + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + supervised = rng.integers(len(pair["E"]), size=(steps, batch_size)) + replay = rng.integers(len(pair["replay"]), size=(steps, batch_size)) + return supervised, replay + + +def make_arm(world, chain, arm, pair=None): + if arm not in (*ARMS, OPTIONAL_ARM, *REFERENCE_ARMS): + raise ValueError(f"Unknown arm: {arm}") + pair = edit_pair(world, chain) if pair is None else pair + supervised = pair["E"].copy() + root = np.intersect1d(supervised, world.root_ids[chain]) + actual = np.intersect1d(supervised, world.actual_ids[chain]) + assert (len(supervised), len(root), len(actual)) == (93, 3, 90) + target = world.answers.copy() + if arm == "root-only": + target[root] = pair["exception"][root] + elif arm == "actual-only": + target[actual] = pair["exception"][actual] + elif arm in ("exception", "class-balanced-exception", OPTIONAL_ARM): + target[supervised] = pair["exception"][supervised] + elif arm == "coherent": + target[supervised] = pair["coherent"][supervised] + # Recompute derived truth, rather than copying the original D declaration. + for task in range(2): + target[world.derived_ids[task]] = target[world.root_ids[task, world.memberships[task]]] + changed = target != world.answers + e = np.flatnonzero(changed & (world.relation < 10)) + d = np.flatnonzero(changed & (world.relation >= 10)) + u = np.flatnonzero(~changed) + if not np.isin(e, supervised).all() or not np.array_equal( + target[pair["replay"]], world.answers[pair["replay"]] + ): + raise ValueError("Supervision or common retention pool violates the truth contract") + if np.intersect1d(pair["replay"], supervised).size: + raise ValueError("The replay pool overlaps S") + selected_people = np.isin(world.memberships[chain], pair["groups"]) + selected_facts = (world.person >= 0) & selected_people[np.maximum(world.person, 0)] + old_exceptions = np.zeros(len(world.answers), dtype=bool) + old_exceptions[world.actual_ids[chain, selected_people & world.exceptions[chain]]] = True + relevant = np.isin(world.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(world.answers), -1, dtype=np.int64) + strata[~changed & old_exceptions] = 0 + strata[~changed & selected_facts & ~old_exceptions] = 1 + strata[~changed & ~selected_facts & relevant] = 2 + strata[~changed & ~selected_facts & ~relevant] = 3 + assert np.array_equal(strata >= 0, ~changed) + supervised_unchanged = np.intersect1d(supervised, u) + probe_unchanged = np.intersect1d(pair["D"], u) + supplied = np.union1d(supervised, pair["replay"]) + # Keep the archived heldout pool; add newly unchanged D, which is never trained. + heldout = np.setdiff1d( + np.intersect1d(np.union1d(pair["heldout"], probe_unchanged), u), supplied + ) + weights = np.ones(len(supervised), dtype=np.float64) + root_mask = np.isin(supervised, root) + if arm == "class-balanced-exception": + weights[root_mask] = len(supervised) / (2 * len(root)) + weights[~root_mask] = len(supervised) / (2 * len(actual)) + return { + "target": target, + "S": supervised, + "S_root": root, + "S_actual": actual, + "S_root_mask": root_mask, + "S_weights": weights, + "E_changed": e, + "E_changed_root": np.intersect1d(e, root), + "E_changed_actual": np.intersect1d(e, actual), + "D": d, + "D_conflict": np.intersect1d(d, pair["conflict_D"]), + "D_probe": pair["D"], + "D_probe_conflict": pair["conflict_D"], + "D_probe_unchanged": probe_unchanged, + "U": u, + "strata": strata, + "heldout": heldout, + "unseen": np.setdiff1d(u, supplied), + "S_unchanged": supervised_unchanged, + "replay": pair["replay"], + "other_chain": np.flatnonzero( + ~changed & np.isin(world.relation, [7, 8, 9, 11] if chain == 0 else [0, 1, 2, 10]) + ), + "independent": np.flatnonzero(~changed & np.isin(world.relation, [3, 4, 5, 6])), + "groups": pair["groups"], + } + + +def accuracy(correct, ids): + return { + "n": len(ids), + "correct": int(correct[ids].sum()), + "accuracy": float(correct[ids].mean()) if len(ids) else None, + } + + +def retention(correct, old_correct, ids): + known = ids[old_correct[ids]] + broken = int((~correct[known]).sum()) + return { + "n": len(ids), + "known": len(known), + "unknown": len(ids) - len(known), + "broken": broken, + "rate": broken / len(known) if len(known) else None, + } + + +def arm_metrics(world, spec, arrays, old_correct): + correct = arrays["correct"] + result = { + name: accuracy(correct, spec[name]) + for name in ( + "S", + "S_root", + "S_actual", + "E_changed", + "E_changed_root", + "E_changed_actual", + "D", + "D_conflict", + "D_probe", + ) + } + for name in ("D", "D_conflict", "D_probe", "D_probe_conflict"): + for split, pool in (("trained", world.train_ids), ("heldout", world.heldout_ids)): + result[f"{name}_{split}"] = accuracy(correct, np.intersect1d(spec[name], pool)) + for name, pool in ( + ("full", spec["U"]), + ("heldout", spec["heldout"]), + ("unseen", spec["unseen"]), + ): + result[f"U_{name}"] = retention(correct, old_correct, pool) + result[f"U_{name}_strata"] = { + str(group): retention( + correct, old_correct, np.intersect1d(pool, np.flatnonzero(spec["strata"] == group)) + ) + for group in range(4) + } + for name in ("S_unchanged", "D_probe_unchanged", "replay", "other_chain", "independent"): + result[f"U_{name}"] = retention(correct, old_correct, spec[name]) + return result + + +def weighted_supervision(logits, labels, weights): + """Average over sampled examples, never renormalize observed class mass.""" + losses = F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), reduction="none") + per_example = losses.reshape(len(labels), -1).mean(-1) + return (per_example * weights).mean(), per_example + + +def select_edit_parameters(model, arm): + if arm != OPTIONAL_ARM: + return select_parameters(model, "mlp", 3) + selected = select_parameters(model, "all") + model.token.weight.requires_grad_(False) + return [parameter for parameter in selected if parameter.requires_grad] + + +def _gradient_norm(loss, selected): + gradients = torch.autograd.grad(loss, selected, retain_graph=True, allow_unused=True) + total = sum(g.detach().float().square().sum() for g in gradients if g is not None) + return float(torch.sqrt(total)) if isinstance(total, torch.Tensor) else 0.0 + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen contract mismatch: {path}") + else: + write_json(path, value) + + +def _contract_hash(contract): + return hashlib.sha256(json.dumps(contract, sort_keys=True).encode()).hexdigest() + + +def _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device): + return { + "model": model.state_dict(), + "config": model.config_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "contract_sha256": _contract_hash(contract), + "timeline": timeline, + "update_stats": stats, + "seconds": seconds, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + } + + +def run_case(model, baseline_state, world, data, old_arrays, chain, arm, dest, study, parent): + """Run or resume one fixed-budget case; no evaluation result changes training.""" + dest = Path(dest) + dest.mkdir(parents=True, exist_ok=True) + device = data["tokens"].device + spec = make_arm(world, chain, arm) + e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"], study["batch_size"]) + contract = { + "parent": parent, + "study": study, + "chain": CHAINS[chain], + "arm": arm, + "sources": source_hashes(), + "sets_sha256": {key: array_hash(value) for key, value in spec.items()}, + "edit_sampling_sha256": array_hash(e_choices), + "replay_sampling_sha256": array_hash(r_choices), + "old_correct_sha256": array_hash(old_arrays["correct"]), + } + _freeze_json(dest / "contract.json", contract) + if (dest / "complete.json").exists(): + completed = json.loads((dest / "complete.json").read_text()) + if completed["contract_sha256"] != _contract_hash(contract): + raise ValueError("Completion contract mismatch") + return completed + model.load_state_dict(baseline_state) + selected = select_edit_parameters(model, arm) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(spec["replay"]), 256): + ids = torch.as_tensor(spec["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + new_data = tensor_queries(world, device, spec["target"]) + atomic_numpy_save( + dest / "sets.npz", + **spec, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, stats, seconds = 0, [], [], 0.0 + resume_path = dest / "resume.pt" + if resume_path.exists(): + state = torch.load(resume_path, map_location="cpu", weights_only=False) + if state["contract_sha256"] != _contract_hash(contract): + raise ValueError("Resume contract mismatch") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + first, timeline, stats, seconds = ( + state["step"], + state["timeline"], + state["update_stats"], + state["seconds"], + ) + if len(stats) != first or first > study["edit_steps"]: + raise ValueError("Invalid restart progress") + torch.set_rng_state(state["torch_rng"]) + if device.type == "cuda": + torch.cuda.set_rng_state(state["cuda_rng"], device) + weights = torch.as_tensor(spec["S_weights"], device=device, dtype=torch.float32) + root_mask = torch.as_tensor(spec["S_root_mask"], device=device) + for step in range(first, study["edit_steps"] + 1): + if step in study["edit_checkpoints"] and not any(p["step"] == step for p in timeline): + arrays = evaluate(model, data, spec["target"]) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + timeline.append( + { + "step": step, + **arm_metrics(world, spec, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + ) + write_json(dest / "trajectory.json", timeline) + if step % study["save_every"] == 0 or step in study["edit_checkpoints"]: + atomic_torch_save( + _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device), + resume_path, + ) + write_json(dest / "update-stats.json", stats) + if step == study["edit_steps"]: + break + model.train() + optimizer.zero_grad(set_to_none=True) + choices = torch.as_tensor(e_choices[step], device=device) + ei = torch.as_tensor(spec["S"][e_choices[step]], device=device) + replay_choices = torch.as_tensor(r_choices[step], device=device) + ri = torch.as_tensor(spec["replay"][r_choices[step]], device=device) + roots = root_mask[choices] + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce, per_example = weighted_supervision(logits, new_data["labels"][ei], weights[choices]) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[replay_choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + study["retention_kl"] * kl + point = { + "step": step + 1, + "root_samples": int(roots.sum()), + "actual_samples": int((~roots).sum()), + "ce": float(ce.detach()), + "kl": float(kl.detach()), + "loss": float(loss.detach()), + } + if step in study["gradient_steps"]: + for name, mask in (("root", roots), ("actual", ~roots)): + component = (per_example * weights[choices] * mask).mean() + point[f"{name}_ce_gradient_norm"] = _gradient_norm(component, selected) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite P1 edit") + point["total_gradient_norm"] = float(norm) + point["gradient_clipped"] = bool(norm > 1) + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + stats.append(point) + if (step + 1) % 128 == 0: + print( + json.dumps({"event": "progress", "case": dest.name, "step": step + 1}), flush=True + ) + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": study["edit_steps"]}, + dest / "model-final.pt", + ) + completed = { + "status": "complete", + "contract_sha256": _contract_hash(contract), + "final_model_sha256": state_hash(model.state_dict()), + "parameters_updated": sum(p.numel() for p in selected), + "final": timeline[-1], + "root_samples": sum(p["root_samples"] for p in stats), + "actual_samples": sum(p["actual_samples"] for p in stats), + "clipped_updates": sum(p["gradient_clipped"] for p in stats), + } + if source_hashes() != contract["sources"]: + raise ValueError("P1 source files changed during this edit") + write_json(dest / "complete.json", completed) + return completed + + +def rescore_references(world, baseline, out, study, old_correct, parent): + """Archive provenance and recompute metrics without mutating historical files.""" + for chain, name in enumerate(CHAINS): + e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"]) + pair = edit_pair(world, chain) + for arm in REFERENCE_ARMS: + source = baseline / "edits" / f"{name}-{arm}-mlp" + spec = make_arm(world, chain, arm, pair) + with np.load(source / "sets.npz") as archived: + for key, expected in ( + ("E", spec["S"]), + ("replay", spec["replay"]), + ("edit_sampling", e_choices), + ("replay_sampling", r_choices), + ("old_correct", old_correct), + (arm, spec["target"]), + ): + if not np.array_equal(archived[key], expected): + raise ValueError(f"Reference reuse contract failed for {source}/{key}") + if not (source / "complete.json").exists(): + raise ValueError(f"Historical reference is incomplete: {source}") + timeline, hashes = [], {} + for step in study["edit_checkpoints"]: + path = source / f"predictions-{step}.npz" + with np.load(path) as stored: + arrays = {key: stored[key] for key in ("prediction", "ended", "correct")} + recomputed = (arrays["prediction"] == spec["target"]) & arrays["ended"] + if not np.array_equal(arrays["correct"], recomputed): + raise ValueError("Historical prediction correctness mismatch") + timeline.append({"step": step, **arm_metrics(world, spec, arrays, old_correct)}) + hashes[path.name] = file_hash(path) + dest = out / "references" / f"{name}-{arm}-mlp" + dest.mkdir(parents=True, exist_ok=True) + _freeze_json( + dest / "contract.json", {"parent": parent, "source": str(source), "files": hashes} + ) + atomic_numpy_save(dest / "sets.npz", **spec, old_correct=old_correct) + write_json(dest / "trajectory.json", timeline) + + +def run_model(baseline, output, study, device): + baseline, output = Path(baseline).resolve(), Path(output).resolve() + if output == baseline or baseline in output.parents: + raise ValueError("P1 results must not be written inside a frozen parent directory") + output.mkdir(parents=True, exist_ok=True) + config_path = baseline / "config.json" + config = json.loads(config_path.read_text()) + if config["sources"] != parent_source_hashes(): + raise ValueError("Frozen parent training sources have changed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent and P1 runtime differ: {key}") + parent_study = config["study"] + for key in ("edit_steps", "edit_checkpoints", "edit_lr", "retention_kl"): + if study[key] != parent_study[key]: + raise ValueError(f"Historical reference configuration differs: {key}") + parent_step = parent_study["steps"] + weights_path = baseline / f"model-{parent_step}.pt" + saved = torch.load(weights_path, map_location="cpu", weights_only=False) + if saved["config"] != config["model"] or saved["step"] != parent_step: + raise ValueError("Parent weight configuration mismatch") + final = json.loads((baseline / "learning-complete.json").read_text()) + if state_hash(saved["model"]) != final["model_sha256"]: + raise ValueError("Parent model state hash mismatch") + world = make_cross_world(config["world"]) + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent world does not match the current generated truth") + parent = { + "directory": str(baseline), + "config_sha256": file_hash(config_path), + "weights_sha256": file_hash(weights_path), + "model_sha256": final["model_sha256"], + "width": config["model"]["width"], + "world": config["world"], + "seed": config["seed"], + "condition": config["condition"], + "step": parent_step, + } + runtime = { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "python": platform.python_version(), + "numpy": np.__version__, + "device_type": device.type, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "precision": "BF16 autocast; FP32 weights and optimizer" + if device.type == "cuda" + else "FP32", + } + contract = {"parent": parent, "study": study, "sources": source_hashes(), "runtime": runtime} + _freeze_json(output / "contract.json", contract) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.cuda.manual_seed_all(config["seed"]) + torch.manual_seed(config["seed"]) + model = CausalLM(ModelConfig(**saved["config"])).to(device) + model.load_state_dict(saved["model"]) + data = tensor_queries(world, device) + old_arrays = evaluate(model, data, world.answers) + with np.load(baseline / f"predictions-{parent_step}.npz") as archived: + for key in ("correct", "prediction", "ended"): + if not np.array_equal(old_arrays[key], archived[key]): + raise ValueError(f"Parent predictions changed under this runtime: {key}") + atomic_numpy_save(output / "baseline-predictions.npz", **old_arrays) + write_json( + output / "runtime.json", + {**runtime, "device": str(device), "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES")}, + ) + rescore_references(world, baseline, output, study, old_arrays["correct"], parent) + completed = [] + for chain, name in enumerate(CHAINS): + for arm in study["arms"]: + dest = output / "edits" / f"{name}-{arm}" + result = run_case( + model, saved["model"], world, data, old_arrays, chain, arm, dest, study, parent + ) + completed.append(f"{name}-{arm}") + write_json( + output / "status.json", + {"state": "running", "complete": completed, "updated": time.time()}, + ) + print( + json.dumps( + {"event": "edit_complete", "case": dest.name, "D": result["final"]["D"]} + ), + flush=True, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "contract_sha256": _contract_hash(contract), + "edit_cases": len(completed), + "cases": completed, + "references": 4, + }, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config") + parser.add_argument("--arms", nargs="+", choices=(*ARMS, OPTIONAL_ARM)) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + args = parser.parse_args() + study = load_study(args.config, args.arms) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + try: + run_model(args.baseline, out, study, torch.device(args.device)) + except Exception as exc: + write_json(out / "failure.json", {"type": type(exc).__name__, "message": str(exc)}) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py new file mode 100644 index 0000000000000000000000000000000000000000..4d87971e01bb7f679239d58f88ea4ac1b054eb88 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py @@ -0,0 +1,375 @@ +"""Uninstantiated P4 projection diagnostics and equal-parameter branches. + +These operators do not choose a real layer, fit a real model's basis, read world +membership truth, or run an experiment. The caller must freeze a candidate and +an information budget first. Group means are not, by themselves, evidence of +an organizational representation. +""" + +from dataclasses import dataclass + +import numpy as np +import torch + + +@dataclass(frozen=True) +class Site: + layer: int + position: int + + +@dataclass(frozen=True) +class Basis: + q: np.ndarray + mean: np.ndarray + scale: np.ndarray + + @property + def rank(self): + return self.q.shape[1] + + def tensors(self, device): + return tuple( + torch.as_tensor(value, dtype=torch.float32, device=device) + for value in (self.q, self.mean, self.scale) + ) + + +def calibration_plan(actual_query_ids, person_by_query, membership_query_ids, supervised, replay): + """Only actual queries in S union R; bridge IDs specify additional self-queries. + + All arguments are query/identity metadata. No group truth or answers are + accepted. In particular this never constructs a derived query to fit Q. + """ + allowed = np.union1d(supervised, replay) + actual = np.intersect1d(actual_query_ids, allowed) + people = np.asarray(person_by_query)[actual] + if (people < 0).any() or len(np.unique(people)) != len(people): + raise ValueError("Calibration must contain one actual query per valid person") + membership = np.asarray(membership_query_ids)[people] + return { + "actual_query_ids": actual, + "person_ids": people, + "membership_query_ids": membership, + "logical_actual_queries": len(actual), + "logical_additional_membership_queries": len(membership), + "derived_calibration_queries": 0, + } + + +def valid_predicted_groups(prediction, ended, allowed_group_tokens): + prediction, ended = np.asarray(prediction), np.asarray(ended) + if prediction.ndim != 1 or ended.shape != prediction.shape or ended.dtype != bool: + raise ValueError("Group predictions require one value and a boolean termination mask") + valid = ended & np.isin(prediction, allowed_group_tokens) + # Invalid predictions are recorded, never replaced with the true group. + return np.where(valid, prediction, -1), valid + + +def _row_span(values, relative_tolerance=1e-6, absolute_tolerance=1e-8): + _, singular, vh = np.linalg.svd(values, full_matrices=False) + threshold = ( + max(absolute_tolerance, relative_tolerance * singular[0]) + if len(singular) + else absolute_tolerance + ) + numerical_rank = int((singular > threshold).sum()) + return vh[:numerical_rank].T, singular, numerical_rank + + +def _orthogonal_residual(values, q): + return values - (values @ q) @ q.T if q.shape[1] else values.copy() + + +def _normalized_basis(q, calibration): + projected = calibration @ q + mean, std = projected.mean(0), projected.std(0) + floor = max(float(np.sqrt(np.mean(std * std))) * 0.01, 1e-8) + std = np.maximum(std, floor) + unit = (projected - mean) / std + total_std = float(np.sqrt(np.mean(np.sum(unit * unit, axis=-1)))) + if not np.isfinite(total_std) or total_std <= 1e-8: + raise ValueError("A nonzero calibration variance is required") + basis = Basis( + q.astype(np.float32), mean.astype(np.float32), (std * total_std).astype(np.float32) + ) + if not np.allclose(basis.q.T @ basis.q, np.eye(q.shape[1]), atol=1e-5): + raise ValueError("The constructed basis is not orthonormal") + return basis + + +def fit_predicted_group_bases( + activations, + predicted_groups, + valid, + *, + rank=32, + seed=74, + variant="group_means", + predicted_answers=None, + answer_valid=None, +): + """Construct a target, orthogonal within-group complement, and random basis. + + Main method input: permitted actual-query states and model-predicted groups. + The optional answer-centered variant is a diagnostic until separately + preregistered. It uses model predictions from those same actual queries; + it does not request default/derived answer truth or extra derived states. + Rank failure returns unavailable; random directions never fill missing rank. + """ + x = np.asarray(activations, dtype=np.float64) + groups, used = np.asarray(predicted_groups), np.asarray(valid).copy() + if x.ndim != 2 or groups.shape != (len(x),) or used.shape != groups.shape or used.dtype != bool: + raise ValueError("Mismatched calibration arrays") + if not np.isfinite(x).all() or rank < 1 or rank > x.shape[1]: + raise ValueError("Finite activations and a feasible positive rank are required") + if (groups[used] < 0).any(): + raise ValueError("Invalid group predictions cannot be marked valid") + if variant not in ("group_means", "answer_centered_diagnostic"): + raise ValueError("Unknown basis variant") + answers = None + if variant == "answer_centered_diagnostic": + if predicted_answers is None or answer_valid is None: + raise ValueError("Answer centering requires model answers and validity flags") + answers, av = np.asarray(predicted_answers), np.asarray(answer_valid) + if answers.shape != groups.shape or av.shape != groups.shape or av.dtype != bool: + raise ValueError("Mismatched predicted answer arrays") + used &= av + report = { + "available": False, + "variant": variant, + "rank_requested": rank, + "calibration_rows": len(x), + "used_rows": int(used.sum()), + "invalid_rows": int((~used).sum()), + "uses_group_truth": False, + "uses_derived_calibration": False, + "random_seed": seed, + } + if not used.any(): + return None, {**report, "reason": "No valid model-predicted calibration groups"} + values, labels = x[used], groups[used] + unique, inverse = np.unique(labels, return_inverse=True) + group_means = np.stack([values[inverse == index].mean(0) for index in range(len(unique))]) + target_matrix = group_means - group_means.mean(0) + answer_span = np.empty((x.shape[1], 0)) + if answers is not None: + answer_labels = answers[used] + answer_means = np.stack( + [values[answer_labels == label].mean(0) for label in np.unique(answer_labels)] + ) + answer_span, _, _ = _row_span(answer_means - answer_means.mean(0)) + target_matrix = _orthogonal_residual(target_matrix, answer_span) + target_span, singular, target_rank = _row_span(target_matrix) + report.update( + predicted_groups=len(unique), + answer_span_rank=answer_span.shape[1], + target_numerical_rank=target_rank, + target_singular_values=singular.tolist(), + ) + if target_rank < rank: + return None, { + **report, + "reason": "Target has fewer than the required independent directions", + } + target = target_span[:, :rank] + residual = values - group_means[inverse] + residual = _orthogonal_residual(_orthogonal_residual(residual, answer_span), target) + complement_span, complement_singular, complement_rank = _row_span(residual) + report.update( + complement_numerical_rank=complement_rank, + complement_singular_values=complement_singular.tolist(), + ) + if complement_rank < rank: + return None, { + **report, + "reason": "Complement has fewer than the required independent directions", + } + if x.shape[1] - answer_span.shape[1] < rank: + return None, {**report, "reason": "Insufficient common admissible dimension"} + random_values = np.random.default_rng(seed).standard_normal((x.shape[1], rank)) + random_values = _orthogonal_residual(random_values.T, answer_span).T + random, triangular = np.linalg.qr(random_values, mode="reduced") + if (np.abs(np.diag(triangular)) < 1e-8).any(): + return None, {**report, "reason": "Random control is numerically rank deficient"} + bases = { + name: _normalized_basis(q, values) + for name, q in ( + ("target", target), + ("complement", complement_span[:, :rank]), + ("random", random), + ) + } + report["normalization"] = { + name: { + "rank": basis.rank, + "total_variance": float( + np.mean(np.sum(((values @ basis.q - basis.mean) / basis.scale) ** 2, axis=1)) + ), + "answer_span_overlap": float(np.linalg.norm(answer_span.T @ basis.q)), + } + for name, basis in bases.items() + } + return bases, {**report, "available": True, "reason": None} + + +def projection_component(values, q, mean): + # Explicit FP32 is necessary: .float() alone does not disable an outer + # autocast context for matrix products in a forward hook. + with torch.autocast(device_type=values.device.type, enabled=False): + return (values.float() @ q.float() - mean.float()) @ q.float().T + + +def match_delta_norm(delta, reference_norms, tolerance=1e-12): + """Zero-length controls with a positive target norm are explicitly unusable.""" + norms = torch.linalg.vector_norm(delta.float(), dim=-1) + reference_norms = torch.as_tensor(reference_norms, dtype=norms.dtype, device=norms.device) + if reference_norms.shape != norms.shape or bool((reference_norms < 0).any()): + raise ValueError("One nonnegative reference norm is required per case") + valid = (norms > tolerance) | (reference_norms <= tolerance) + scale = torch.where( + valid, reference_norms / norms.clamp_min(tolerance), torch.zeros_like(norms) + ) + return delta * scale[:, None], valid + + +def remove_projection(values, q, mean, reference_norms=None): + delta = -projection_component(values, q, mean) + valid = torch.ones(len(values), device=values.device, dtype=torch.bool) + if reference_norms is not None: + delta, valid = match_delta_norm(delta, reference_norms) + return values + delta.to(values.dtype), {"delta": delta, "valid": valid} + + +def restore_projection(values, clean_source, q, reference_norms=None): + """Restore only a fixed later-site projection, not an entire clean activation. + + clean_source must be from the same declared checkpoint and clean query, or + an explicitly labeled wrong-source control. A pre-edit source in an edited + model is a separate diagnostic and may undo the edit; it is never implicit. + """ + if values.shape != clean_source.shape: + raise ValueError("Restoration source and receiving states must have the same shape") + with torch.autocast(device_type=values.device.type, enabled=False): + delta = ((clean_source.float() - values.float()) @ q.float()) @ q.float().T + valid = torch.ones(len(values), device=values.device, dtype=torch.bool) + if reference_norms is not None: + delta, valid = match_delta_norm(delta, reference_norms) + return values + delta.to(values.dtype), {"delta": delta, "valid": valid} + + +def validate_restoration_sites(source, receiver, layers, answer_positions, allow_readout=False): + """A later relational post-block must still have a path to the value readout.""" + if not (0 <= source.layer < receiver.layer < layers): + raise ValueError("Restoration must be at a strictly later block, never the ablation point") + if source.position < 0 or receiver.position < 0: + raise ValueError("Token positions must be nonnegative") + if receiver.position < source.position: + raise ValueError("The receiving token is causally before the source token") + answer_positions = np.asarray(answer_positions) + if (answer_positions < receiver.position).any(): + raise ValueError("The receiving state cannot include an answer token") + if receiver.layer == layers - 1: + if (receiver.position < answer_positions).any(): + raise ValueError("Final-block earlier-token patches cannot affect value readout") + if not allow_readout: + raise ValueError("Final answer-marker restoration is a readout control, not routing") + return {"readout_control": receiver.layer == layers - 1} + + +def downstream_routing_site(source, layers, answer_positions): + """Prespecified L+1/same-token rescue; late candidates have no such rescue.""" + if source.layer > layers - 3: + raise ValueError("This late candidate has no nonterminal same-token routing rescue") + receiver = Site(source.layer + 1, source.position) + validate_restoration_sites(source, receiver, layers, answer_positions) + return receiver + + +def query_site_roles(lengths, position): + lengths = np.asarray(lengths) + if not np.isin(lengths, [4, 5]).all() or position not in (2, 3, 4): + raise ValueError("Only the declared basic/derived symbolic query forms are supported") + if (position >= lengths).any(): + raise ValueError("An intervention cannot use a future answer-token position") + return np.where( + position == lengths - 1, + "answer_marker", + "first_relation" if position == 2 else "second_relation", + ) + + +def attach_state_operation(model, site, operation): + """Attach a batch-local operation; caller supplies fixed source/control states. + + Operations return (new_state, diagnostics). Prompt and EOS passes may use + the same pre-answer operation; future answer tokens must never be sources. + """ + if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: + raise ValueError("Invalid intervention site") + traces = [] + + def intervene(_module, _inputs, output): + if site.position >= output.shape[1]: + raise ValueError("Intervention site is outside this query") + changed, trace = operation(output[:, site.position]) + if changed.shape != output[:, site.position].shape: + raise ValueError("An intervention changed the residual dimension") + result = output.clone() + result[:, site.position] = changed + traces.append(trace) + return result + + return model.blocks[site.layer].register_forward_hook(intervene), traces + + +def attach_equal_branch(model, basis, site, bottleneck=32, seed=73): + """The main experiment adds this branch to a common trainable MLP scope.""" + from .bios_branch import ResidualBranch + + if hasattr(model, "edit_branch"): + raise ValueError("An edit branch is already attached") + if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: + raise ValueError("Invalid branch site") + if site.position not in (2, 3): + raise ValueError("Method branches are restricted to locked relation candidates 2/3") + device = next(model.parameters()).device + branch = ResidualBranch(*basis.tensors(device), width=bottleneck, seed=seed) + model.add_module("edit_branch", branch) + + def add(_module, _inputs, output): + if site.position >= output.shape[1]: + raise ValueError("Branch site is outside this query") + changed = output.clone() + changed[:, site.position] += branch(output[:, site.position]) + return changed + + handle = model.blocks[site.layer].register_forward_hook(add) + expected = bottleneck * (basis.rank + model.config.width) + if sum(parameter.numel() for parameter in branch.parameters()) != expected: + raise ValueError("Unequal branch parameter count") + return branch, handle + + +def select_branch_parameters(model, branch, *, train_common_mlp=True, start=3): + from .bios_model import select_parameters + + if model.edit_branch is not branch: + raise ValueError("The branch is not attached to this model") + if train_common_mlp: + selected = select_parameters(model, "mlp", start) + else: + selected = [] + for parameter in model.parameters(): + parameter.requires_grad_(False) + parameter.grad = None + for parameter in branch.parameters(): + parameter.requires_grad_(True) + parameter.grad = None + selected.append(parameter) + return selected + + +def remove_equal_branch(model, handle): + handle.remove() + delattr(model, "edit_branch") diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_model.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7190d562883dec0d900e7ac14e894975f76499fb --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_model.py @@ -0,0 +1,120 @@ +"""Ordinary causal GPT-2-style language model used by protocol v2.3.""" + +import math +from dataclasses import asdict, dataclass + +import torch +from torch import nn +from torch.nn import functional as F + + +@dataclass(frozen=True) +class ModelConfig: + vocab_size: int + width: int = 768 + layers: int = 8 + heads: int = 12 + context: int = 128 + + +class Attention(nn.Module): + def __init__(self, config): + super().__init__() + self.heads = config.heads + self.qkv = nn.Linear(config.width, 3 * config.width) + self.proj = nn.Linear(config.width, config.width) + + def forward(self, x): + batch, length, width = x.shape + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +class MLP(nn.Module): + def __init__(self, width): + super().__init__() + self.up = nn.Linear(width, 4 * width) + self.activation = nn.GELU(approximate="tanh") + self.down = nn.Linear(4 * width, width) + + def forward(self, x): + return self.down(self.activation(self.up(x))) + + +class Block(nn.Module): + def __init__(self, config): + super().__init__() + self.ln1, self.ln2 = nn.LayerNorm(config.width), nn.LayerNorm(config.width) + self.attention = Attention(config) + self.mlp = MLP(config.width) + + def forward(self, x): + x = x + self.attention(self.ln1(x)) + return x + self.mlp(self.ln2(x)) + + +class CausalLM(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.token = nn.Embedding(config.vocab_size, config.width) + self.position = nn.Embedding(config.context, config.width) + self.blocks = nn.ModuleList([Block(config) for _ in range(config.layers)]) + self.ln_final = nn.LayerNorm(config.width) + self.apply(self._initialize) + for block in self.blocks: + for module in (block.attention.proj, block.mlp.down): + nn.init.normal_(module.weight, std=0.02 / math.sqrt(2 * config.layers)) + + @staticmethod + def _initialize(module): + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, std=0.02) + if isinstance(module, nn.Linear): + nn.init.zeros_(module.bias) + elif isinstance(module, nn.LayerNorm): + nn.init.ones_(module.weight) + nn.init.zeros_(module.bias) + + def forward(self, tokens, positions=None): + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + for block in self.blocks: + x = block(x) + 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 config_dict(self): + return asdict(self.config) + + +def select_parameters(model, scope, start=3): + if scope not in {"all", "mlp", "down"}: + raise ValueError("Scope must be all, mlp or down") + selected = list(model.parameters()) if scope == "all" else [] + if scope == "mlp": + selected = [p for block in model.blocks[start : start + 3] for p in block.mlp.parameters()] + elif scope == "down": + selected = [model.blocks[start + 1].mlp.down.weight] + ids = {id(p) for p in selected} + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) in ids) + parameter.grad = None + return selected + + +def matmul_flops(config, batch, sequence=6, output_positions=2, backward=True): + """Executed-shape dense/attention FLOPs estimate; excludes elementwise operations. + + Multiplication and addition each count as one. Backward uses a factor of two + forwards, a conventional upper approximation also used for frozen parameters. + This is not a hardware counter or a cross-editor exact FLOP measurement. + """ + d, layers, vocab = config.width, config.layers, config.vocab_size + forward = layers * (24 * batch * sequence * d * d + 4 * batch * sequence * sequence * d) + forward += 2 * batch * output_positions * d * vocab + return forward * (3 if backward else 1) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_organization.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_organization.py new file mode 100644 index 0000000000000000000000000000000000000000..a64a674326bdc2e7202a987e0ac941b40640d912 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_organization.py @@ -0,0 +1,256 @@ +"""Equal-presentation bioS corpora differing only in document organization. + +A joins a person's six facts to the true employer default. B keeps the person's +facts together but supplies an unrelated company's default. C keeps B's exact +actual/default pair and moves the other five personal facts to distinct company +origins. No fact is falsified; every condition uses the same presentation pool. +""" + +import numpy as np + +from .bios_data import EOS, N_BASE, N_COMPANIES, N_PEOPLE, RELATIONS, array_hash, rng_for + +CONDITIONS = ("A", "B", "C") +CONDITION_NAMES = {"A": "relation_linked", "B": "person_grouped", "C": "shuffled"} +PERSONAL_RELATIONS = (0, 2, 3, 4, 5, 6) +N_PRESENTATIONS = N_PEOPLE * len(RELATIONS) + + +def _fact_lookup(world): + """Look up fact IDs without depending on the current contiguous numbering.""" + lookup = np.full((7, N_PEOPLE), -1, dtype=np.int64) + for relation in range(7): + ids = np.flatnonzero(world.relation[:N_BASE] == relation) + subjects = world.company[ids] if relation == 1 else world.person[ids] + lookup[relation, subjects] = ids + return lookup + + +def make_documents(world, condition, organization_seed=0): + """Return (2048, 7) fact IDs in canonical relation order. + + Organization is fixed across epochs. Random group ordering and within-group + assignment use a separate seed, shared across all three conditions. C's + seven company origins are distinct, including its unlinked default. + """ + if condition not in CONDITIONS: + raise ValueError(f"Unknown organization condition: {condition}") + if organization_seed < 0: + raise ValueError("organization_seed must be nonnegative") + lookup = _fact_lookup(world) + documents = np.empty((N_PEOPLE, 7), dtype=np.int64) + people = np.arange(N_PEOPLE) + for relation in PERSONAL_RELATIONS: + documents[:, relation] = lookup[relation, people] + documents[:, 1] = lookup[1, world.employers] + if condition == "A": + return documents + + rng = rng_for(world.seed, 101, organization_seed) + members = np.stack( + [rng.permutation(np.flatnonzero(world.employers == c)) for c in range(N_COMPANIES)] + ) + if members.shape != (N_COMPANIES, 32): + raise ValueError("Organization protocol requires 64 companies with 32 people each") + # Independent company cycles per employee-rank lane avoid a stable unrelated + # company partner. Every cycle is a derangement and visits every company. + cycles = np.stack([rng.permutation(N_COMPANIES) for _ in range(32)]) + lane = np.arange(32)[:, None] + anchors = members[cycles, lane] + documents[anchors, 1] = lookup[1, np.roll(cycles, -1, axis=1)] + if condition == "C": + for shift, relation in enumerate((0, 3, 4, 5, 6), start=2): + donor_members = members.copy() + # Each donor person contributes exactly one fact of this relation. + for row in donor_members: + rng.shuffle(row) + donors = donor_members[np.roll(cycles, -shift, axis=1), lane] + documents[anchors, relation] = lookup[relation, donors] + return documents + + +def apply_epoch(documents, world_seed, epoch): + """Apply a shared row permutation and cyclic slot rotation (zero-based epoch). + + Every seven complete epochs, every presentation visits all seven positions. + The permutation depends on the world and epoch, never on the condition. + """ + documents = np.asarray(documents) + if documents.shape != (N_PEOPLE, 7) or epoch < 0: + raise ValueError("Expected canonical (2048, 7) documents and nonnegative epoch") + rows = rng_for(world_seed, 102, epoch).permutation(N_PEOPLE) + return np.roll(documents[rows], epoch % 7, axis=1) + + +def document_epoch(world, condition, epoch, organization_seed=0): + return apply_epoch(make_documents(world, condition, organization_seed), world.seed, epoch) + + +def render_documents(world, ids): + """Render facts with cross-fact causal attention, answer/EOS-only supervision. + + Each row is one document, independently batched; no inter-document attention + is required. Positions select logits that predict the next answer/EOS token. + """ + ids = np.asarray(ids, dtype=np.int64) + if ids.ndim != 2 or ids.shape[1] != 7 or np.any((ids < 0) | (ids >= N_BASE)): + raise ValueError("Expected seven base fact IDs per document") + tokens = np.empty((*ids.shape, 6), dtype=np.int64) + tokens[:, :, :4] = world.prompts[ids, :4] + tokens[:, :, 4] = world.answers[ids] + tokens[:, :, 5] = EOS + positions = (np.arange(7)[:, None] * 6 + np.array([3, 4])).ravel() + labels = np.stack([world.answers[ids], np.full_like(ids, EOS)], axis=-1) + return { + "tokens": tokens.reshape(len(ids), 42), + "positions": np.broadcast_to(positions, (len(ids), 14)).copy(), + "labels": labels.reshape(len(ids), 14), + "fact_ids": ids.copy(), + } + + +def presentation_ids(world, documents): + """Assign each shared presentation to exactly one canonical document slot. + + Personal presentation IDs are 7*person+relation. The 32 default copies use + 7*employee+1, assigned in sorted row order. This assignment is made before + epoch rotation, and permits a fixed text/template for every presentation. + """ + documents = np.asarray(documents, dtype=np.int64) + if documents.shape != (N_PEOPLE, 7): + raise ValueError("Expected canonical (2048, 7) documents") + if not np.all(world.relation[documents] == np.arange(7)): + raise ValueError("Presentation assignment requires canonical relation order") + ids = world.person[documents] * 7 + world.relation[documents] + for company in range(N_COMPANIES): + rows = np.flatnonzero(world.company[documents[:, 1]] == company) + people = np.flatnonzero(world.employers == company) + if len(rows) != len(people): + raise ValueError("Each company default must have 32 presentations") + ids[rows, 1] = people * 7 + 1 + if not np.array_equal(np.sort(ids.ravel()), np.arange(N_PRESENTATIONS)): + raise ValueError("Presentations were lost or duplicated") + return ids + + +def audit_organizations(world, documents): + """Fail on confounds and report the measured organization intervention.""" + if set(documents) != set(CONDITIONS): + raise ValueError("Audit requires A, B and C") + expected_counts = np.where(world.relation[:N_BASE] == 1, 32, 1) + expected_answers = np.bincount( + world.answers[:N_BASE], weights=expected_counts, minlength=world.vocab_size + ).astype(np.int64) + conditions = {} + for condition, ids in documents.items(): + if ids.shape != (N_PEOPLE, 7) or not np.all(world.relation[ids] == np.arange(7)): + raise ValueError("Invalid document shape or relation slots") + counts = np.bincount(ids.ravel(), minlength=N_BASE) + if not np.array_equal(counts, expected_counts): + raise ValueError("Per-fact presentation counts differ") + answers = np.bincount(world.answers[ids].ravel(), minlength=world.vocab_size) + if not np.array_equal(answers, expected_answers): + raise ValueError("Answer-token presentation counts differ") + companies, people = world.company[ids], world.person[ids] + same_company = companies[:, :, None] == companies[:, None, :] + same_person = (people[:, :, None] == people[:, None, :]) & (people[:, :, None] >= 0) + personal = people[:, PERSONAL_RELATIONS] + all_personal_same = np.all(personal == personal[:, :1], axis=1) + if condition in ("A", "B") and not all_personal_same.all(): + raise ValueError("Person aggregation was broken") + if condition == "A" and not np.all(companies == companies[:, :1]): + raise ValueError("A contains a broken employer/default link") + if condition in ("B", "C") and np.any(companies[:, 1] == companies[:, 2]): + raise ValueError("Unrelated default accidentally matches actual person's employer") + if condition == "C" and np.any( + np.sort(companies, axis=1)[:, 1:] == np.sort(companies, axis=1)[:, :-1] + ): + raise ValueError("C contains two facts with the same company origin") + pids = presentation_ids(world, ids) + slots = np.zeros((N_BASE, 7), dtype=np.int64) + for epoch in range(7): + arranged = apply_epoch(ids, world.seed, epoch) + for slot in range(7): + np.add.at(slots[:, slot], arranged[:, slot], 1) + if not np.array_equal(slots, np.repeat(expected_counts[:, None], 7, axis=1)): + raise ValueError("Per-fact positions are not balanced over seven epochs") + default_actual_same = world.answers[ids[:, 1]] == world.answers[ids[:, 2]] + conditions[condition] = { + "name": CONDITION_NAMES[condition], + "documents": len(ids), + "presentations": int(ids.size), + "unique_base_facts": int(np.count_nonzero(counts)), + "document_tokens": 42, + "supervised_tokens_per_document": 14, + "total_input_tokens_per_epoch": int(ids.size * 6), + "total_supervised_tokens_per_epoch": int(ids.size * 2), + "facts_sha256": array_hash(ids), + "presentation_ids_sha256": array_hash(pids), + "exposure_sha256": array_hash(counts), + "answer_histogram_sha256": array_hash(answers), + "seven_epoch_fact_slot_sha256": array_hash(slots), + "company_origin_cooccurrence": same_company.mean(axis=0).tolist(), + "person_origin_cooccurrence": same_person.mean(axis=0).tolist(), + "all_personal_same_fraction": float(all_personal_same.mean()), + "default_actual_same_answer_count": int(default_actual_same.sum()), + "default_actual_same_answer_rate": float(default_actual_same.mean()), + "relation_counts": { + relation: int((world.relation[ids] == i).sum()) + for i, relation in enumerate(RELATIONS) + }, + } + if not np.array_equal(documents["B"][:, 1:3], documents["C"][:, 1:3]): + raise ValueError("B and C must share exactly the same default/actual fact pairs") + return { + "schema": "bios-organization-v1", + "world_seed": world.seed, + "truth_sha256": array_hash(world.answers), + "relation_slot_order": list(RELATIONS), + "same_truth_and_per_fact_presentations": True, + "position_balance_period_epochs": 7, + "same_default_actual_pairs_B_C": True, + "templates_and_aliases": "symbolic tokens fixed; English view uses common presentations", + "conditions": conditions, + } + + +def english_fact(world, fact_id, variant=0): + """Readable supplemental view; this text is not used in symbolic training.""" + if not 0 <= fact_id < N_BASE: + raise ValueError("Expected a base fact") + relation = int(world.relation[fact_id]) + subject = ( + world.names["companies"][int(world.company[fact_id])] + if relation == 1 + else (world.names["people"][int(world.person[fact_id])]) + ) + kind, raw = world.token_labels[int(world.answers[fact_id])].split(":", 1) + fields = { + "company": "companies", + "city": "cities", + "university": "universities", + "major": "majors", + } + value = raw if kind == "date" else world.names[fields[kind]][int(raw)] + templates = ( + ("{s} works for {v}.", "{s}'s employer is {v}.", "{v} employs {s}."), + ( + "{s}'s default work city is {v}.", + "{s} uses {v} as the default work city.", + "The default work city for {s} is {v}.", + ), + ( + "{s}'s actual work city is {v}.", + "{s} actually works in {v}.", + "The actual work city of {s} is {v}.", + ), + ("{s} was born on {v}.", "{s}'s birth date is {v}.", "The birth date of {s} is {v}."), + ("{s} was born in {v}.", "{s}'s birth city is {v}.", "The birth city of {s} is {v}."), + ("{s} attended {v}.", "{s}'s university is {v}.", "{s} studied at {v}."), + ( + "{s} majored in {v}.", + "{s}'s academic major is {v}.", + "The academic major of {s} is {v}.", + ), + ) + return templates[relation][variant % 3].format(s=subject, v=value) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_organization_train.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_organization_train.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5d2bba261629aecc04944afd599bb827c634a8 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_organization_train.py @@ -0,0 +1,521 @@ +"""Matched A/B/C organization training; independent of the legacy SA/AS runs. + +An update contains 16 separate seven-fact causal documents and 28 isolated old +derived queries. Their supervised tokens are weighted 80:20. Each document is +a separate batch row, so attention never crosses document boundaries. +""" + +import argparse +import fcntl +import hashlib +import json +import math +import os +import platform +import random +import time +import traceback +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import ( + N_BASE, + N_PEOPLE, + N_QUERIES, + RELATIONS, + array_hash, + load_world, + rng_for, + write_json, +) +from .bios_model import CausalLM, ModelConfig, matmul_flops +from .bios_organization import apply_epoch, make_documents, render_documents +from .bios_train import code_fingerprint, evaluate, precision, tensor_data + +DOCUMENT_BATCH = 16 +DERIVED_BATCH = 28 +STEPS_PER_EPOCH = N_PEOPLE // DOCUMENT_BATCH +DEFAULT_STEPS = 14336 +WARMUP_EPOCHS = 16 +CHECKPOINTS = (0, 896, 1792, 3584, 7168, 10752, 14336, 21504, 28672) + + +def checkpoint_steps(steps): + if steps < 1: + raise ValueError("steps must be positive") + return sorted({step for step in CHECKPOINTS if step <= steps} | {steps}) + + +def derived_schedule(world_seed, steps, pool=None): + """Condition-independent stream; exhaust each permutation before repeating.""" + rng = rng_for(world_seed, 702) + size = steps * DERIVED_BATCH + pool = np.arange(N_BASE, N_QUERIES) if pool is None else np.asarray(pool) + if not len(pool) or len(np.unique(pool)) != len(pool): + raise ValueError("Derived pool must be nonempty and unique") + if np.any(pool < N_BASE) or np.any(pool >= N_QUERIES): + raise ValueError("Derived pool contains non-derived queries") + cycles = [rng.permutation(pool) for _ in range(math.ceil(size / len(pool)))] + return np.concatenate(cycles)[:size].reshape(steps, DERIVED_BATCH) + + +def learning_rate(step, base_lr): + # A constant rate within each complete epoch also matches per-fact LR exposure. + return base_lr * min((step // STEPS_PER_EPOCH + 1) / WARMUP_EPOCHS, 1.0) + + +def state_hash(state): + digest = hashlib.sha256() + for name, tensor in sorted(state.items()): + value = tensor.detach().cpu().contiguous() + digest.update(name.encode()) + digest.update(str(value.dtype).encode()) + digest.update(str(tuple(value.shape)).encode()) + digest.update(value.numpy().tobytes()) + return digest.hexdigest() + + +def schedule_hash(documents, world_seed, epochs): + digest = hashlib.sha256() + for epoch in range(epochs): + digest.update(np.ascontiguousarray(apply_epoch(documents, world_seed, epoch)).tobytes()) + return digest.hexdigest() + + +def update_flops(config): + return matmul_flops(config, DOCUMENT_BATCH, sequence=42, output_positions=14) + matmul_flops( + config, DERIVED_BATCH, sequence=6, output_positions=2 + ) + + +def two_context_backward(model, documents, isolated, derived_ids, device): + """Compute the exact per-token joint objective without retaining both graphs.""" + with precision(device): + logits = model(documents["tokens"], documents["positions"]) + doc_loss = F.cross_entropy(logits.float().flatten(0, 1), documents["labels"].flatten()) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(isolated["tokens"][derived_ids], isolated["positions"][derived_ids]) + derived_loss = F.cross_entropy( + logits.float().flatten(0, 1), isolated["labels"][derived_ids].flatten() + ) + (0.2 * derived_loss).backward() + return doc_loss.detach(), derived_loss.detach() + + +def atomic_torch_save(value, path): + temporary = path.with_suffix(path.suffix + ".tmp") + torch.save(value, temporary) + os.replace(temporary, path) + + +def atomic_numpy_save(path, **arrays): + temporary = path.with_suffix(path.suffix + ".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def core_sources(): + directory = Path(__file__).resolve().parent + names = ( + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization.py", + "bios_organization_train.py", + ) + return {name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in names} + + +def make_config(args, world, model, documents, derived): + steps = args.steps + epochs = math.ceil(steps / STEPS_PER_EPOCH) + return { + "protocol": "v2.4", + "dataset": "bios-organization-v1", + "phase": "development", + "run_kind": "full" + if steps == DEFAULT_STEPS and (args.width, args.layers, args.heads) == (768, 8, 12) + else "smoke", + "condition": args.condition, + "world_seed": world.seed, + "seed": args.seed, + "organization_seed": args.organization_seed, + "steps": steps, + "model": model.config_dict(), + "parameters": sum(p.numel() for p in model.parameters()), + "model_initial_sha256": state_hash(model.state_dict()), + "lr": args.lr, + "optimizer": "AdamW", + "weight_decay": 0.1, + "gradient_clip_norm": 1.0, + "warmup_epochs": WARMUP_EPOCHS, + "warmup_steps": WARMUP_EPOCHS * STEPS_PER_EPOCH, + "lr_rule": "constant within epoch: base_lr * min((epoch + 1) / 16, 1)", + "documents_per_step": DOCUMENT_BATCH, + "facts_per_document": 7, + "derived_queries_per_step": DERIVED_BATCH, + "document_weight": 0.8, + "derived_weight": 0.2, + "document_shape": {"sequence": 42, "supervised_positions": 14}, + "derived_shape": {"sequence": 6, "supervised_positions": 2}, + "context_objective": "answer+EOS only; same-document preceding facts visible causally", + "isolated_objective": "old-world derived QA only; no supporting document", + "cross_document_attention": False, + "evaluation": "all 14400 isolated queries; greedy value then generated EOS", + "steps_per_epoch": STEPS_PER_EPOCH, + "epochs": steps / STEPS_PER_EPOCH, + "checkpoints": checkpoint_steps(steps), + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "lengths_sha256": array_hash(world.lengths), + "documents_sha256": array_hash(documents), + "document_schedule_sha256": schedule_hash(documents, world.seed, epochs), + "derived_schedule_sha256": array_hash(derived), + "planned_atomic_presentations": steps * 112, + "planned_derived_presentations": steps * 28, + "planned_total_presentations": steps * 140, + "planned_document_presentations": steps * DOCUMENT_BATCH, + "planned_input_tokens_including_padding": steps * (16 * 42 + 28 * 6), + "planned_supervised_tokens": steps * (16 * 14 + 28 * 2), + "planned_train_matmul_flops_estimate": steps * update_flops(model.config), + "flops_method": "executed dense/attention shapes; backward=2x forward; excludes " + "elementwise operations, evaluation, padding-free reinterpretation", + "core_source_sha256": core_sources(), + } + + +def run_locked(args, out): + torch.set_num_threads(args.threads) + torch.manual_seed(args.seed) + random.seed(args.seed) + np.random.seed(args.seed) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + world = load_world(args.world) + documents = make_documents(world, args.condition, args.organization_seed) + from .bios_capacity import qa_split, split_metrics + + split_mode = getattr(args, "qa_split", "all") + train_ids, heldout_ids = qa_split(world, split_mode) + derived = derived_schedule(world.seed, args.steps, train_ids) + model = CausalLM(ModelConfig(world.vocab_size, args.width, args.layers, args.heads)).to(device) + config = make_config(args, world, model, documents, derived) + if getattr(args, "study", "legacy") == "capacity-v1": + config["core_source_sha256"]["bios_capacity.py"] = hashlib.sha256( + Path(__file__).with_name("bios_capacity.py").read_bytes() + ).hexdigest() + config.update( + { + "protocol": "v2.5-development", + "run_kind": "capacity-development", + "qa_split": split_mode, + "qa_train_ids": train_ids.tolist(), + "qa_heldout_ids": heldout_ids.tolist(), + "qa_split_policy": "half within company and old-exception stratum; world seed only", + "evaluation": "all base plus separately reported trained/heldout derived queries", + } + ) + config_path = out / "config.json" + if args.resume: + if not config_path.exists() or not (out / "resume.pt").exists(): + raise ValueError("Resume requires config.json and an atomic resume.pt checkpoint") + original = json.loads(config_path.read_text()) + differences = [key for key, value in config.items() if original.get(key) != value] + if differences: + raise ValueError("Resume configuration mismatch: " + ", ".join(differences)) + elif config_path.exists() or any(out.glob("model-*.pt")) or (out / "resume.pt").exists(): + raise ValueError("Output already contains a run; use a fresh directory or --resume") + else: + config.update( + { + "world": str(Path(args.world).resolve()), + "output": str(out.resolve()), + "execution": { + "device": args.device, + "threads": args.threads, + "torch": torch.__version__, + "python": platform.python_version(), + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast on CUDA; FP32 weights/loss/Adam moments", + "deterministic_algorithms": torch.are_deterministic_algorithms_enabled(), + "allow_tf32": torch.backends.cuda.matmul.allow_tf32, + }, + **code_fingerprint(), + } + ) + write_json(config_path, config) + atomic_numpy_save(out / "schedule.npz", documents=documents, derived=derived) + optimizer = torch.optim.AdamW( + model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + isolated = tensor_data(world, device) + counts = np.zeros(N_QUERIES, dtype=np.int64) + slot_counts = np.zeros((N_BASE, 7), dtype=np.int64) + weighted_exposure = np.zeros(N_QUERIES, dtype=np.float64) + timeline, losses = [], [] + train_seconds, first_step = 0.0, 0 + if args.resume: + state = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if state["config_sha256"] != hashlib.sha256(config_path.read_bytes()).hexdigest(): + raise ValueError("Resume checkpoint configuration fingerprint mismatch") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + torch.set_rng_state(state["torch_rng"]) + if device.type == "cuda" and state["cuda_rng"] is not None: + torch.cuda.set_rng_state(state["cuda_rng"], device) + random.setstate(state["python_rng"]) + np.random.set_state(state["numpy_rng"]) + counts, slot_counts = state["counts"], state["slot_counts"] + weighted_exposure = state["weighted_exposure"] + timeline, train_seconds, first_step = ( + state["timeline"], + state["train_seconds"], + state["step"], + ) + resumes_path = out / "resumes.json" + resumes = json.loads(resumes_path.read_text()) if resumes_path.exists() else [] + resumes.append({"from_step": first_step, "device": args.device, **code_fingerprint()}) + write_json(resumes_path, resumes) + if (out / "failure.json").exists(): + os.replace(out / "failure.json", out / f"failure-before-resume-{len(resumes)}.json") + if device.type == "cuda": + torch.cuda.reset_peak_memory_stats(device) + cached_epoch, cached_documents = None, None + active_step = first_step + try: + for step in range(first_step, args.steps + 1): + active_step = step + if step in checkpoint_steps(args.steps) and not (args.resume and step == first_step): + started = time.perf_counter() + metrics, arrays = evaluate(model, isolated, world, batch_size=args.eval_batch_size) + if getattr(args, "study", "legacy") == "capacity-v1": + metrics.update(split_metrics(world, arrays, train_ids, heldout_ids)) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slot_exposure=slot_counts, + lr_weighted_exposure=weighted_exposure, + ) + atomic_torch_save( + { + "model": { + key: value.detach().cpu() for key, value in model.state_dict().items() + }, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + record = { + "step": step, + "epoch": step / STEPS_PER_EPOCH, + **metrics, + "train_seconds": train_seconds, + "train_matmul_flops_estimate": step * update_flops(model.config), + "presentations": int(counts.sum()), + "document_presentations": step * DOCUMENT_BATCH, + "base_presentations": int(counts[:N_BASE].sum()), + "derived_presentations": int(counts[N_BASE:].sum()), + "coverage_base": float((counts[:N_BASE] > 0).mean()), + "coverage_derived": float((counts[N_BASE:] > 0).mean()), + "world_tokens": int((counts * (world.lengths + 2)).sum()), + "input_tokens_including_padding": step * (16 * 42 + 28 * 6), + "supervised_tokens": step * (16 * 14 + 28 * 2), + "exposure_sha256": array_hash(counts), + "slot_exposure_sha256": array_hash(slot_counts), + "lr_weighted_exposure_sha256": array_hash(weighted_exposure), + "lr_weighted_exposure_by_relation": { + relation: float(weighted_exposure[world.relation == i].sum()) + for i, relation in enumerate((*RELATIONS, "derived")) + }, + "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "eval_and_checkpoint_seconds": time.perf_counter() - started, + "mean_training_loss_since_previous": float(np.mean([x[0] for x in losses])) + if losses + else None, + "mean_context_document_loss": float(np.mean([x[1] for x in losses])) + if losses + else None, + "mean_isolated_derived_loss": float(np.mean([x[2] for x in losses])) + if losses + else None, + } + timeline.append(record) + write_json(out / "learning.json", timeline) + atomic_torch_save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) + if device.type == "cuda" + else None, + "python_rng": random.getstate(), + "numpy_rng": np.random.get_state(), + "timeline": timeline, + "counts": counts, + "slot_counts": slot_counts, + "weighted_exposure": weighted_exposure, + "train_seconds": train_seconds, + "step": step, + "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), + }, + out / "resume.pt", + ) + losses = [] + print( + json.dumps( + { + "event": "checkpoint", + "step": step, + "base": metrics["base_accuracy"], + "derived": metrics["derived_accuracy"], + "train_seconds": train_seconds, + } + ), + flush=True, + ) + if step == args.steps: + break + epoch = step // STEPS_PER_EPOCH + if cached_epoch != epoch: + ordered = apply_epoch(documents, world.seed, epoch) + rendered = render_documents(world, ordered) + # One small epoch tensor transfer; training slices never join documents. + cached_documents = { + key: torch.as_tensor(rendered[key], device=device) + for key in ("tokens", "positions", "labels") + } + cached_epoch = epoch + offset = (step % STEPS_PER_EPOCH) * DOCUMENT_BATCH + batch = { + key: value[offset : offset + DOCUMENT_BATCH] + for key, value in cached_documents.items() + } + fact_ids = ordered[offset : offset + DOCUMENT_BATCH] + derived_ids = torch.as_tensor(derived[step], device=device) + lr = learning_rate(step, args.lr) + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + doc_loss, derived_loss = two_context_backward( + model, batch, isolated, derived_ids, device + ) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(doc_loss + derived_loss) or not torch.isfinite(norm): + raise FloatingPointError("Nonfinite document/derived loss or gradient norm") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - started + dloss, qloss = float(doc_loss), float(derived_loss) + losses.append((0.8 * dloss + 0.2 * qloss, dloss, qloss)) + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, derived[step], 1) + np.add.at(slot_counts, (fact_ids, np.arange(7)[None, :]), 1) + np.add.at(weighted_exposure, fact_ids.ravel(), lr) + np.add.at(weighted_exposure, derived[step], lr) + if (step + 1) % 100 == 0: + print( + json.dumps( + { + "event": "progress", + "step": step + 1, + "epoch": (step + 1) / STEPS_PER_EPOCH, + "loss": float(np.mean([x[0] for x in losses[-100:]])), + "train_seconds": train_seconds, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "step": args.steps, + "status": "complete", + "final": timeline[-1], + "exposure_sha256": array_hash(counts), + "slot_exposure_sha256": array_hash(slot_counts), + "model_final_sha256": state_hash(model.state_dict()), + }, + ) + except BaseException as error: + write_json( + out / "failure.json", + { + "step": active_step, + "reason": str(error), + "type": type(error).__name__, + "traceback": traceback.format_exc(), + "train_seconds": train_seconds, + "last_committed_checkpoint": timeline[-1]["step"] if timeline else None, + }, + ) + raise + + +def train(args): + checkpoint_steps(args.steps) + if ( + getattr(args, "qa_split", "all") != "all" + and getattr(args, "study", "legacy") != "capacity-v1" + ): + raise ValueError("Heldout QA requires explicit capacity study") + if args.width < 1 or args.layers < 1 or args.heads < 1 or args.width % args.heads: + raise ValueError("Model dimensions must be positive and width divisible by heads") + if args.lr <= 0 or not math.isfinite(args.lr): + raise ValueError("Learning rate must be finite and positive") + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".train.lock").open("a") as lock: + try: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as error: + raise RuntimeError("Another process is training in this output directory") from error + run_locked(args, out) + + +def parser(): + result = argparse.ArgumentParser(description=__doc__) + result.add_argument("--world", required=True) + result.add_argument("--output", required=True) + result.add_argument("--condition", choices=("A", "B", "C"), required=True) + result.add_argument("--seed", type=int, default=0) + result.add_argument("--organization-seed", type=int, default=0) + result.add_argument("--steps", type=int, default=DEFAULT_STEPS) + result.add_argument("--lr", type=float, default=1e-4) + result.add_argument("--device", default="cuda") + result.add_argument("--threads", type=int, default=4) + result.add_argument("--eval-batch-size", type=int, default=512) + result.add_argument("--width", type=int, default=768) + result.add_argument("--layers", type=int, default=8) + result.add_argument("--heads", type=int, default=12) + result.add_argument("--study", choices=("legacy", "capacity-v1"), default="legacy") + result.add_argument("--qa-split", choices=("all", "half"), default="all") + result.add_argument("--resume", action="store_true") + return result + + +def main(): + train(parser().parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_data.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_data.py new file mode 100644 index 0000000000000000000000000000000000000000..98352c46d29112ab2ac2be7212204897c13aea18 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_data.py @@ -0,0 +1,455 @@ +"""Pinned six-attribute bioS reconstruction for plan 14.27 (not the old graph).""" + +from __future__ import annotations + +import ast +import calendar +import hashlib +import json +import random +from collections import Counter +from pathlib import Path + +import numpy as np + +SOURCE = Path("data/bios-source") +MATERIAL = SOURCE / "data-synthetic-pretrain/Capo-bioS-bioR" +SOURCE_CODE = MATERIAL / "Capo-bioS-bioR.py" +MONTHS = list(calendar.month_name)[1:] +ATTRS = ("date", "birthcity", "university", "field", "workcity", "company") +TASKS = (*ATTRS, "year", "parity", "company_city", "city_company", "comparison") + +# View 0 of the first six tasks is the question wording in Part 3.1, section 2.2. +# Additional tasks and views are an explicit measurement adaptation. +QUESTIONS = { + "date": [ + "What is the birth date of {n}?", + "On what date was {n} born?", + "Give {n}'s full date of birth.", + "When was {n} born?", + "State the birthday, including the year, of {n}.", + "What is {n}'s complete birth date?", + ], + "birthcity": [ + "What is the birth city of {n}?", + "In which city was {n} born?", + "Give {n}'s city of birth.", + "Where was {n} born?", + "Name the birthplace city of {n}.", + "What city is {n}'s birthplace?", + ], + "university": [ + "Which university did {n} study?", + "Where did {n} attend university?", + "Give the university attended by {n}.", + "At which university did {n} study?", + "Name {n}'s university.", + "What university educated {n}?", + ], + "field": [ + "What major did {n} study?", + "What was {n}'s field of study?", + "Give {n}'s university major.", + "In what subject did {n} major?", + "Name the discipline studied by {n}.", + "Which subject did {n} study at university?", + ], + "company": [ + "Which company did {n} work for?", + "Who was {n}'s employer?", + "Give the company employing {n}.", + "At what company did {n} work?", + "Name {n}'s employer.", + "What is the name of the company where {n} worked?", + ], + "workcity": [ + "Where did {n} work?", + "In which city did {n} work?", + "Give {n}'s work city.", + "What city was {n}'s employer based in?", + "Name the city of {n}'s workplace.", + "What was {n}'s city of employment?", + ], + "year": [ + "What is the birth year of {n}?", + "In which year was {n} born?", + "Give only {n}'s birth year.", + "Name the year in {n}'s date of birth.", + "What year marks {n}'s birth?", + "State the year of birth for {n}.", + ], + "parity": [ + "Was {n} born in an even-numbered month?", + "Is {n}'s birth month number even?", + "Does the month of {n}'s birth have an even number?", + "Is the calendar month when {n} was born even-numbered?", + "For {n}, is the birth month one of months 2, 4, 6, 8, 10, or 12?", + "Is the number of {n}'s birth month divisible by two?", + ], + "company_city": [ + "Give {n}'s company, then work city.", + "Name the employer of {n}, followed by its city.", + "For {n}, list company before workplace city.", + "What company employed {n}, and in what city?", + "State {n}'s company and city, in that order.", + "Report {n}'s employer first and work city second.", + ], + "city_company": [ + "Give {n}'s work city, then company.", + "Name the work city of {n}, followed by the employer.", + "For {n}, list workplace city before company.", + "In what city did {n} work, and for what company?", + "State {n}'s work city and company, in that order.", + "Report {n}'s work city first and employer second.", + ], + "comparison": [ + "Who was born earlier, {a} or {b}?", + "Which was born first: {a} or {b}?", + "Between {a} and {b}, name the older person.", + "Whose date of birth is earlier, {a}'s or {b}'s?", + "Compare the birthdays of {a} and {b}. Who is older?", + "Of {a} and {b}, who has the earlier birthday including the year?", + ], +} + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write_json(path, obj): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(obj, indent=2, ensure_ascii=False) + "\n") + temp.replace(path) + + +def load_json(path): + return json.loads(Path(path).read_text()) + + +def verify_source(): + manifest = load_json("configs/bios-source-manifest.json") + for row in manifest["files"]: + if digest(SOURCE / row["path"]) != row["sha256"]: + raise ValueError(f"Official source changed: {row['path']}") + return manifest + + +def source_templates(): + """Read literal templates without importing or changing the upstream source.""" + tree = ast.parse(SOURCE_CODE.read_text()) + fn = next( + n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "get_text_simple3" + ) + values = {} + for node in fn.body: + if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name): + name = node.targets[0].id + if name.startswith("sentence_structures"): + values[int(name[-1]) - 1] = ast.literal_eval(node.value) + return [values[i] for i in range(6)] + + +def date(p): + return f"{MONTHS[p['month'] - 1]} {p['day']}, {p['year']}" + + +def date_key(p): + return p["year"], p["month"], p["day"] + + +def render_sentences(p, templates, ids, order=range(6)): + fields = dict( + birthday=date(p), + birthcity=p["birthcity"], + university=p["university"], + field=p["field"], + company1city=p["workcity"], + company1name=p["company"], + ) + return [ + " " + templates[a][ids[a]].format(name=p["name"] if j == 0 else p["pronoun"], **fields) + for j, a in enumerate(order) + ] + + +def make_people(seed, count): + if count % 10: + raise ValueError("Population must permit exact 50/10/40 splits") + rng = random.Random(seed) + pools = { + key: (MATERIAL / "fields" / f"{key}.txt").read_text().splitlines() + for key in ( + "first_name", + "middle_name", + "last_name", + "city", + "university", + "field", + "company", + ) + } + names, people = set(), [] + for i in range(count): + while True: + name_ids = [ + rng.randrange(len(pools[k])) for k in ("first_name", "middle_name", "last_name") + ] + name = " ".join( + pools[k][v] + for k, v in zip(("first_name", "middle_name", "last_name"), name_ids, strict=True) + ) + if name not in names: + names.add(name) + break + indices = { + k: rng.randrange(len(pools[k])) for k in ("city", "university", "field", "company") + } + company, city = [s.strip() for s in pools["company"][indices["company"]].split(";", 1)] + people.append( + dict( + id=i, + name=name, + name_ids=name_ids, + attribute_ids=indices, + year=rng.randrange(1900, 2100), + month=rng.randrange(1, 13), + day=rng.randrange(1, 29), + birthcity=pools["city"][indices["city"]], + university=pools["university"][indices["university"]], + field=pools["field"][indices["field"]], + company=company, + workcity=city, + pronoun="He" if i % 2 == 0 else "She", + ) + ) + ids = list(range(count)) + random.Random(seed + 1000000).shuffle(ids) + for j, i in enumerate(ids): + people[i]["split"] = ( + "train" if j < count // 2 else ("dev" if j < 6 * count // 10 else "test") + ) + # One balanced comparison row per person. Both participants stay in the same split. + for split in ("train", "dev", "test"): + indices = [p["id"] for p in people if p["split"] == split] + random.Random(seed + len(indices)).shuffle(indices) + for j in range(0, len(indices), 2): + a, b = indices[j : j + 2] + if date_key(people[a]) == date_key(people[b]): + for k in range(j + 2, len(indices)): + c = indices[k] + if date_key(people[a]) != date_key(people[c]): + indices[j + 1], indices[k] = indices[k], indices[j + 1] + b = c + break + else: + raise ValueError("Equal-date terminal pair; choose a new prespecified seed") + people[a]["partner"] = b + people[b]["partner"] = a + return people + + +def answer(p, task, other=None): + if task == "date": + return date(p) + if task == "year": + return str(p["year"]) + if task == "parity": + return "yes" if p["month"] % 2 == 0 else "no" + if task == "company_city": + return f"{p['company']}; {p['workcity']}" + if task == "city_company": + return f"{p['workcity']}; {p['company']}" + if task == "comparison": + return min((p, other), key=date_key)["name"] + return p[task] + + +def question(p, task, view=0, other=None, cot=False): + q = QUESTIONS[task][view].format(n=p["name"], a=p["name"], b=other["name"] if other else "") + return "Question: " + q + (" Explain briefly." if cot else "") + "\nAnswer:" + + +def reasoning(p, task, other=None): + value = answer(p, task, other) + if task == "parity": + return ( + f"{date(p)}; {MONTHS[p['month'] - 1]} is month {p['month']}; " + f"{p['month']} is {'even' if p['month'] % 2 == 0 else 'odd'}; Answer: {value}" + ) + if task == "comparison": + return f"{p['name']}: {date(p)}; {other['name']}: {date(other)}; Answer: {value}" + if task == "year": + return f"{date(p)}; the year is {p['year']}; Answer: {value}" + if task in ("company_city", "city_company"): + return f"company: {p['company']}; work city: {p['workcity']}; Answer: {value}" + return f"{task}: {value}; Answer: {value}" + + +def edit_cases(people, seed): + rng = random.Random(seed + 3000000) + groups = [ + [p for p in people if p["split"] == "test" and p["month"] % 2 == parity] + for parity in (0, 1) + ] + selected = rng.sample(groups[0], 8) + rng.sample(groups[1], 8) + result = [] + for p in selected: + month = rng.choice([m for m in range(1, 13) if m % 2 != p["month"] % 2]) + year = rng.choice([y for y in range(1900, 2100) if y != p["year"]]) + result.append( + dict( + person_id=p["id"], + old_month=p["month"], + old_year=p["year"], + new_month=month, + new_year=year, + day=p["day"], + cells=[ + dict(month=m, year=y) + for m, y in ( + (p["month"], p["year"]), + (month, p["year"]), + (p["month"], year), + (month, year), + ) + ], + ) + ) + return result + + +def prepare_world(cfg, seed, tokenizer): + root = Path(cfg["data_root"]) / f"world-{seed}" + if (root / "audit.json").exists(): + audit = load_json(root / "audit.json") + for f, h in audit["files"].items(): + if digest(root / f) != h: + raise ValueError(f"Data changed: {root / f}") + return audit + root.mkdir(parents=True, exist_ok=True) + manifest = verify_source() + source_hash = digest(SOURCE_CODE) + templates = source_templates() + people = make_people(seed, cfg["people"]) + write_json(root / "people.json", people) + write_json(root / "edit-cases.json", edit_cases(people, seed)) + write_json(root / "questions.json", QUESTIONS) + rng = random.Random(seed + 2000000) + template_ids = np.empty((len(people), 5, 6), dtype=np.int16) + # Store separately tokenized full-name/pronoun sentences; no splitting at periods. + # This preserves abbreviations in company names and city names. + all_ids, lengths = [], [] + with (root / "biographies.jsonl").open("w") as out: + for p in people: + for variant in range(5): + ids = [rng.randrange(len(t)) for t in templates] + template_ids[p["id"], variant] = ids + sentences = render_sentences(p, templates, ids) + out.write( + json.dumps( + dict( + person_id=p["id"], + variant=variant, + template_ids=ids, + order=list(ATTRS), + source_sha256=source_hash, + text="".join(sentences), + ) + ) + + "\n" + ) + for a in range(6): + # Force this attribute first, and then second, to obtain both name forms. + full = render_sentences(p, templates, ids, [a])[0] + pro = render_sentences(p, templates, ids, [(a + 1) % 6, a])[1] + for text in (full, pro): + enc = tokenizer.encode(text).ids + all_ids.append(enc) + lengths.append(len(enc)) + max_len = max(lengths) + packed = np.zeros((len(all_ids), max_len), dtype=np.uint16) + for i, tokens in enumerate(all_ids): + packed[i, : len(tokens)] = tokens + np.save(root / "sentence-tokens.npy", packed.reshape(len(people), 5, 6, 2, max_len)) + np.save( + root / "sentence-lengths.npy", + np.array(lengths, dtype=np.int16).reshape(len(people), 5, 6, 2), + ) + np.save(root / "template-ids.npy", template_ids) + assert len({p["name"] for p in people}) == len(people) + for p in people: + assert people[p["partner"]]["split"] == p["split"] + assert date_key(p) != date_key(people[p["partner"]]) + counts = Counter(p["split"] for p in people) + for task in TASKS: + assert len(QUESTIONS[task]) == len(set(QUESTIONS[task])) == 6 + files = [ + "people.json", + "edit-cases.json", + "questions.json", + "biographies.jsonl", + "sentence-tokens.npy", + "sentence-lengths.npy", + "template-ids.npy", + ] + audit = dict( + seed=seed, + people=len(people), + splits=dict(counts), + source_revision=manifest["revision"], + source_sha256=digest(SOURCE_CODE), + template_counts=dict(zip(ATTRS, map(len, templates), strict=True)), + variants=5, + facts_per_person=6, + passes=540, + tasks_per_train_person=11, + train_rows=counts["train"] * 11, + qa_training_views=[0], + globally_held_out_views=list(range(1, 6)), + equal_date_comparisons=0, + cross_split_comparisons=0, + comparison_first_answer_fraction={ + s: np.mean( + [date_key(p) < date_key(people[p["partner"]]) for p in people if p["split"] == s] + ).item() + for s in counts + }, + city_collisions=sum(p["birthcity"] == p["workcity"] for p in people), + max_sentence_tokens=max_len, + files={f: digest(root / f) for f in files}, + ) + write_json(root / "audit.json", audit) + return audit + + +class BioStream: + """One deterministic pass presents every person exactly once, including the tail.""" + + def __init__(self, root, seed, condition): + self.tokens = np.load(Path(root) / "sentence-tokens.npy", mmap_mode="r") + self.lengths = np.load(Path(root) / "sentence-lengths.npy", mmap_mode="r") + self.seed, self.condition = seed, condition + self.count = self.tokens.shape[0] + + def pass_tokens(self, epoch): + rng = np.random.default_rng(np.random.SeedSequence([self.seed, epoch, 1427])) + people = rng.permutation(self.count) + stream = [50256] + order_hash = hashlib.sha256() + for pid in people: + variant = 0 if self.condition == "S" else (epoch + int(pid)) % 5 + order = rng.permutation(6) if self.condition == "MP" else np.arange(6) + order_hash.update(np.array([pid, variant, *order], dtype=np.int64).tobytes()) + for j, attr in enumerate(order): + form = int(j != 0) + size = self.lengths[pid, variant, attr, form] + stream.extend(self.tokens[pid, variant, attr, form, :size]) + stream.append(50256) + return np.asarray(stream, dtype=np.int64), order_hash.hexdigest() + + def exact_token_budget(self, passes): + # Permuting only changes which sentence uses the full name; sum its exact sizes. + return sum(len(self.pass_tokens(e)[0]) - 1 for e in range(passes)) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_diagnostics.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..dc0de9f1aeb4e6e8a48ea33b265811985ebea4d8 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_diagnostics.py @@ -0,0 +1,463 @@ +"""Frozen endpoint diagnostics for bioS; no training and no ground-truth auto inputs.""" + +from __future__ import annotations + +import calendar +import json +import os +import random +import re +import time +from collections import defaultdict +from pathlib import Path + +import torch +from tokenizers import Tokenizer + +from .bios_original_data import ATTRS, TASKS, answer, date, digest, load_json, question, write_json +from .bios_original_train import ( + amp, + encode_row, + generate, + load_model, + normalize, + sequence_scores, + setup, +) + +DEFAULT_ROOT = "docs/development-artifacts/bios-original-diagnostics-v1" +TASK_PAIR = ("parity", "comparison") + + +def select_people(people, world, count=24): + """Sample whole development partner pairs without model-dependent filtering.""" + if count % 2: + raise ValueError("The development count must consist of whole pairs") + pairs = [ + (p["id"], p["partner"]) for p in people if p["split"] == "dev" and p["id"] < p["partner"] + ] + pairs = random.Random(world + 930001).sample(pairs, count // 2) + return sorted(i for pair in pairs for i in pair) + + +def parse_date(text): + """Strict full-string date parser; malformed generations remain failures.""" + text = normalize(text) + names = {name.casefold(): i for i, name in enumerate(calendar.month_name) if i} + match = re.fullmatch(r"([a-z]+) ([1-9]|1\d|2[0-8]), (\d{4})", text) + if match is None or match[1] not in names: + return None + return (int(match[3]), names[match[1]], int(match[2])) + + +def operation_prompt(task, first, second=None): + """Exact rule-training prompt; only supplied strings enter this function.""" + if task == "parity": + parsed = parse_date(first) + month = calendar.month_name[parsed[1]] if parsed else first + return f"Question: Is {month} an even-numbered month?\nAnswer:" + if task == "comparison": + return f"Question: Which date is earlier, {first} or {second}?\nAnswer:" + raise ValueError(task) + + +def decode_operation(task, generated, first, second=None, names=None): + """Map a model-selected supplied date to its name without consulting truth.""" + if task == "parity": + return normalize(generated) + chosen = normalize(generated) + values = [normalize(first), normalize(second)] + if values[0] == values[1] or chosen not in values: + return None + return names[values.index(chosen)] + + +def symbolic_operation(task, first, second=None, names=None): + """A separately labelled host-computation ceiling, never a model result.""" + a = parse_date(first) + if a is None: + return None + if task == "parity": + return "yes" if a[1] % 2 == 0 else "no" + b = parse_date(second) + if b is None or a == b: + return None + return names[0 if a < b else 1] + + +def audit_batches(people, tasks, cot, batch_size): + """Select one original physical batch per split, independent of predictions.""" + eligible = [p for p in people if p["split"] in ("dev", "test")] + rows_per_person = len(tasks) * 6 * (2 if cot else 1) + starts = set() + for split in ("dev", "test"): + person_index = next(i for i, p in enumerate(eligible) if p["split"] == split) + starts.add((person_index * rows_per_person // batch_size) * batch_size) + return sorted(starts) + + +def read_selected_batches(path, starts, batch_size): + batches = {s: [] for s in starts} + with Path(path).open() as stream: + for i, line in enumerate(stream): + for s in starts: + if s <= i < s + batch_size: + batches[s].append(dict(load_json_line=json.loads(line), source_row=i)) + if i >= max(starts) + batch_size - 1: + break + if any(len(rows) != batch_size for rows in batches.values()): + raise ValueError("Incomplete historical physical batch") + return [dict(start=s, rows=rows) for s, rows in batches.items()] + + +def prepare(config_path, root=DEFAULT_ROOT, count=24): + root = Path(root) + if (root / "plan.json").exists(): + raise FileExistsError("Diagnostic inputs already frozen") + cfg = load_json(config_path) + source_files = [ + "src/llm_memory_editability/bios_original_diagnostics.py", + "scripts/run_bios_original_diagnostics.py", + "src/llm_memory_editability/bios_original_data.py", + "src/llm_memory_editability/bios_original_model.py", + "src/llm_memory_editability/bios_original_train.py", + ] + # Loading current implementations is valid only if original implementations match. + frozen = Path(cfg["result_root"]) / "execution-source" + for file in source_files[2:]: + if digest(file) != digest(frozen / file): + raise ValueError(f"Original source changed: {file}") + plan = dict( + version=1, + created_unix=time.time(), + config_path=str(config_path), + config_sha256=digest(config_path), + config=cfg, + count=count, + views=[0, 1], + diagnostic_batch_size=16, + audit_batch_size=cfg["evaluation"]["batch_size"], + max_new_tokens=cfg["evaluation"]["max_new_tokens"], + source_sha256={f: digest(f) for f in source_files}, + tokenizer_sha256=digest(Path(cfg["data_root"]) / "tokenizer/tokenizer.json"), + worlds={}, + endpoints=[], + ) + for world in cfg["world_seeds"]: + data_path = Path(cfg["data_root"]) / f"world-{world}/people.json" + people = load_json(data_path) + plan["worlds"][str(world)] = dict( + person_ids=select_people(people, world, count), + people_path=str(data_path), + sha256=digest(data_path), + ) + for init in cfg["initialization_seeds"]: + for condition in cfg["task"]["conditions"]: + stages = ["adapt", "task"] if condition in ("S", "M", "MP") else ["task"] + for stage in stages: + path = ( + Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" + ) + complete = load_json(path / "complete.json") + evaluation = load_json(path / "evaluation/evaluation-complete.json") + if complete["checkpoint_sha256"] != evaluation["checkpoint_sha256"]: + raise ValueError("Checkpoint/evaluation hash disagreement") + endpoint_id = f"world-{world}-{condition}-{stage}" + tasks = ATTRS if stage == "adapt" else TASKS + cot = stage == "task" and condition == "MP-CoT" + selected = read_selected_batches( + path / "evaluation/predictions.jsonl", + audit_batches(people, tasks, cot, plan["audit_batch_size"]), + plan["audit_batch_size"], + ) + sample = root / "audit-inputs" / f"{endpoint_id}.json" + write_json(sample, selected) + plan["endpoints"].append( + dict( + id=endpoint_id, + world=world, + init=init, + condition=condition, + stage=stage, + checkpoint=str(path / "final.pt"), + checkpoint_sha256=complete["checkpoint_sha256"], + audit_sample=str(sample), + audit_sample_sha256=digest(sample), + ) + ) + write_json(root / "plan.json", plan) + return plan + + +def verify_plan(plan): + for path, sha in plan["source_sha256"].items(): + if digest(path) != sha: + raise ValueError(f"Frozen diagnostic source changed: {path}") + for data in plan["worlds"].values(): + if digest(data["people_path"]) != data["sha256"]: + raise ValueError("People data changed") + + +def run_audit(model, tok, endpoint, plan, output, device): + sample = Path(endpoint["audit_sample"]) + if digest(sample) != endpoint["audit_sample_sha256"]: + raise ValueError("Audit inputs changed") + report = [] + for batch in load_json(sample): + rows = [r["load_json_line"] for r in batch["rows"]] + encoded = [encode_row(tok, r["prompt"], r["answer"]) for r in rows] + with torch.no_grad(), amp(device): + avg, full = sequence_scores(model, encoded, device) + generated, ended = generate( + model, tok, [r["prompt"] for r in rows], device, plan["max_new_tokens"] + ) + for original, text, eos, mean_lp, full_lp in zip( + batch["rows"], generated, ended, avg.tolist(), full.tolist(), strict=True + ): + old = original["load_json_line"] + extracted = text.rsplit("Answer:", 1)[-1].strip() if old["cot"] else text + report.append( + dict( + source_row=original["source_row"], + physical_batch_start=batch["start"], + original=old, + reloaded_generated=text, + reloaded_eos=eos, + generated_identical=text == old["generated"], + eos_identical=eos == old["eos"], + correctness_identical=(normalize(extracted) == normalize(old["answer"])) + == old["correct"], + mean_logp_difference=mean_lp - old["answer_mean_logp"], + full_logp_difference=full_lp - old["answer_full_logp"], + ) + ) + write_json(output / "audit-rows.json", report) + summary = dict( + rows=len(report), + generation_mismatches=sum(not r["generated_identical"] for r in report), + eos_mismatches=sum(not r["eos_identical"] for r in report), + correctness_mismatches=sum(not r["correctness_identical"] for r in report), + max_abs_full_logp_difference=max(abs(r["full_logp_difference"]) for r in report), + exact_original_batch=True, + precision="FP32 parameters, BF16 autocast, TF32 enabled", + ) + summary["status"] = ( + "passed" + if all( + summary[k] == 0 + for k in ("generation_mismatches", "eos_mismatches", "correctness_mismatches") + ) + and summary["max_abs_full_logp_difference"] <= 1e-4 + else "discrepancy" + ) + write_json(output / "audit-summary.json", summary) + return summary + + +def generate_rows(model, tok, rows, plan, device): + for start in range(0, len(rows), plan["diagnostic_batch_size"]): + batch = rows[start : start + plan["diagnostic_batch_size"]] + outputs, ended = generate( + model, tok, [r["prompt"] for r in batch], device, plan["max_new_tokens"] + ) + for row, text, eos in zip(batch, outputs, ended, strict=True): + row.update(generated=text, eos=eos) + print( + json.dumps( + dict(generation_done=min(start + len(batch), len(rows)), generation_total=len(rows)) + ), + flush=True, + ) + + +def run_diagnostics(model, tok, endpoint, plan, output, device): + world = plan["worlds"][str(endpoint["world"])] + people = load_json(world["people_path"]) + selected = [people[i] for i in world["person_ids"]] + extraction = [ + dict(person_id=p["id"], view=v, prompt=question(p, "date", v), target=date(p)) + for p in selected + for v in plan["views"] + ] + generate_rows(model, tok, extraction, plan, device) + lookup = {} + for row in extraction: + row.update( + parseable=parse_date(row["generated"]) is not None, + correct=normalize(row["generated"]) == normalize(row["target"]), + ) + lookup[row["person_id"], row["view"]] = row + write_json(output / "extractions.json", extraction) + rows = [] + for p in selected: + other = people[p["partner"]] + for task in TASK_PAIR: + for view in plan["views"]: + base = dict( + person_id=p["id"], + partner=other["id"], + view=view, + task=task, + target=answer(p, task, other), + ) + for cot in (False, True): + rows.append( + dict( + base, + mode="cot" if cot else "direct", + prompt=question(p, task, view, other, cot), + cot_trained=endpoint["condition"] == "MP-CoT", + ) + ) + for mode in ("oracle_rule", "autonomous_rule"): + a = date(p) if mode == "oracle_rule" else lookup[p["id"], view]["generated"] + b = ( + date(other) + if mode == "oracle_rule" + else lookup[other["id"], view]["generated"] + ) + parsed = parse_date(a) is not None and ( + task != "comparison" or parse_date(b) is not None + ) + valid = normalize(a) == normalize(date(p)) and ( + task != "comparison" or normalize(b) == normalize(date(other)) + ) + symbolic = symbolic_operation(task, a, b, (p["name"], other["name"])) + rows.append( + dict( + base, + mode=mode, + prompt=operation_prompt(task, a, b), + supplied_dates=[a, b] if task == "comparison" else [a], + inputs_parseable=parsed, + inputs_correct=valid, + symbolic_prediction=symbolic, + symbolic_correct=symbolic is not None + and normalize(symbolic) == normalize(base["target"]), + ) + ) + generate_rows(model, tok, rows, plan, device) + totals = defaultdict(lambda: defaultdict(int)) + for row in rows: + p, other = people[row["person_id"]], people[row["partner"]] + if row["mode"] in ("direct", "cot"): + pred = ( + row["generated"].rsplit("Answer:", 1)[-1].strip() + if row["mode"] == "cot" + else row["generated"] + ) + else: + dates = row["supplied_dates"] + pred = decode_operation( + row["task"], + row["generated"], + dates[0], + dates[1] if len(dates) == 2 else None, + (p["name"], other["name"]), + ) + row["prediction"] = pred + row["output_in_question_pair"] = ( + pred is not None and normalize(pred) in (normalize(p["name"]), normalize(other["name"])) + if row["task"] == "comparison" + else None + ) + if row["task"] == "comparison" and row["mode"] in ("oracle_rule", "autonomous_rule"): + row["output_is_supplied_date"] = normalize(row["generated"]) in { + normalize(value) for value in row["supplied_dates"] + } + row["correct"] = pred is not None and normalize(pred) == normalize(row["target"]) + row["correct_with_eos"] = row["correct"] and row["eos"] + key = f"{row['task']}/view-{row['view']}/{row['mode']}" + total = totals[key] + total["n"] += 1 + total["correct"] += row["correct"] + total["correct_with_eos"] += row["correct_with_eos"] + if row["task"] == "comparison": + total["output_in_question_pair"] += row["output_in_question_pair"] + if "output_is_supplied_date" in row: + total["output_is_supplied_date"] += row["output_is_supplied_date"] + if row["mode"] == "autonomous_rule": + for condition in ("inputs_parseable", "inputs_correct"): + total[condition + "_n"] += row[condition] + total[condition + "_correct"] += row[condition] and row["correct"] + total["symbolic_correct"] += row["symbolic_correct"] + with (output / "diagnostics.jsonl").open("w") as stream: + for row in rows: + stream.write(json.dumps(row) + "\n") + summary = dict( + rows=len(rows), + extraction_rows=len(extraction), + extraction_correct=sum(r["correct"] for r in extraction), + extraction_parseable=sum(r["parseable"] for r in extraction), + totals=dict(totals), + people=len(selected), + independent_partner_pairs=len(selected) // 2, + split="development", + no_training=True, + limitations=[ + "Oracle and autonomous rules use externally supplied text and a changed prompt.", + "Non-MP-CoT models did not train on the CoT instruction.", + "Host date-to-name mapping and symbolic ceilings are not model reasoning.", + "Twenty-four people are a fixed diagnostic subset, not population estimates.", + ], + ) + write_json(output / "diagnostic-summary.json", summary) + return summary + + +def run_endpoint(root, endpoint_id, device="cuda:0", memory_fraction=0.045): + root = Path(root) + plan = load_json(root / "plan.json") + verify_plan(plan) + endpoint = next(e for e in plan["endpoints"] if e["id"] == endpoint_id) + output = root / "endpoints" / endpoint_id + if (output / "complete.json").exists(): + return load_json(output / "complete.json") + output.mkdir(parents=True, exist_ok=True) + if digest(endpoint["checkpoint"]) != endpoint["checkpoint_sha256"]: + raise ValueError("Checkpoint changed") + cfg = plan["config"] + setup(endpoint["init"], device) + if str(device).startswith("cuda"): + torch.cuda.set_per_process_memory_fraction(memory_fraction, device) + torch.cuda.reset_peak_memory_stats(device) + tok_path = Path(cfg["data_root"]) / "tokenizer/tokenizer.json" + if digest(tok_path) != plan["tokenizer_sha256"]: + raise ValueError("Tokenizer changed") + tok = Tokenizer.from_file(str(tok_path)) + start = time.monotonic() + model = load_model(endpoint["checkpoint"], cfg, device, adapters=True).eval() + model.requires_grad_(False) + write_json( + output / "running.json", + dict( + endpoint=endpoint_id, + started_unix=time.time(), + pid=os.getpid(), + device=device, + cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), + memory_fraction=memory_fraction, + shared_gpu=True, + torch_version=torch.__version__, + ), + ) + audit = run_audit(model, tok, endpoint, plan, output, device) + diagnostics = ( + run_diagnostics(model, tok, endpoint, plan, output, device) + if endpoint["stage"] == "task" + else None + ) + result = dict( + endpoint=endpoint, + seconds=time.monotonic() - start, + audit=audit, + diagnostics=diagnostics, + shared_gpu=True, + memory_fraction=memory_fraction, + cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), + peak_allocated_bytes=torch.cuda.max_memory_allocated(device) + if str(device).startswith("cuda") + else None, + ) + write_json(output / "complete.json", result) + return result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_model.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_model.py new file mode 100644 index 0000000000000000000000000000000000000000..039ceaef72cf7fefa38bb094dbefbe9f7e88d651 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_model.py @@ -0,0 +1,130 @@ +"""GPT-2 blocks, quarter-head NeoX RoPE, tied vocabulary, explicit Q/V/embedding LoRA.""" + +from __future__ import annotations + +import math + +import torch +from torch import nn +from torch.nn import functional as F + + +class Attention(nn.Module): + def __init__(self, cfg): + super().__init__() + width = cfg["width"] + self.heads = cfg["heads"] + self.dim = width // self.heads + self.rotary_dim = int(self.dim * cfg["rotary_fraction"]) + assert self.rotary_dim % 2 == 0 and self.rotary_dim > 0 + self.qkv = nn.Linear(width, 3 * width) + self.out = nn.Linear(width, width) + freq = 1.0 / ( + cfg["rotary_base"] ** (torch.arange(0, self.rotary_dim, 2).float() / self.rotary_dim) + ) + angle = torch.outer(torch.arange(cfg["context"]).float(), freq) + angle = torch.cat((angle, angle), dim=-1)[None, None] + self.register_buffer("cos", angle.cos(), persistent=False) + self.register_buffer("sin", angle.sin(), persistent=False) + self.dropout = cfg["dropout"] + self.rank = 0 + + def add_lora(self, rank): + self.rank = rank + width = self.heads * self.dim + self.q_a = nn.Parameter(torch.randn(rank, width) * 0.02) + self.q_b = nn.Parameter(torch.zeros(width, rank)) + self.v_a = nn.Parameter(torch.randn(rank, width) * 0.02) + self.v_b = nn.Parameter(torch.zeros(width, rank)) + + def rotate(self, x): + z, tail = x[..., : self.rotary_dim], x[..., self.rotary_dim :] + half = self.rotary_dim // 2 + swapped = torch.cat((-z[..., half:], z[..., :half]), dim=-1) + size = x.shape[-2] + z = z * self.cos[:, :, :size].to(x.dtype) + swapped * self.sin[:, :, :size].to(x.dtype) + return torch.cat((z, tail), dim=-1) + + def forward(self, x): + b, t, width = x.shape + q, k, v = self.qkv(x).chunk(3, dim=-1) + if self.rank: + q = q + F.linear(F.linear(x, self.q_a), self.q_b) + v = v + F.linear(F.linear(x, self.v_a), self.v_b) + q, k, v = [z.view(b, t, self.heads, self.dim).transpose(1, 2) for z in (q, k, v)] + y = F.scaled_dot_product_attention( + self.rotate(q), + self.rotate(k), + v, + is_causal=True, + dropout_p=self.dropout if self.training else 0, + ) + return self.out(y.transpose(1, 2).contiguous().view(b, t, width)) + + +class Block(nn.Module): + def __init__(self, cfg): + super().__init__() + width = cfg["width"] + self.ln1, self.ln2 = nn.LayerNorm(width), nn.LayerNorm(width) + self.attn = Attention(cfg) + self.up, self.down = nn.Linear(width, 4 * width), nn.Linear(4 * width, width) + self.dropout = nn.Dropout(cfg["dropout"]) + + def forward(self, x): + x = x + self.dropout(self.attn(self.ln1(x))) + return x + self.dropout(self.down(F.gelu(self.up(self.ln2(x)), approximate="tanh"))) + + +class GPT(nn.Module): + def __init__(self, cfg): + super().__init__() + self.cfg = cfg + self.embedding = nn.Embedding(cfg["vocab_size"], cfg["width"]) + self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg["layers"])]) + self.norm = nn.LayerNorm(cfg["width"]) + self.dropout = nn.Dropout(cfg["dropout"]) + self.embedding_rank = 0 + self.apply(self._init) + for block in self.blocks: + nn.init.normal_(block.attn.out.weight, std=0.02 / math.sqrt(2 * cfg["layers"])) + nn.init.normal_(block.down.weight, std=0.02 / math.sqrt(2 * cfg["layers"])) + + @staticmethod + def _init(module): + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, std=0.02) + if isinstance(module, nn.Linear): + nn.init.zeros_(module.bias) + + def add_lora(self, qv_rank, embedding_rank): + self.requires_grad_(False) + for b in self.blocks: + b.attn.add_lora(qv_rank) + self.embedding_rank = embedding_rank + self.emb_a = nn.Parameter(torch.randn(self.cfg["vocab_size"], embedding_rank) * 0.02) + self.emb_b = nn.Parameter(torch.zeros(embedding_rank, self.cfg["width"])) + + def hidden(self, ids): + x = self.embedding(ids) + if self.embedding_rank: + x = x + F.embedding(ids, self.emb_a) @ self.emb_b + x = self.dropout(x) + for block in self.blocks: + x = block(x) + return self.norm(x) + + def logits(self, hidden): + # Preserve input/output tying also for the embedding update. + logits = F.linear(hidden, self.embedding.weight) + if self.embedding_rank: + logits = logits + F.linear(F.linear(hidden, self.emb_b), self.emb_a) + return logits + + def forward(self, ids, targets=None): + h = self.hidden(ids) + if targets is None: + return self.logits(h) + # Avoid materializing logits at padded/unsupervised positions. + valid = targets != -100 + return F.cross_entropy(self.logits(h[valid]).float(), targets[valid], reduction="mean") diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_report.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_report.py new file mode 100644 index 0000000000000000000000000000000000000000..8aace2494390c65045a2d379beb42695d3b84c8e --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_report.py @@ -0,0 +1,685 @@ +"""Read-only, CPU aggregation of the completed original bioS development run.""" + +from __future__ import annotations + +import csv +import hashlib +import json +import math +import re +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +from llm_memory_editability.bios_original_data import ( + ATTRS, + MONTHS, + TASKS, + answer, + question, +) + +DATE_PATTERN = re.compile( + "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}" +) +DIMENSIONS = ("world", "initialization", "condition", "stage", "split", "task", "view", "cot") +COUNTS = ( + "n", + "correct", + "eos", + "format_recognized", + "correct_eos", + "correct_unrecognized", + "wrong_recognized", + "wrong_unrecognized", + "terminal_answer_match", + "target_text_present", + "city_swap", + "comparison_outside_pair", + "sum_full_logp", + "sum_mean_logp", + "sum_answer_probability", +) + + +def normalize(text): + """Independently reproduce the historical frozen evaluator's normalization.""" + return " ".join(text.strip().rstrip(".").casefold().split()) + + +def extract(row): + text = row["generated"] + return text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text + + +def recognized(text, task, vocabulary): + value = normalize(text) + if task == "parity": + return value in ("yes", "no") + if task == "year": + return bool(re.fullmatch(r"\d{4}", value)) + if task == "date": + return bool(DATE_PATTERN.fullmatch(value)) + if task in ("company_city", "city_company"): + fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") + parts = value.split(";") + return len(parts) == 2 and all( + part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) + ) + return value in vocabulary["name" if task == "comparison" else task] + + +def review_flags(row, person, vocabulary, partner=None): + """Mechanical error labels only; these do not replace the frozen score.""" + text, target = extract(row), normalize(row["answer"]) + correct = normalize(text) == target + form = recognized(text, row["task"], vocabulary) + suffix = row["generated"].rsplit("Answer:", 1)[-1] + terminal = not correct and "Answer:" in row["generated"] and normalize(suffix) == target + # A literal occurrence is an inspection cue, not a semantic-correctness claim. + present = not correct and bool( + re.search(r"(? 1e-5: + raise ValueError(f"Invalid log probability: {path}:{line_number}") + cell[target] += value + cell["sum_answer_probability"] += math.exp(row["answer_full_logp"]) + for category in ( + "terminal_answer_match", + "target_text_present", + "city_swap", + "comparison_outside_pair", + "wrong_recognized", + "wrong_unrecognized", + "correct_unrecognized", + ): + sample_key = (row["task"], row["view"] == 0, row["cot"], category) + if flags[category] and sample_counts[sample_key] < 2: + sample_counts[sample_key] += 1 + examples.append( + dict( + **meta, + category=category, + source=str(path), + line=line_number, + **row, + review_status="deterministic inspection sample; not human-labelled", + ) + ) + expected_cells = len(cfg["evaluation"]["splits"]) * len(tasks) * 6 * len(modes) + if len(cells) != expected_cells or len(completion["totals"]) != expected_cells: + raise ValueError(f"Incomplete evaluation cell matrix: {path}") + counts = Counter(p["split"] for p in people) + for (split, task, view, cot), cell in cells.items(): + if cell["n"] != counts[split]: + raise ValueError(f"Incomplete population: {path}: {split}/{task}/{view}/{cot}") + old = completion["totals"][f"{split}/{task}/view-{view}/cot-{cot}"] + if any(cell[k] != old[k] for k in ("n", "correct", "format_recognized")): + raise ValueError(f"Historical totals mismatch: {path}") + if not math.isclose(cell["sum_full_logp"], old["sum_full_logp"], abs_tol=1e-8): + raise ValueError(f"Historical logp total mismatch: {path}") + checks["cells_population_and_historical_totals_verified"] += 1 + provenance = dict( + **meta, + path=str(path), + sha256=digest.hexdigest(), + bytes=path.stat().st_size, + checkpoint_sha256=completion["checkpoint_sha256"], + checks=dict(checks), + completion_sha256=hashlib.sha256(completion_path.read_bytes()).hexdigest(), + ) + conditional = conditional_rows(seen, people, meta, modes) if meta["stage"] == "task" else [] + return [finalized(v) for v in cells.values()], examples, provenance, conditional + + +def pretrain_rows(cfg): + curves, inventory = [], [] + for world in cfg["world_seeds"]: + for init in cfg["initialization_seeds"]: + for condition in cfg["pretrain"]["conditions"]: + root = Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/pretrain" + path = root / "metrics.jsonl" + metrics = [json.loads(line) for line in path.read_text().splitlines()] + expected = list(range(1, cfg["pretrain"]["passes"] + 1)) + if [r["passes"] for r in metrics] != expected: + raise ValueError(f"Incomplete pretraining curve: {path}") + for row in metrics: + curves.append( + dict(world=world, initialization=init, condition=condition, **row) + ) + inventory.append( + dict( + world=world, + initialization=init, + condition=condition, + path=str(path), + sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + passes=len(metrics), + final_nll=metrics[-1]["nll"], + nodes=[ + dict(passes=n, checkpoint_exists=(root / f"pass-{n:03d}.pt").exists()) + for n in cfg["pretrain"]["nodes"] + ], + ) + ) + return curves, inventory + + +def paired_differences(groups): + pairs = [("S", "M"), ("M", "MP"), ("MP", "MP-R"), ("MP-R", "MP-Random"), ("MP", "MP-CoT")] + lookup = {} + for row in groups: + key = tuple( + row[k] + for k in ("world", "initialization", "stage", "split", "task", "view_group", "cot") + ) + lookup.setdefault(key, {})[row["condition"]] = row + rows = [] + for key, conditions in lookup.items(): + for left, right in pairs: + if left not in conditions or right not in conditions: + continue + a, b = conditions[left], conditions[right] + if a["n"] != b["n"]: + raise ValueError("Unequal paired populations") + rows.append( + dict( + **dict( + zip( + ( + "world", + "initialization", + "stage", + "split", + "task", + "view_group", + "cot", + ), + key, + strict=True, + ) + ), + left=left, + right=right, + n_each=a["n"], + left_accuracy=a["correct_rate"], + right_accuracy=b["correct_rate"], + difference_pp=100 * (b["correct_rate"] - a["correct_rate"]), + ) + ) + return rows + + +def make_plots(output, curves, groups): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, axes = plt.subplots(1, 2, figsize=(11, 4)) + for world in sorted({r["world"] for r in curves}): + for c, color in zip(("S", "M", "MP"), ("#9b5f1b", "#4477aa", "#228833"), strict=True): + subset = [r for r in curves if r["world"] == world and r["condition"] == c] + axes[0].plot( + [r["passes"] for r in subset], + [r["nll"] for r in subset], + color=color, + alpha=0.8, + label=f"{c}, world {world}", + ) + axes[0].set(xlabel="Biography exposures per person", ylabel="Training NLL", yscale="log") + axes[0].legend(fontsize=7) + for offset, view, color in [(-0.17, "canonical", "#4477aa"), (0.17, "heldout", "#cc6677")]: + means = [] + for c in ("S", "M", "MP"): + data = [ + r["correct_rate"] + for r in groups + if r["stage"] == "adapt" + and r["split"] == "test" + and r["condition"] == c + and r["view_group"] == view + and r["family"] == "six_attributes" + ] + means.append(100 * sum(data) / len(data)) + axes[1].bar([i + offset for i in range(3)], means, width=0.32, label=view, color=color) + axes[1].set( + xticks=range(3), + xticklabels=("S", "M", "MP"), + ylabel="QA extraction accuracy (%)", + ylim=(0, 105), + ) + axes[1].legend() + fig.suptitle("Original bioS development: training fit and later QA extraction") + fig.tight_layout() + for suffix in ("png", "pdf"): + fig.savefig(output / f"bios-pretrain-and-extraction.{suffix}", dpi=160) + plt.close(fig) + + +def report_text(overall, groups, endpoints): + def mean(rows, field="correct_rate"): + # Exactly one initialization per world in this development configuration. + per_world = {} + for row in rows: + per_world.setdefault(row["world"], []).append(row[field]) + values = [sum(v) / len(v) for v in per_world.values()] + return 100 * sum(values) / len(values) if values else float("nan") + + def select(rows, **conditions): + return [r for r in rows if all(r[k] == v for k, v in conditions.items())] + + lines = [ + "# 原版 bioS 开发预测复盘", + "", + "本报告独立复算两开发世界的 570 万条既有预测、18 个评价端点与全部 3240 个预训练" + "日志节点。没有新增训练、GPU 前向或更改历史预测。原始评分与完成文件逐单元一致。", + "", + "表中百分比先在每个世界内汇总,再对两个世界等权;这是开发结果,无新增独立确认。" + "同一人物的五个留出问法,以及同一比较人物对的两个问序,属于重复测量。", + "", + "## 六属性 QA 提取", + "", + "| BIO 条件 | 规范问法 | 五个留出问法均值 |", + "| --- | ---: | ---: |", + ] + for condition in ("S", "M", "MP"): + values = [ + mean( + select( + overall, + stage="adapt", + split="test", + condition=condition, + family="six_attributes", + view_group=v, + cot=False, + ) + ) + for v in ("canonical", "heldout") + ] + lines.append(f"| {condition} | {values[0]:.2f}% | {values[1]:.2f}% |") + lines += [ + "", + "S/M/MP 使用相同人物与语义事实曝光;M 增加表述,MP 再重排句序。" + "QA 适配使用训练人物,测试人物只参加 BIO 预训练。这里测的是经共同 QA 适配后的提取," + "不能称为预训练终点未经适配的问答表现。工作城市已出现于传记,属于提取任务。", + "", + "## 任务适配后的规范问法", + "", + "| 模型 / 推理方式 | 日期 | 年份 | 月份奇偶 | 出生早晚比较 |", + "| --- | ---: | ---: | ---: | ---: |", + ] + for condition, cot in [ + ("MP", False), + ("MP-R", False), + ("MP-Random", False), + ("MP-CoT", False), + ("MP-CoT", True), + ]: + values = [ + mean( + select( + groups, + stage="task", + split="test", + condition=condition, + view_group="canonical", + cot=cot, + task=task, + ) + ) + for task in ("date", "year", "parity", "comparison") + ] + mode = "CoT" if cot else "直接" + lines.append(f"| {condition} / {mode} | " + " | ".join(f"{v:.2f}%" for v in values) + " |") + lines += [ + "", + "年份和奇偶需要从已知属性执行操作,不能与六属性提取的平均值混为一项。" + "MP-CoT 的两种推理方式使用同一适配端点,但解释提示、监督格式及输出计算不同。" + "MP-R 的收益须与匹配的 MP-Random 同时检查。", + "", + "## 错误与计分审阅", + "", + ] + for condition, cot in (("MP", False), ("MP-CoT", True)): + value = mean( + select( + groups, + stage="task", + split="test", + condition=condition, + view_group="canonical", + cot=cot, + task="comparison", + ), + "comparison_outside_pair_rate", + ) + lines.append( + f"- {condition} / {'CoT' if cot else '直接'} 的比较输出中," + f"{value:.2f}% 未精确返回问题中任一人的名字;这不能只解释为日期运算错误。" + ) + suffix = mean( + select( + groups, + stage="task", + split="test", + condition="MP-CoT", + view_group="heldout", + cot=False, + task="date", + ), + "terminal_answer_match_rate", + ) + lines += [ + f"- MP-CoT 直接作答的留出日期问法中,{suffix:.2f}% 的全量输出虽未通过冻结评分," + "最后一个 `Answer:` 后恰为目标日期。这是可复核的格式失分,保留为事后辅助统计;" + "没有改写主分数。", + "- `wrong_recognized` 只表示输出满足原格式规则但不等于标签;" + "`target_text_present` 只表示原输出出现目标文字,不认定语义正确。" + "城市互换与问题外人名由已知人物表确定。", + "- `error-review-samples.jsonl` 按任务、问法组、模式、错误标签保存最先两条," + "是确定性审阅样本,不是错误率的随机估计,也不是全量人工语义标注。", + "- CoT 的历史 `answer_full_logp` 是解释提示后直接接短答案的概率," + "不是所生成推理链或最终答案的概率,不用于判断 CoT 是否掌握知识。", + "- `conditional-task-scores.csv` 在同一人物、相同问法和输出模式下检查源属性是否答对;" + "比较题要求两个人的日期都答对。它是条件子集分析,覆盖率与全量分数同时保留," + "不等同于把模型自产属性重新输入后的两次调用实验。", + "", + "## 预训练曲线与剩余工作", + "", + "`pretrain-curves.csv` 与图保留六条各 540 次曝光的训练 NLL。不同数据条件的文本" + "可预测性不同,NLL 不能当作统一知识量刻度。已保存权重节点存在不等于已测出各节点的" + "知识/推理能力;当前没有这样的语义学习曲线。", + "", + "本 CPU 报告没有完成独立权重重载、oracle 属性输入或自主提取后运算;" + "100k 正式矩阵与日期编辑也未执行。它们的后续结果应写入独立产物。", + "", + "复现:`PYTHONPATH=src .venv/bin/python scripts/report_bios_original.py`。" + "原预测、配置、数据及报告源码哈希见 `audit.json`。", + "", + f"已核验端点:{len(endpoints)};完整单元表 `cells.csv`,按任务与问法组汇总" + " `task-view-groups.csv`,世界内配对差 `paired-world-differences.csv`。", + ] + return "\n".join(lines) + "\n" + + +def run_report(config_path, output): + cfg = json.loads(config_path.read_text()) + output.mkdir(parents=True, exist_ok=True) + cells, examples, endpoints, conditional = [], [], [], [] + for world in cfg["world_seeds"]: + people_path = Path(cfg["data_root"]) / f"world-{world}/people.json" + people = json.loads(people_path.read_text()) + if [p["id"] for p in people] != list(range(cfg["people"])): + raise ValueError("People index contract changed") + for init in cfg["initialization_seeds"]: + for stage, conditions in ( + ("adapt", cfg["pretrain"]["conditions"]), + ("task", cfg["task"]["conditions"]), + ): + for condition in conditions: + meta = dict(world=world, initialization=init, condition=condition, stage=stage) + root = ( + Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" + ) + a, b, c, d = read_endpoint(root, meta, cfg, people) + cells.extend(a) + examples.extend(b) + endpoints.append(c) + conditional.extend(d) + print( + json.dumps(dict(**meta, rows=sum(r["n"] for r in a), status="verified")), + flush=True, + ) + groups = rollup(cells, views=True) + overall = overall_rows(groups) + curves, inventory = pretrain_rows(cfg) + write_csv(output / "cells.csv", cells) + write_csv(output / "task-view-groups.csv", groups) + write_csv(output / "overall.csv", overall) + write_csv(output / "paired-world-differences.csv", paired_differences(groups)) + write_csv(output / "conditional-task-scores.csv", conditional) + write_csv(output / "pretrain-curves.csv", curves) + with (output / "error-review-samples.jsonl").open("w") as stream: + for example in examples: + stream.write(json.dumps(example, ensure_ascii=False) + "\n") + save_json( + output / "audit.json", + dict( + created_at_utc=datetime.now(timezone.utc).isoformat(), + scope="CPU predictions/logs audit; no checkpoint reload or GPU inference", + config=str(config_path), + config_sha256=hashlib.sha256(config_path.read_bytes()).hexdigest(), + raw_prediction_rows=sum(r["n"] for r in cells), + endpoint_count=len(endpoints), + cells=len(cells), + pretraining_runs=len(inventory), + pretrain_nodes=len(curves), + endpoints=endpoints, + pretrain=inventory, + failures=[], + sources=[ + dict(path=str(p), sha256=hashlib.sha256(p.read_bytes()).hexdigest()) + for p in ( + Path(__file__), + Path("scripts/report_bios_original.py"), + Path("src/llm_memory_editability/bios_original_data.py"), + Path("src/llm_memory_editability/bios_original_train.py"), + *[ + Path(cfg["data_root"]) / f"world-{w}/people.json" + for w in cfg["world_seeds"] + ], + ) + ], + missing_scientific_deliverables=[ + "Independent GPU checkpoint reload remains unverified by this CPU report", + "Oracle-input and extract-then-operate inference are absent from these inputs", + "Pretraining semantic trajectories absent; existing curve is training NLL only", + "Sampled output inspection is separate from exhaustive human semantic adjudication", + ], + ), + ) + save_json( + output / "summary.json", + dict( + development_worlds=cfg["world_seeds"], + independent_worlds=len(cfg["world_seeds"]), + test_overall=[r for r in overall if r["split"] == "test"], + probability_caveat=( + "CoT logp scores the short gold answer immediately after the explanation prompt; " + "it is not the probability of the generated CoT or its final answer." + ), + scoring=( + "Historical answer EM; EOS is reported independently. Views and paired " + "comparison orientations are repeated measurements, not independent worlds." + ), + ), + ) + make_plots(output, curves, overall) + (output / "report.md").write_text(report_text(overall, groups, endpoints)) + return overall diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_train.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_train.py new file mode 100644 index 0000000000000000000000000000000000000000..eea8f0449758025224fd3bb37444cc7e54e7ef7c --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_original_train.py @@ -0,0 +1,669 @@ +"""Restartable development execution for the original bioS experiment, plan 14.27.""" + +from __future__ import annotations + +import contextlib +import json +import math +import os +import random +import re +import time +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_original_data import ( + ATTRS, + MATERIAL, + MONTHS, + TASKS, + BioStream, + answer, + date, + digest, + load_json, + question, + reasoning, + write_json, +) +from .bios_original_model import GPT + + +def setup(seed, device): + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + torch.set_num_threads(4) + torch.manual_seed(seed) + random.seed(seed) + np.random.seed(seed) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.use_deterministic_algorithms(True) + if str(device).startswith("cuda"): + torch.cuda.set_device(device) + + +def amp(device): + return ( + torch.autocast("cuda", dtype=torch.bfloat16) + if str(device).startswith("cuda") + else contextlib.nullcontext() + ) + + +def append(path, record): + with Path(path).open("a") as out: + out.write(json.dumps(record) + "\n") + + +def atomic_save(path, obj): + path = Path(path) + tmp = path.with_suffix(".tmp") + torch.save(obj, tmp) + tmp.replace(path) + + +def pack_tokens(tokens, context=512): + """Adjacent chunks overlap by the context token only; every target is scored once.""" + n = len(tokens) - 1 + rows = math.ceil(n / context) + x = np.full((rows, context), 50256, dtype=np.int64) + y = np.full((rows, context), -100, dtype=np.int64) + x.flat[:n] = tokens[:-1] + y.flat[:n] = tokens[1:] + return torch.from_numpy(x), torch.from_numpy(y) + + +def optimizer_for(model, settings): + params = [p for p in model.parameters() if p.requires_grad] + groups = [ + dict(params=[p for p in params if p.ndim >= 2], weight_decay=settings["weight_decay"]), + dict(params=[p for p in params if p.ndim < 2], weight_decay=0.0), + ] + return torch.optim.AdamW( + groups, + lr=settings["learning_rate"], + betas=tuple(settings.get("adam_betas", [0.9, 0.999])), + eps=settings.get("adam_epsilon", 1e-6), + fused=next(model.parameters()).is_cuda, + ) + + +def parameter_count(model): + return sum(p.numel() for p in model.parameters()) + + +def pretrain(cfg, world, init, condition, device, stop_after_pass=None): + setup(init, device) + root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / "pretrain" + root.mkdir(parents=True, exist_ok=True) + settings = cfg["pretrain"] + data_root = Path(cfg["data_root"]) / f"world-{world}" + stream = BioStream(data_root, world, condition) + contract = dict( + config=cfg, + world=world, + init=init, + condition=condition, + data_audit_sha256=digest(data_root / "audit.json"), + ) + if (root / "contract.json").exists(): + if load_json(root / "contract.json") != contract: + raise ValueError("Run contract changed; use a new run directory") + else: + write_json(root / "contract.json", contract) + model = GPT(cfg["model"]).to(device) + opt = optimizer_for(model, settings) + start, step, seen, elapsed = 0, 0, 0, 0.0 + latest = root / "latest.pt" + 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"]) + start, step, seen, elapsed = [state[k] for k in ("passes", "step", "tokens", "elapsed")] + del state + elif (root / "metrics.jsonl").exists(): + raise ValueError("Metrics without a resumable checkpoint require investigation") + if (root / "metrics.jsonl").exists(): + kept = [ + line + for line in (root / "metrics.jsonl").read_text().splitlines() + if json.loads(line)["passes"] <= start + ] + (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) + if start == 0 and not (root / "pass-000.pt").exists(): + atomic_save(root / "pass-000.pt", dict(model=model.state_dict(), config=cfg["model"])) + if not latest.exists(): + atomic_save( + latest, + dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + passes=0, + step=0, + tokens=0, + elapsed=0.0, + ), + ) + count = parameter_count(model) + write_json( + root / "model.json", + dict( + parameters=count, + trainable=count, + device=str(device), + gpu=torch.cuda.get_device_name(device) if "cuda" in str(device) else "cpu", + torch=torch.__version__, + resume_pass=start, + ), + ) + model.train() + runner = torch.compile(model) if settings.get("compile") else model + wall = time.monotonic() + for epoch in range(start, min(settings["passes"], stop_after_pass or settings["passes"])): + pass_start = time.monotonic() + tokens, order_hash = stream.pass_tokens(epoch) + xs, ys = pack_tokens(tokens, cfg["model"]["context"]) + total_loss, valid_tokens = 0.0, 0 + batch = settings["batch_size"] + micro = settings["micro_batch_size"] + for i in range(0, len(xs), batch): + # Learning rate follows complete-person exposure; no outcome-based stopping. + progress = (epoch + i / len(xs)) / settings["passes"] + cosine = ( + settings["minimum_lr_ratio"] + + (1 - settings["minimum_lr_ratio"]) * (1 + math.cos(math.pi * progress)) / 2 + ) + lr = ( + settings["learning_rate"] + * cosine + * min(1, (step + 1) / max(1, settings["warmup_steps"])) + ) + for group in opt.param_groups: + group["lr"] = lr + opt.zero_grad(set_to_none=True) + end = min(i + batch, len(xs)) + denom = int((ys[i:end] != -100).sum()) + batch_loss = 0.0 + for j in range(i, end, micro): + x, y = ( + xs[j : min(j + micro, end)].to(device), + ys[j : min(j + micro, end)].to(device), + ) + n = int((y != -100).sum()) + with amp(device): + loss = runner(x, y) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite loss at pass {epoch}, step {step}") + (loss * (n / denom)).backward() + batch_loss += loss.detach().item() * n + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), settings["gradient_clip"]) + if not torch.isfinite(norm): + raise FloatingPointError(f"Nonfinite gradient at step {step}") + opt.step() + step += 1 + total_loss += batch_loss + valid_tokens += denom + if step % 10 == 0: + write_json( + root / "status.json", + dict( + state="running", + passes_completed=epoch, + pass_fraction=end / len(xs), + step=step, + learning_rate=lr, + last_batch_nll=batch_loss / denom, + tokens=seen + valid_tokens, + elapsed=elapsed + time.monotonic() - wall, + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + assert valid_tokens == len(tokens) - 1 + seen += valid_tokens + duration = time.monotonic() - pass_start + record = dict( + passes=epoch + 1, + people_presented=(epoch + 1) * stream.count, + tokens=seen, + pass_tokens=valid_tokens, + nll=total_loss / valid_tokens, + seconds=duration, + tokens_per_second=valid_tokens / duration, + step=step, + learning_rate=lr, + presentation_sha256=order_hash, + estimated_training_flops=6 * count * seen, + elapsed=elapsed + time.monotonic() - wall, + ) + append(root / "metrics.jsonl", record) + print(json.dumps(record), flush=True) + if epoch + 1 in settings["nodes"]: + atomic_save( + root / f"pass-{epoch + 1:03d}.pt", + dict(model=model.state_dict(), config=cfg["model"], metrics=record), + ) + if (epoch + 1) % 10 == 0 or epoch + 1 == stop_after_pass or epoch + 1 == settings["passes"]: + atomic_save( + latest, + dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + passes=epoch + 1, + step=step, + tokens=seen, + elapsed=elapsed + time.monotonic() - wall, + ), + ) + write_json( + root / "status.json", + dict( + state="complete" if epoch + 1 == settings["passes"] else "running", + passes_completed=epoch + 1, + **record, + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + return root / f"pass-{settings['passes']:03d}.pt" + + +def encode_row(tokenizer, prompt, target): + prefix = tokenizer.encode(prompt).ids + suffix = tokenizer.encode(" " + target).ids + [50256] + return dict(ids=prefix + suffix, answer_start=len(prefix)) + + +def supervised_batch(rows, device): + width = max(len(r["ids"]) for r in rows) - 1 + x = torch.full((len(rows), width), 50256, dtype=torch.long, device=device) + y = torch.full_like(x, -100) + for i, r in enumerate(rows): + ids = torch.tensor(r["ids"], device=device) + x[i, : len(ids) - 1] = ids[:-1] + y[i, r["answer_start"] - 1 : len(ids) - 1] = ids[r["answer_start"] :] + return x, y + + +def sequence_scores(model, rows, device): + x, y = supervised_batch(rows, device) + h = model.hidden(x) + b, t = torch.where(y != -100) + losses = F.cross_entropy(model.logits(h[b, t]).float(), y[b, t], reduction="none") + sums = torch.zeros(len(rows), device=device).scatter_add_(0, b, losses) + sizes = torch.bincount(b, minlength=len(rows)) + return -sums / sizes, -sums + + +def task_rows(people, tokenizer, tasks, condition, epoch, seed): + rng = random.Random(seed) + # Use the published label vocabulary, independent of held-out person attributes. + cities = sorted( + set((MATERIAL / "fields/city.txt").read_text().splitlines()) + | { + line.split(";", 1)[1].strip() + for line in (MATERIAL / "fields/company.txt").read_text().splitlines() + } + ) + bins = defaultdict(list) + for city in cities: + bins[len(tokenizer.encode(" " + city).ids)].append(city) + rows = [] + for p in people: + if p["split"] != "train": + continue + other = people[p["partner"]] + for j, task in enumerate(tasks): + cot = condition == "MP-CoT" and (p["id"] + j + epoch) % 2 == 0 + prompt = question(p, task, other=other, cot=cot) + target = reasoning(p, task, other) if cot else answer(p, task, other) + row = encode_row(tokenizer, prompt, target) + row.update(person_id=p["id"], task=task, cot=cot) + if task in ("birthcity", "workcity") and p["birthcity"] != p["workcity"]: + competing = p["workcity"] if task == "birthcity" else p["birthcity"] + candidates = [ + c + for c in bins[len(tokenizer.encode(" " + competing).ids)] + if c not in (p["birthcity"], p["workcity"]) + ] + if not candidates: + raise ValueError( + "No length-matched random city; cannot silently relax matching" + ) + negative = rng.choice(candidates) if condition == "MP-Random" else competing + row["negative"] = encode_row(tokenizer, prompt, negative) + rows.append(row) + return rows + + +def rule_rows(tokenizer): + rows = [] + for m, name in enumerate(MONTHS, 1): + rows.append( + encode_row( + tokenizer, + f"Question: Is {name} an even-numbered month?\nAnswer:", + "yes" if m % 2 == 0 else "no", + ) + ) + rng = random.Random(14270000) + for i in range(24): + a, b = [ + dict( + year=rng.randrange(1900, 2100), month=rng.randrange(1, 13), day=rng.randrange(1, 29) + ) + for _ in range(2) + ] + if i % 2: + a, b = ( + max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + ) + else: + a, b = ( + min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + ) + rows.append( + encode_row( + tokenizer, + f"Question: Which date is earlier, {date(a)} or {date(b)}?\nAnswer:", + date(b if i % 2 else a), + ) + ) + return rows + + +def load_model(path, cfg, device, adapters=False): + model = GPT(cfg["model"]) + if adapters: + model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) + state = torch.load(path, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + return model.to(device) + + +def finetune(cfg, world, init, condition, stage, parent, device, tokenizer): + setup(init + 1, device) + root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / stage + root.mkdir(parents=True, exist_ok=True) + people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") + contract = dict( + config=cfg, + world=world, + init=init, + condition=condition, + stage=stage, + parent=str(parent), + parent_sha256=digest(parent), + ) + if (root / "contract.json").exists() and load_json(root / "contract.json") != contract: + raise ValueError("Finetuning contract changed") + write_json(root / "contract.json", contract) + if (root / "complete.json").exists(): + return root / "final.pt" + model = load_model(parent, cfg, device, adapters=stage == "task") + if stage == "adapt": + model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) + model.to(device) + opt = optimizer_for(model, cfg["adapt"]) + start, step = 0, 0 + if (root / "latest.pt").exists(): + ck = torch.load(root / "latest.pt", map_location=device, weights_only=False) + model.load_state_dict(ck["model"]) + opt.load_state_dict(ck["optimizer"]) + start, step = ck["epoch"], ck["step"] + del ck + if (root / "metrics.jsonl").exists(): + kept = [ + line + for line in (root / "metrics.jsonl").read_text().splitlines() + if json.loads(line)["epoch"] <= start + ] + (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) + write_json( + root / "parameters.json", + dict( + total=parameter_count(model), + trainable=sum(p.numel() for p in model.parameters() if p.requires_grad), + trainable_names=[n for n, p in model.named_parameters() if p.requires_grad], + ), + ) + epochs = cfg[stage]["epochs"] + model.train() + for epoch in range(start, epochs): + rows = task_rows( + people, + tokenizer, + ATTRS if stage == "adapt" else TASKS, + condition if stage == "task" else "MP", + epoch, + world + 1427, + ) + if stage == "task": + rows += rule_rows(tokenizer) * cfg["task"]["rule_repetitions_per_epoch"] + random.Random(world + epoch + 20000000).shuffle(rows) + batch, micro = cfg["adapt"]["batch_size"], cfg["adapt"]["micro_batch_size"] + ce_sum, ranking_sum, candidates, target_tokens = 0.0, 0.0, 0, 0 + wall = time.monotonic() + for i in range(0, len(rows), batch): + group = rows[i : i + batch] + lr = cfg["adapt"]["learning_rate"] * ( + 0.1 + 0.9 * (1 + math.cos(math.pi * (epoch + i / len(rows)) / epochs)) / 2 + ) + for pg in opt.param_groups: + pg["lr"] = lr + opt.zero_grad(set_to_none=True) + for j in range(0, len(group), micro): + part = group[j : j + micro] + with amp(device): + scores, _ = sequence_scores(model, part, device) + ce = -scores.mean() + neg_pairs = [(k, r["negative"]) for k, r in enumerate(part) if "negative" in r] + rank = scores.sum() * 0 + if stage == "task" and neg_pairs: + neg, _ = sequence_scores(model, [r for _, r in neg_pairs], device) + pos = scores[[k for k, _ in neg_pairs]] + # Normalize by all positive rows, including zero collision/non-city terms. + rank = F.softplus(cfg["task"]["margin"] - (pos - neg)).sum() / len(part) + candidates += len(neg_pairs) + coefficient = ( + cfg["task"]["ranking_coefficient"] + if condition in ("MP-R", "MP-Random") and stage == "task" + else 0.0 + ) + loss = ce + coefficient * rank + if not torch.isfinite(loss): + raise FloatingPointError("Nonfinite finetuning loss") + (loss * len(part) / len(group)).backward() + ce_sum += ce.item() * len(part) + ranking_sum += rank.item() * len(part) + target_tokens += sum(len(r["ids"]) - r["answer_start"] for r in part) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(norm): + raise FloatingPointError("Nonfinite finetuning gradient") + opt.step() + step += 1 + if step % 25 == 0: + write_json( + root / "status.json", + dict( + state="running", + epoch=epoch, + fraction=min(i + batch, len(rows)) / len(rows), + step=step, + last_ce=ce.item(), + pid=os.getpid(), + updated_unix=time.time(), + ), + ) + rec = dict( + epoch=epoch + 1, + rows=len(rows), + ce=ce_sum / len(rows), + rank=ranking_sum / len(rows), + scored_negative_candidates=candidates, + target_tokens=target_tokens, + seconds=time.monotonic() - wall, + ) + append(root / "metrics.jsonl", rec) + print(json.dumps(rec), flush=True) + atomic_save( + root / "latest.pt", + dict(model=model.state_dict(), optimizer=opt.state_dict(), epoch=epoch + 1, step=step), + ) + atomic_save(root / "final.pt", dict(model=model.state_dict(), config=cfg["model"])) + write_json( + root / "complete.json", + dict(epochs=epochs, step=step, checkpoint_sha256=digest(root / "final.pt")), + ) + return root / "final.pt" + + +@torch.no_grad() +def generate(model, tokenizer, prompts, device, max_tokens): + # Right padding; each row's final real position supplies its own next token. + sequences = [tokenizer.encode(p).ids for p in prompts] + outputs, finished = [[] for _ in prompts], [False] * len(prompts) + for _ in range(max_tokens): + width = max(map(len, sequences)) + if width > model.cfg["context"]: + break + ids = torch.full((len(prompts), width), 50256, dtype=torch.long, device=device) + for i, seq in enumerate(sequences): + ids[i, : len(seq)] = torch.tensor(seq, device=device) + with amp(device): + h = model.hidden(ids) + last = h[ + torch.arange(len(prompts), device=device), + torch.tensor([len(s) - 1 for s in sequences], device=device), + ] + pred = model.logits(last).argmax(-1).tolist() + for i, token in enumerate(pred): + if not finished[i]: + outputs[i].append(token) + sequences[i].append(token) + finished[i] = token == 50256 + if all(finished): + break + return [tokenizer.decode(ids, skip_special_tokens=True).strip() for ids in outputs], finished + + +def normalize(text): + return " ".join(text.strip().rstrip(".").casefold().split()) + + +def recognized_format(text, task, vocabulary): + value = normalize(text) + if task == "parity": + return value in ("yes", "no") + if task == "year": + return bool(re.fullmatch(r"\d{4}", value)) + if task == "date": + return bool( + re.fullmatch( + "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}", + value, + ) + ) + if task in ("company_city", "city_company"): + parts = value.split(";") + fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") + return len(parts) == 2 and all( + part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) + ) + return value in vocabulary["name" if task == "comparison" else task] + + +@torch.no_grad() +def evaluate(cfg, world, checkpoint, output, device, tokenizer, tasks=TASKS, cot=False): + output = Path(output) + if (output / "evaluation-complete.json").exists(): + if load_json(output / "evaluation-complete.json")["checkpoint_sha256"] != digest( + checkpoint + ): + raise ValueError("Evaluated checkpoint changed") + return + output.mkdir(parents=True, exist_ok=True) + people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") + vocabulary = {field: {normalize(p[field]) for p in people} for field in ("name", *ATTRS[1:])} + model = load_model(checkpoint, cfg, device, adapters=True).eval() + totals = defaultdict(lambda: defaultdict(float)) + batch = [] + with (output / "predictions.jsonl").open("w") as out: + + def flush(): + if not batch: + return + enc = [encode_row(tokenizer, r["prompt"], r["answer"]) for r in batch] + with amp(device): + avg, full = sequence_scores(model, enc, device) + generated, ended = generate( + model, + tokenizer, + [r["prompt"] for r in batch], + device, + cfg["evaluation"]["max_new_tokens"], + ) + for row, text, stop, av, lp in zip( + batch, generated, ended, avg.tolist(), full.tolist(), strict=True + ): + extracted = text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text + correct = normalize(extracted) == normalize(row["answer"]) + # Syntactic recognition is distinct from correctness; retain raw output. + recognized = recognized_format(extracted, row["task"], vocabulary) + row.update( + generated=text, + eos=stop, + correct=correct, + format_recognized=recognized, + answer_mean_logp=av, + answer_full_logp=lp, + ) + out.write(json.dumps(row) + "\n") + key = f"{row['split']}/{row['task']}/view-{row['view']}/cot-{row['cot']}" + t = totals[key] + t["n"] += 1 + t["correct"] += correct + t["format_recognized"] += recognized + t["sum_full_logp"] += lp + batch.clear() + write_json( + output / "evaluation-status.json", + dict( + rows=sum(t["n"] for t in totals.values()), + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + + for p in people: + if p["split"] not in cfg["evaluation"]["splits"]: + continue + other = people[p["partner"]] + for task in tasks: + for view in cfg["evaluation"]["views"]: + for use_cot in [False, True] if cot else [False]: + batch.append( + dict( + person_id=p["id"], + split=p["split"], + task=task, + view=view, + cot=use_cot, + partner=other["id"] if task == "comparison" else None, + prompt=question(p, task, view, other, use_cot), + answer=answer(p, task, other), + ) + ) + if len(batch) == cfg["evaluation"]["batch_size"]: + flush() + flush() + write_json( + output / "evaluation-complete.json", + dict(checkpoint_sha256=digest(checkpoint), totals=dict(totals)), + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_path_diagnostics.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_path_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..219336bcde27c897b81d6c253255dca79eb11d1c --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_path_diagnostics.py @@ -0,0 +1,727 @@ +"""Read-only answer-source diagnostics for the frozen two-chain experiments. + +Matching an answer to a candidate is a behavioral description, not evidence that +the model used that internal path. Multiple matching roles are never tie-broken. +""" + +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, write_json + +LEARNING_ROLES = ("default", "actual", "other_default", "other_actual") +EDIT_ROLES = ( + "new_default", + "new_actual", + "old_default", + "old_actual", + "other_default", + "other_actual", +) +# Codes are shared across files. Role names differ between learning and editing. +NOT_APPLICABLE, TERMINATION_ERROR, OTHER, INDISTINGUISHABLE = -1, 0, 1, 2 +ROLE_CODE_START = 3 + + +def file_sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def classify_answers(prediction, ended, candidates): + """Return exclusive categories plus *all* matched role bits, including overlaps. + + An unfinished generation is a termination error even if its value matches. + Correctness is deliberately separate: a correct answer can have ambiguous roles. + """ + prediction, ended, candidates = map(np.asarray, (prediction, ended, candidates)) + if ( + candidates.ndim != 2 + or prediction.shape != ended.shape + or candidates.shape[0] != len(prediction) + ): + raise ValueError("Incompatible prediction/candidate shapes") + if not 1 <= candidates.shape[1] <= 8: + raise ValueError("Candidate role bitset requires one to eight roles") + matched = prediction[:, None] == candidates + n_matches = matched.sum(axis=1) + bits = (matched.astype(np.uint8) * (1 << np.arange(candidates.shape[1]))).sum(axis=1) + category = np.full(len(prediction), OTHER, dtype=np.int8) + unique = n_matches == 1 + category[unique] = ROLE_CODE_START + matched[unique].argmax(axis=1) + category[n_matches > 1] = INDISTINGUISHABLE + category[~ended.astype(bool)] = TERMINATION_ERROR + return category, bits.astype(np.uint8) + + +def candidate_answers(world, chain, target=None): + """Candidate values for all people, with no dependence on model predictions.""" + other = 1 - chain + old_default = world.answers[world.root_ids[chain, world.memberships[chain]]] + old_actual = world.answers[world.actual_ids[chain]] + current = world.answers if target is None else target + other_default = current[world.root_ids[other, world.memberships[other]]] + other_actual = current[world.actual_ids[other]] + if target is None: + roles = LEARNING_ROLES + values = (old_default, old_actual, other_default, other_actual) + else: + roles = EDIT_ROLES + values = ( + target[world.root_ids[chain, world.memberships[chain]]], + target[world.actual_ids[chain]], + old_default, + old_actual, + other_default, + other_actual, + ) + return roles, np.column_stack(values) + + +def score_saved_arrays(arrays, answers): + prediction, ended = arrays["prediction"], arrays["ended"] + if prediction.shape != answers.shape or ended.shape != answers.shape: + raise ValueError("Saved prediction length differs from truth") + if not np.isin(ended, [False, True]).all(): + raise ValueError("Invalid termination flags") + correct = (prediction == answers) & ended.astype(bool) + if not np.array_equal(correct, arrays["correct"]): + raise ValueError("Saved correctness differs from value-plus-EOS scoring") + return correct + + +def annotate_predictions(world, arrays, target=None): + """Full-query arrays plus candidate matrices aligned with derived_query_ids.""" + answers = world.answers if target is None else target + correct = score_saved_arrays(arrays, answers) + category = np.full(len(answers), NOT_APPLICABLE, dtype=np.int8) + bits = np.zeros(len(answers), dtype=np.uint8) + candidates = [] + for chain in range(2): + roles, values = candidate_answers(world, chain, target) + ids = world.derived_ids[chain] + category[ids], bits[ids] = classify_answers( + arrays["prediction"][ids], arrays["ended"][ids], values + ) + candidates.append(values) + return { + "query_id": np.arange(len(answers), dtype=np.int32), + "prediction": np.asarray(arrays["prediction"], dtype=np.int32), + "ended": np.asarray(arrays["ended"], dtype=bool), + "correct": correct, + "class_code": category, + "matched_role_bits": bits, + "derived_query_ids": world.derived_ids.astype(np.int32), + "candidate_tokens": np.stack(candidates).astype(np.int32), + "candidate_roles": np.array(roles), + } + + +def learning_subsets(world): + """Overlapping diagnostic groups; every row retains its own denominator.""" + yield "all_queries", np.arange(len(world.answers)) + yield "base", np.arange(world.n_base) + yield "independent_attributes", np.flatnonzero(np.isin(world.relation, [3, 4, 5, 6])) + for chain, name in enumerate(CHAINS): + for relation, ids in ( + ("membership", world.membership_ids[chain]), + ("default", world.root_ids[chain]), + ("actual", world.actual_ids[chain]), + ): + yield f"{name}/base/{relation}", ids + for split, ids in ( + ("all", world.derived_ids[chain]), + ("trained", world.train_ids[chain]), + ("heldout", world.heldout_ids[chain]), + ): + yield f"{name}/qa/{split}/all", ids + for label, mask in ( + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + yield ( + f"{name}/qa/{split}/{label}", + np.intersect1d(ids, world.derived_ids[chain, mask]), + ) + + +def editing_subsets(world, pair, chain, target): + yield "E/all", pair["E"] + yield "E/default", np.intersect1d(pair["E"], world.root_ids[chain]) + yield "E/actual", np.intersect1d(pair["E"], world.actual_ids[chain]) + # Membership in the 45-person manipulated cohort differs from factual conflict: + # six old exceptions can also conflict; coherent edits have no *new* conflicts. + actual_conflict = target[world.derived_ids[chain]] != target[world.actual_ids[chain]] + for split, ids in ( + ("all", pair["D"]), + ("trained", np.intersect1d(pair["D"], world.train_ids[chain])), + ("heldout", np.intersect1d(pair["D"], world.heldout_ids[chain])), + ): + yield f"D/{split}/all", ids + for label, group in ( + ("manipulated_conflict_cohort", pair["conflict_D"]), + ("factual_conflict", world.derived_ids[chain, actual_conflict]), + ("no_factual_conflict", world.derived_ids[chain, ~actual_conflict]), + ("old_exception", world.derived_ids[chain, world.exceptions[chain]]), + ("ordinary", world.derived_ids[chain, ~world.exceptions[chain]]), + ): + yield f"D/{split}/{label}", np.intersect1d(ids, group) + for pool_name, pool in ( + ("full", np.flatnonzero(pair["strata"] >= 0)), + ("editor_heldout", pair["heldout"]), + ): + yield f"U/{pool_name}/all", pool + for stratum in range(4): + yield ( + f"U/{pool_name}/stratum_{stratum}", + np.intersect1d(pool, np.flatnonzero(pair["strata"] == stratum)), + ) + + +def summary_rows(world, annotations, subsets, identity, old_correct=None): + """Counts are sufficient to reaggregate without hiding empty or ambiguous cells.""" + classes, bits = annotations["class_code"], annotations["matched_role_bits"] + for label, ids in subsets: + ids = np.asarray(ids) + correct = annotations["correct"][ids] + row = { + **identity, + "subset": label, + "n": len(ids), + "correct": int(correct.sum()), + "accuracy": float(correct.mean()) if len(ids) else None, + "termination_error": int((~annotations["ended"][ids]).sum()), + "role_not_applicable": int((classes[ids] == NOT_APPLICABLE).sum()), + "other_answer": int((classes[ids] == OTHER).sum()), + "indistinguishable": int((classes[ids] == INDISTINGUISHABLE).sum()), + "indistinguishable_wrong": int(((classes[ids] == INDISTINGUISHABLE) & ~correct).sum()), + } + # Stable CSV schema, even though learning uses only four roles. + for role in dict.fromkeys((*LEARNING_ROLES, *EDIT_ROLES)): + role_names = list(annotations["candidate_roles"]) + if role in role_names: + index = role_names.index(role) + row[f"unique_{role}"] = int((classes[ids] == ROLE_CODE_START + index).sum()) + row[f"matches_{role}"] = int( + (((bits[ids] & (1 << index)) != 0) & annotations["ended"][ids]).sum() + ) + else: + row[f"unique_{role}"] = row[f"matches_{role}"] = 0 + if old_correct is not None: + known = old_correct[ids] + row["old_known"] = int(known.sum()) + row["old_known_coverage"] = float(known.mean()) if len(ids) else None + row["old_known_now_wrong"] = int((known & ~correct).sum()) + row["damage_rate"] = ( + (float((known & ~correct).sum() / known.sum()) if known.any() else None) + if label.startswith("U/") + else None + ) + else: + row.update( + old_known=None, old_known_coverage=None, old_known_now_wrong=None, damage_rate=None + ) + yield row + + +def _write_csv(path, rows): + with Path(path).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def _safe_output(output, source_roots): + output = Path(output).resolve() + if any(output == root or root in output.parents for root in source_roots): + raise ValueError("Diagnostics must not be written into source experiment directories") + output.mkdir(parents=True, exist_ok=True) + return output + + +def analyze_saved(repository, output, manifest_path="configs/bios-cross-scale-development-v1.json"): + """Re-score the complete matrix using CPU arrays; never invoke old summary writers.""" + repository = Path(repository).resolve() + manifest_path = repository / manifest_path + manifest = json.loads(manifest_path.read_text()) + source_roots = [(repository / size["output"]).resolve() for size in manifest["sizes"]] + output = _safe_output(output, source_roots) + ledger = {} + + def record(path): + path = Path(path).resolve() + key = str(path.relative_to(repository)) if repository in path.parents else str(path) + digest = file_sha256(path) + if key in ledger and ledger[key] != digest: + raise ValueError(f"Source changed during analysis: {path}") + ledger[key] = digest + + record(manifest_path) + worlds, pairs = {}, {} + learning_rows, editing_rows, error_rows = [], [], [] + counts = { + "models": 0, + "learning_checkpoints": 0, + "edit_cases": 0, + "edit_checkpoints": 0, + "scored_query_predictions": 0, + "classified_derived_predictions": 0, + } + for size, root in zip(manifest["sizes"], source_roots, strict=True): + contract_path = root / "launch-contract.json" + record(contract_path) + contract = json.loads(contract_path.read_text()) + study = contract["study"] + expected_runs = { + (w, seed, condition) + for w in study["worlds"] + for seed in study["seeds"] + for condition in CONDITIONS + } + seen_runs = set() + for config_path in sorted(root.glob("world-*/config.json")): + record(config_path) + config = json.loads(config_path.read_text()) + if config["sources"] != contract["sources"] or config["study"] != study: + raise ValueError(f"Run contract mismatch: {config_path}") + for name, digest in config["sources"].items(): + path = repository / "src/llm_memory_editability" / name + if file_sha256(path) != digest: + raise ValueError(f"Frozen source changed: {name}") + record(path) + run = config_path.parent + key = (config["world"], config["seed"], config["condition"]) + if key in seen_runs: + raise ValueError("Duplicate model") + seen_runs.add(key) + if not (run / "complete.json").exists(): + raise ValueError(f"Incomplete run: {run}") + record(run / "complete.json") + world_seed = config["world"] + if world_seed not in worlds: + worlds[world_seed] = make_cross_world( + world_seed, repository / "data/bios-organization-v1" + ) + world = worlds[world_seed] + if config["truth_sha256"] != array_hash(world.answers) or config[ + "prompts_sha256" + ] != array_hash(world.prompts): + raise ValueError("Generated data mismatch") + common = { + "width": size["width"], + "parameters": config["parameters"], + "world": world_seed, + "seed": config["seed"], + "condition": config["condition"], + } + out_run = output / "queries" / f"width-{size['width']}" / run.name + out_run.mkdir(parents=True, exist_ok=True) + baseline = None + for step in study["checkpoints"]: + prediction_path = run / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {name: loaded[name] for name in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays) + np.savez_compressed(out_run / f"learning-{step}.npz", **annotated) + identity = { + **common, + "phase": "learning", + "chain": "", + "kind": "", + "scope": "", + "step": step, + } + learning_rows.extend( + summary_rows(world, annotated, learning_subsets(world), identity) + ) + counts["learning_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + if step == study["steps"]: + baseline = arrays["correct"] + if baseline is None: + raise ValueError("Missing learning endpoint") + for chain, name in enumerate(CHAINS): + pair_key = (world_seed, chain) + if pair_key not in pairs: + pairs[pair_key] = edit_pair(world, chain) + pair = pairs[pair_key] + for kind in ("coherent", "exception"): + target = pair[kind] + for scope in ("mlp", "all"): + case = f"{name}-{kind}-{scope}" + dest = run / "edits" / case + record(dest / "complete.json") + record(dest / "sets.npz") + with np.load(dest / "sets.npz", allow_pickle=False) as loaded: + for field, expected in pair.items(): + if not np.array_equal(loaded[field], expected): + raise ValueError(f"Edit set mismatch: {dest}/{field}") + if not np.array_equal(loaded["old_correct"], baseline): + raise ValueError(f"Edit baseline mismatch: {dest}") + for step in study["edit_checkpoints"]: + prediction_path = dest / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {k: loaded[k] for k in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays, target) + np.savez_compressed(out_run / f"{case}-{step}.npz", **annotated) + identity = { + **common, + "phase": "editing", + "chain": name, + "kind": kind, + "scope": scope, + "step": step, + } + editing_rows.extend( + summary_rows( + world, + annotated, + editing_subsets(world, pair, chain, target), + identity, + baseline, + ) + ) + # Readable per-D query ledger, with every ambiguity explicitly retained. + roles, values = candidate_answers(world, chain, target) + for query in pair["D"]: + person = world.person[query] + matches = [ + role + for i, role in enumerate(roles) + if annotated["matched_role_bits"][query] & (1 << i) + ] + code = int(annotated["class_code"][query]) + category = { + TERMINATION_ERROR: "termination_error", + OTHER: "other", + INDISTINGUISHABLE: "indistinguishable", + } + error_rows.append( + { + **identity, + "query": int(query), + "person": int(person), + "heldout": bool(query in world.heldout_ids[chain]), + "old_exception": bool(world.exceptions[chain, person]), + "manipulated_conflict_cohort": bool( + query in pair["conflict_D"] + ), + "factual_conflict": bool( + values[person, 0] != values[person, 1] + ), + "prediction": int(arrays["prediction"][query]), + "ended": bool(arrays["ended"][query]), + "correct": bool(arrays["correct"][query]), + "class": category.get( + code, + roles[code - ROLE_CODE_START] + if code >= ROLE_CODE_START + else "", + ), + "matched_roles": "|".join(matches), + **{ + role: int(values[person, i]) + for i, role in enumerate(roles) + }, + } + ) + counts["edit_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + counts["edit_cases"] += 1 + counts["models"] += 1 + print(json.dumps({"event": "p0_model_scored", **common, **counts}), flush=True) + if seen_runs != expected_runs: + raise ValueError(f"Incomplete or unexpected model grid: width {size['width']}") + if ( + counts["models"] != manifest["learning_runs"] + or counts["edit_cases"] != manifest["edit_cases"] + ): + raise ValueError("Incomplete matrix") + _write_csv(output / "learning-strata.csv", learning_rows) + _write_csv(output / "editing-strata.csv", editing_rows) + _write_csv(output / "propagation-queries.csv", error_rows) + # Verify that reading/analysis did not mutate any source and that no parallel + # process changed this historical input batch while it was being analyzed. + for name, digest in ledger.items(): + if file_sha256(repository / name) != digest: + raise ValueError(f"Source changed during analysis: {name}") + write_json(output / "sources.json", ledger) + write_json( + output / "schema.json", + { + "class_codes": { + "not_applicable_to_base_query": -1, + "termination_error": 0, + "other": 1, + "indistinguishable": 2, + "unique_role_start": 3, + }, + "learning_roles": LEARNING_ROLES, + "editing_roles": EDIT_ROLES, + "matched_role_bits": "bit i indicates value matches role i; EOS checked separately", + "candidate_tokens_shape": "chain, person, role; " + "maps to derived_query_ids[chain, person]", + "interpretation": "Candidate answer agreement is not causal evidence for a path. " + "Overlapping roles are never assigned a preferred interpretation.", + "subset_rows_overlap": True, + "manipulated_conflict_cohort": "Original 45 people, also tagged in coherent controls; " + "factual_conflict is measured from actual target answers.", + }, + ) + code_hashes = { + str(path.relative_to(repository)): file_sha256(path) + for path in (Path(__file__).resolve(), repository / "scripts/analyze_bios_paths.py") + } + audit = { + "complete": True, + **counts, + "source_files": len(ledger), + "sources_sha256": file_sha256(output / "sources.json"), + "analysis_sources": code_hashes, + "errors": [], + "source_data_modified": False, + "source_hashes_rechecked_after_analysis": True, + } + write_json(output / "audit.json", audit) + _report(output, audit, learning_rows, editing_rows) + return audit + + +def _report(output, audit, learning_rows, editing_rows): + lines = [ + "# P0:已有预测的行为诊断", + "", + f"完成{audit['models']}个模型、{audit['edit_cases']}个编辑;" + f"重计分{audit['learning_checkpoints']}个学习和{audit['edit_checkpoints']}个编辑检查点。", + "", + "候选答案相同的角色记为不可区分;答案重合不能证明内部路径。" + "终止失败独立于答案值记录。下表为案例等权均值,非独立查询推断。", + "", + "| 宽度 | 编辑 | 案例 | 冲突留出D | 新实际城市匹配 | 不可区分 | 终止失败 |", + "|---:|---|---:|---:|---:|---:|---:|", + ] + grouped = defaultdict(list) + for row in editing_rows: + if ( + row["kind"] == "exception" + and row["step"] == 512 + and row["subset"] == "D/heldout/manipulated_conflict_cohort" + ): + grouped[row["width"], row["scope"]].append(row) + for (width, scope), rows in sorted(grouped.items()): + rates = [ + np.mean([r[key] / r["n"] for r in rows]) + for key in ("correct", "matches_new_actual", "indistinguishable", "termination_error") + ] + lines.append( + f"| {width} | {scope} | {len(rows)} | " + + " | ".join(f"{100 * rate:.2f}%" for rate in rates) + + " |" + ) + lines += [ + "", + "新实际城市匹配是允许与旧实际/另一条链答案重合的描述性比例;" + "唯一匹配和全部角色位图均另存,不能据此宣称捷径已证实。", + "", + "学习分层见 learning-strata.csv;编辑分层见 editing-strata.csv;" + "每条传播查询见 propagation-queries.csv;全部逐查询数组见 queries/。", + "自主两步前向诊断尚须单独执行并记录模型权重来源。", + "", + ] + (output / "report.md").write_text("\n".join(lines)) + + +def free_generate_values(model, prompts, lengths, device, batch_size=512): + """Exactly the frozen value-plus-EOS generation convention, without targets.""" + import torch + + from .bios_train import precision + + predictions, ended = [], [] + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[begin : begin + batch_size], device=device) + n = torch.as_tensor(lengths[begin : begin + batch_size], device=device) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)} + + +def autonomous_two_step(model, world, chain, device, batch_size=512, answers=None): + """Generate bridge identity, then query that predicted identity, never the true one. + + Truth is accessed only for scoring after both model calls. A wrong but valid + bridge may coincidentally lead to a correct city; keep that outcome and the + first-hop correctness separately. Invalid/unterminated bridges fail outright. + """ + membership_ids = world.membership_ids[chain] + first = free_generate_values( + model, world.prompts[membership_ids], world.lengths[membership_ids], device, batch_size + ) + allowed_subjects = world.prompts[world.root_ids[chain], 1] + valid = first["ended"] & np.isin(first["prediction"], allowed_subjects) + second_prediction = np.full(len(membership_ids), -1, dtype=np.int64) + second_ended = np.zeros(len(membership_ids), dtype=bool) + if valid.any(): + # Root queries have the same grammar and relation token. Do not choose a + # template using true membership; replace the subject using generated data. + root_template = world.prompts[world.root_ids[chain, 0]] + prompts = np.broadcast_to(root_template, (int(valid.sum()), 5)).copy() + prompts[:, 1] = first["prediction"][valid] + lengths = np.full(len(prompts), world.lengths[world.root_ids[chain, 0]], dtype=np.int64) + second = free_generate_values(model, prompts, lengths, device, batch_size) + second_prediction[valid], second_ended[valid] = second["prediction"], second["ended"] + target = world.answers if answers is None else answers + return { + "query_id": world.derived_ids[chain], + "bridge_prediction": first["prediction"], + "bridge_ended": first["ended"], + "bridge_valid": valid, + "bridge_correct": (first["prediction"] == target[membership_ids]) & first["ended"], + "prediction": second_prediction, + "ended": second_ended, + "correct": valid & second_ended & (second_prediction == target[world.derived_ids[chain]]), + } + + +def diagnose_two_step_run( + run, output, device="cuda", learning_steps=(15360,), include_edits=False, batch_size=512 +): + """Independent, resumable forward-only jobs; no optimizer or training mutations.""" + import torch + + from .bios_model import CausalLM, ModelConfig + + run, output = Path(run).resolve(), Path(output).resolve() + repository = Path(__file__).resolve().parents[2] + output = _safe_output(output, [run]) + config = json.loads((run / "config.json").read_text()) + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if array_hash(world.answers) != config["truth_sha256"]: + raise ValueError("Two-step world differs from trained world") + device = torch.device(device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + jobs = [ + ( + f"learning-{step}", + run / f"model-{step}.pt", + world.answers, + run / f"predictions-{step}.npz", + ) + for step in learning_steps + ] + if include_edits: + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + for kind in ("coherent", "exception"): + for scope in ("mlp", "all"): + dest = run / "edits" / f"{name}-{kind}-{scope}" + jobs.append( + ( + dest.name, + dest / "model-final.pt", + pair[kind], + dest / f"predictions-{config['study']['edit_steps']}.npz", + ) + ) + for label, checkpoint, answers, direct_path in jobs: + dest = output / label + dest.mkdir(parents=True, exist_ok=True) + identity = { + "run": str(run), + "checkpoint": str(checkpoint), + "checkpoint_sha256": file_sha256(checkpoint), + "direct_predictions_sha256": file_sha256(direct_path), + "config_sha256": file_sha256(run / "config.json"), + "diagnostic_source_sha256": file_sha256(__file__), + "answer_sha256": array_hash(answers), + "batch_size": batch_size, + "device_type": device.type, + "torch": torch.__version__, + "precision": "BF16 autocast; FP32 weights" if device.type == "cuda" else "FP32", + } + complete_path = dest / "complete.json" + if complete_path.exists(): + saved = json.loads(complete_path.read_text()) + if saved["identity"] != identity: + raise ValueError(f"Changed diagnostic identity: {dest}") + continue + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + with np.load(direct_path) as data: + direct = {k: data[k] for k in ("prediction", "ended", "correct")} + score_saved_arrays(direct, answers) + rows = [] + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device, batch_size, answers) + ids = world.derived_ids[chain] + arrays.update({f"direct_{k}": v[ids] for k, v in direct.items()}) + np.savez_compressed(dest / f"{name}.npz", **arrays) + for split, mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("trained", np.isin(ids, world.train_ids[chain])), + ("heldout", np.isin(ids, world.heldout_ids[chain])), + ): + for population, population_mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + selected = mask & population_mask + n = int(selected.sum()) + rows.append( + { + "chain": name, + "split": split, + "population": population, + "n": n, + **{ + key: int(arrays[key][selected].sum()) + for key in ( + "correct", + "direct_correct", + "bridge_valid", + "bridge_correct", + ) + }, + } + ) + _write_csv(dest / "summary.csv", rows) + write_json( + complete_path, + { + "identity": identity, + "complete": True, + "queries": int(world.derived_ids.size), + "oracle_bridging": False, + }, + ) + del model, saved + if device.type == "cuda": + torch.cuda.empty_cache() + print( + json.dumps({"event": "two_step_complete", "run": str(run), "case": label}), flush=True + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_path_minimal.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_path_minimal.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2ed53451de1a88abe78ee5e58cb49745597c2b --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_path_minimal.py @@ -0,0 +1,379 @@ +"""Two-layer follow-up: common-error removal versus competing new answers.""" + +import argparse +import fcntl +import itertools +import json +import os +import subprocess +import sys +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig +from .bios_path_transfer import ROOT, inner, norm, path_mode, sha, stamp, tensor_sha + +CONFIG = ROOT / "configs/bios-path-minimal-v1.json" + + +def toy_data(config, device): + people = config["people"] + person = torch.arange(people, device=device).repeat_interleave(3) + relation = torch.arange(3, device=device).repeat(people) + value_start = 3 + people + 3 + tokens = torch.stack( + (torch.ones_like(person), 3 + person, 3 + people + relation, torch.full_like(person, 2)), -1 + ) + labels = value_start + (person + (relation == 2)) % 3 + return tokens, labels, value_start + + +def probe_data(config, person, kind, device): + tokens, old, values = toy_data(config, device) + ids = torch.arange(person * 3, person * 3 + 3, device=device) + a, b, c = values + (person + 1) % 3, values + (person + 2) % 3, values + person % 3 + labels = old[ids].clone() + labels[0], labels[1] = a if kind == "coherent" else b, a + return tokens[ids], labels, (a, b, c) + + +def gradients(model, tokens, labels, arm): + projection = model.blocks[0].mlp.down + captured = {} + + def hook(module, inputs, output): + captured["z"], captured["h"] = inputs[0], output + + handle = projection.register_forward_hook(hook) + try: + with path_mode(model, 0, arm): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits.double(), labels, reduction="none") + actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) + z, delta = captured["z"].detach(), delta.detach() + g = torch.einsum("btd,btk->btdk", delta, z).sum(1) + if norm(g.sum(0) - actual) / max(norm(actual), 1e-30) > 5e-5: + raise ValueError("Minimal-model gradient reconstruction failed") + return {"logits": logits.detach(), "loss": loss.detach(), "g": g, "z": z, "delta": delta} + finally: + handle.remove() + + +@torch.no_grad() +def evaluate(model, tokens, labels, values): + logits = model(tokens)[:, -1].double() + p = logits.softmax(-1) + a, b, c = values + return { + "loss": F.cross_entropy(logits, labels, reduction="none").cpu().tolist(), + "prediction": logits.argmax(-1).cpu().tolist(), + "probabilities_abc": p[:, [a, b, c]].cpu().tolist(), + "source_target_probability": p[0, labels[0]].item(), + "derived_margin_ab": (logits[1, a] - logits[1, b]).item(), + "isotropic_same_probability_reference": (p[1].square().sum() - p[1, a] - p[1, b]).item(), + } + + +def freeze(config): + directory = ROOT / config["artifacts"] + directory.mkdir(parents=True, exist_ok=True) + path = directory / "preregistration-lock.json" + if path.exists(): + raise FileExistsError("Cannot replace minimal-model prospective lock") + section = ( + "### 18.7 " + (ROOT / "docs/experimental-protocol.md").read_text().split("### 18.7 ", 1)[1] + ) + (directory / "preregistration.md").write_text(section) + files = [ + CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_path_minimal.py", + ROOT / "scripts/analyze_bios_path_margin.py", + ROOT / "tests/test_bios_path_minimal.py", + ROOT / "src/llm_memory_editability/bios_path_transfer.py", + ROOT / "src/llm_memory_editability/bios_model.py", + ROOT / "docs/development-artifacts/path-transfer-v1/audit.json", + ] + sources = {} + for file in files: + relative = file.relative_to(ROOT) + sources[str(relative)] = sha(file) + destination = directory / "frozen-files" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(file.read_bytes()) + write_json( + path, + { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(directory / "preregistration.md"), + "torch": torch.__version__, + }, + ) + return {"lock": str(path), "sha256": sha(path)} + + +def verify(config): + directory = ROOT / config["artifacts"] + path = directory / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Minimal config/runtime changed") + for name, digest in lock["sources"].items(): + if sha(ROOT / name) != digest: + raise ValueError("Minimal frozen source changed: " + name) + if sha(directory / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Minimal protocol changed") + return sha(path) + + +def learn(config, seed, device, out): + torch.manual_seed(seed) + tokens, labels, values = toy_data(config, device) + model = CausalLM(ModelConfig(values + 3, config["width"], 2, config["heads"], context=8)).to( + device + ) + if (out / "parent.pt").exists(): + saved = torch.load(out / "parent.pt", map_location=device, weights_only=False) + model.load_state_dict(saved["model"]) + return model + optimizer = torch.optim.AdamW( + model.parameters(), lr=config["train_lr"], weight_decay=config["train_weight_decay"] + ) + trajectory = [] + for step in range(config["train_steps"] + 1): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits, labels) + if step in (0, 128, 512, config["train_steps"]): + trajectory.append( + { + "step": step, + "loss": loss.item(), + "accuracy": logits.argmax(-1).eq(labels).float().mean().item(), + } + ) + if step == config["train_steps"]: + break + optimizer.zero_grad(set_to_none=True) + loss.backward() + optimizer.step() + torch.save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": config["train_steps"], + }, + out / "parent.pt", + ) + write_json(out / "learning.json", trajectory) + return model + + +def trajectory(model, parent, config, person, kind, arm, device, directory): + model.load_state_dict(parent) + model.eval() + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name == config["target_parameter"]) + tokens, labels, values = probe_data(config, person, kind, device) + w = model.blocks[0].mlp.down.weight + timeline, steps, factors = [], [], [] + for step in range(config["edit_steps"] + 1): + measure = step % config["measure_every"] == 0 or step == config["edit_steps"] + full = gradients( + model, tokens if measure else tokens[:1], labels if measure else labels[:1], "full" + ) + source = full if arm == "full" else gradients(model, tokens[:1], labels[:1], arm) + if not torch.equal(full["logits"][:1], source["logits"][:1]): + # Different batch sizes allow only normal FP32 GEMM rounding. + if (full["logits"][:1] - source["logits"][:1]).abs().max().item() > 3e-5: + raise ValueError("Minimal forward mismatch") + raw, original = source["g"][0], full["g"][0] + direction = raw * (norm(original) / norm(raw)) if norm(raw) else raw + if measure: + row = { + "step": step, + **evaluate(model, tokens, labels, values), + "source_gradient_norm": norm(original), + "intervened_gradient_norm": norm(raw), + "kernel_source": inner(full["g"][0], direction), + "kernel_derived": inner(full["g"][1], direction), + "kernel_retention": inner(full["g"][2], direction), + "kernel_derived_full": inner(full["g"][1], original), + } + timeline.append(row) + factors.append( + { + key: value.detach().cpu().numpy() + for key, value in { + "z": full["z"], + "delta": full["delta"], + "source_z": source["z"][:1], + "source_delta": source["delta"][:1], + }.items() + } + ) + if step == config["edit_steps"]: + break + before_weight = w.detach().clone() if measure else None + with torch.no_grad(): + w.add_(direction, alpha=-config["edit_lr"]) + if measure: + after = evaluate(model, tokens, labels, values) + actual_delta = w.detach() - before_weight + row["one_step_observed_derived"] = after["loss"][1] - row["loss"][1] + row["one_step_predicted_derived"] = inner(full["g"][1], actual_delta) + row["one_step_margin_change"] = after["derived_margin_ab"] - row["derived_margin_ab"] + steps.append( + { + "step": step, + "source_loss": full["loss"][0].item(), + "direction_norm": norm(direction), + "source_gradient_norm": norm(original), + } + ) + for name, value in model.state_dict().items(): + if name != config["target_parameter"] and not torch.equal(value, parent[name]): + raise ValueError("Minimal frozen parameter changed") + directory.mkdir(parents=True, exist_ok=True) + write_json( + directory / "trajectory.json", + { + "person": person, + "kind": kind, + "arm": arm, + "values_abc": values, + "labels": labels.cpu().tolist(), + "timeline": timeline, + "steps": steps, + }, + ) + np.savez_compressed( + directory / "factors.npz", + **{key: np.stack([factor[key] for factor in factors]) for key in factors[0]}, + ) + torch.save(w.detach().cpu(), directory / "edited-weight.pt") + write_json( + directory / "complete.json", + { + "finished_at": stamp(), + "steps": len(steps), + "weight_sha256": tensor_sha(w), + "frozen_parameters_unchanged": True, + "files": { + name: sha(directory / name) + for name in ("trajectory.json", "factors.npz", "edited-weight.pt") + }, + }, + ) + + +def run(config, seed, device): + lock_hash = verify(config) + if seed not in config["seeds"]: + raise ValueError("Unknown seed") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + out = ROOT / config["output"] / f"seed-{seed}" + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + write_json( + out / "runtime.json", + { + "started_at": stamp(), + "lock_sha256": lock_hash, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + ) + model = learn(config, seed, device, out) + parent = {k: v.detach().clone() for k, v in model.state_dict().items()} + for person, kind, arm in itertools.product( + config["people_to_edit"], config["kinds"], config["arms"] + ): + directory = out / f"person-{person}-{kind}-{arm}" + if not (directory / "complete.json").exists(): + trajectory(model, parent, config, person, kind, arm, device, directory) + print( + json.dumps( + { + "event": "trajectory", + "seed": seed, + "person": person, + "kind": kind, + "arm": arm, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "finished_at": stamp(), + "lock_sha256": lock_hash, + "files": { + str(path.relative_to(out)): sha(path) + for path in out.rglob("*") + if path.is_file() and path != out / "complete.json" and path.name != ".lock" + }, + }, + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("freeze", "worker", "dispatch")) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--gpus", nargs="+", type=int, default=[5, 8]) + args = parser.parse_args() + config = json.loads(CONFIG.read_text()) + if args.command == "freeze": + print(json.dumps(freeze(config))) + elif args.command == "worker": + run(config, args.seed, torch.device(args.device)) + else: + verify(config) + output = ROOT / config["output"] + output.mkdir(parents=True, exist_ok=True) + workers = [] + for index, seed in enumerate(config["seeds"]): + log = (output / f"seed-{seed}.log").open("a") + env = { + **os.environ, + "CUDA_VISIBLE_DEVICES": str(args.gpus[index % len(args.gpus)]), + "PYTHONPATH": str(ROOT / "src"), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + proc = subprocess.Popen( + [ + sys.executable, + str(ROOT / "scripts/run_bios_path_minimal.py"), + "worker", + "--seed", + str(seed), + ], + env=env, + cwd=ROOT, + stdout=log, + stderr=subprocess.STDOUT, + ) + workers.append((proc, log)) + codes = [] + for proc, log in workers: + codes.append(proc.wait()) + log.close() + write_json(output / "dispatch.json", {"finished_at": stamp(), "returncodes": codes}) + if any(codes): + raise RuntimeError("Minimal worker failed; see retained logs") + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_path_transfer.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_path_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..0c54e9cfda468b9a153577dd716a037dde1577f1 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_path_transfer.py @@ -0,0 +1,653 @@ +"""Prospective v2.13: forward-preserving path interventions and local transfer. + +Only a single MLP output weight is differentiated/updated in production. +Downstream parameters are frozen; the custom attention paths alter its input VJP. +""" + +import argparse +import fcntl +import hashlib +import itertools +import json +import os +import platform +import subprocess +import sys +import time +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path +from types import MethodType + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import edit_pair, make_cross_world +from .bios_cross_train import tensor_queries +from .bios_data import EOS, array_hash, write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = ROOT / "configs/bios-path-transfer-v1.json" +ARMS = ("full", "no_cross", "no_mlp", "fixed_qk") + + +def stamp(): + return datetime.now(timezone.utc).isoformat() + + +def sha(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def tensor_sha(value): + return hashlib.sha256(value.detach().cpu().contiguous().numpy().tobytes()).hexdigest() + + +def inner(a, b): + return (a.double() * b.double()).sum().item() + + +def norm(a): + return a.double().norm().item() + + +def relative(a, b): + return norm(a - b) / max(norm(b), 1e-30) + + +def cosine(a, b): + return inner(a, b) / max(norm(a) * norm(b), 1e-30) + + +def attention_surrogate(module, x, mode): + """Correct input Jacobian for frozen QK, or only the diagonal position blocks. + + no_cross makes T copies of the input: copy s only differentiates x_s, + then computes output s with the full original causal context. Thus Q_s, + K_s and V_s derivatives survive; all x_t -> output_s, t != s vanish. + """ + batch, length, width = x.shape + heads, dim = module.heads, width // module.heads + if mode == "no_cross": + expanded = x[:, None].expand(batch, length, length, width) + diagonal = torch.eye(length, device=x.device, dtype=x.dtype)[None, :, :, None] + routed = expanded.detach() + diagonal * (expanded - expanded.detach()) + q, k, v = module.qkv(routed).reshape(batch, length, length, 3, heads, dim).unbind(3) + index = torch.arange(length, device=x.device) + q = q[:, index, index] # B, query, H, D + scores = torch.einsum("bshd,bsthd->bhst", q, k) / dim**0.5 + mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() + a = scores.masked_fill(~mask, -torch.inf).softmax(-1) + output = torch.einsum("bhst,bsthd->bshd", a, v).reshape(batch, length, width) + else: + q, k, v = module.qkv(x).reshape(batch, length, 3, heads, dim).unbind(2) + scores = torch.einsum("bshd,bthd->bhst", q, k) / dim**0.5 + mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() + a = scores.masked_fill(~mask, -torch.inf).softmax(-1) + if mode == "fixed_qk": + a = a.detach() + elif mode != "manual_full": + raise ValueError(mode) + output = torch.einsum("bhst,bthd->bshd", a, v).reshape(batch, length, width) + return module.proj(output) + + +@contextmanager +def path_mode(model, layer, arm): + if arm not in (*ARMS, "manual_full"): + raise ValueError(arm) + saved = [] + try: + for block in model.blocks[layer + 1 :]: + if arm == "no_mlp": + module = block.mlp + original = module.forward + + def stopped(self, x, original=original): + with torch.no_grad(): + return original(x) + + module.forward = MethodType(stopped, module) + saved.append((module, original)) + elif arm != "full": + module = block.attention + original = module.forward + + def altered(self, x, original=original, arm=arm): + with torch.no_grad(): + reference = original(x) + surrogate = attention_surrogate(self, x, arm) + return reference + (surrogate - surrogate.detach()) + + module.forward = MethodType(altered, module) + saved.append((module, original)) + yield + finally: + for module, original in saved: + module.forward = original + + +def cases(world): + result = [] + for chain in range(2): + pair = edit_pair(world, chain) + for group in pair["groups"]: + members = np.flatnonzero(world.memberships[chain] == group) + eligible = members[ + np.isin(world.derived_ids[chain, members], world.heldout_ids) + & np.isin(world.derived_ids[chain, members], pair["conflict_D"]) + ] + if not len(eligible): + raise ValueError("No prespecified heldout conflict person") + person = int(eligible[0]) + others = members[ + (members != person) + & ~world.exceptions[chain, members] + & np.isin(world.derived_ids[chain, members], world.heldout_ids) + ] + if not len(others): + raise ValueError("No prespecified second heldout person") + other = int(others[0]) + distant = int(np.flatnonzero(~np.isin(world.memberships[chain], pair["groups"]))[0]) + root = int(world.root_ids[chain, group]) + actual = int(world.actual_ids[chain, person]) + default = int(pair["coherent"][root]) + alternative = int(pair["exception"][actual]) + if default == alternative: + raise ValueError("Selected person is not a new conflict") + for kind in ("root", "coherent", "conflict"): + source = root if kind == "root" else actual + target = alternative if kind == "conflict" else default + associated = actual if kind == "root" else root + ids = [ + source, + int(world.derived_ids[chain, person]), + int(world.derived_ids[chain, other]), + associated, + int(world.actual_ids[1 - chain, person]), + int(world.actual_ids[chain, distant]), + ] + targets = [target, default, default, default, *world.answers[ids[-2:]].tolist()] + result.append( + { + "name": f"chain-{chain}-group-{int(group)}-{kind}", + "chain": chain, + "group": int(group), + "kind": kind, + "person": person, + "other_person": other, + "ids": ids, + "targets": targets, + "old_targets": world.answers[ids].tolist(), + "roles": [ + "source", + "derived_same", + "derived_other", + "associated", + "retention_local", + "retention_distant", + ], + } + ) + return result + + +def example_data(world, case, device): + # Use the original interface, including teacher-forced answer for EOS loss. + targets = world.answers.copy() + targets[case["ids"]] = case["targets"] + all_data = tensor_queries(world, device, targets) + ids = torch.tensor(case["ids"], device=device) + return {key: value[ids] for key, value in all_data.items()} + + +def subset(data, ids): + return {key: value[ids] for key, value in data.items()} + + +def losses(logits, labels): + return ( + F.cross_entropy( + logits.double().reshape(-1, logits.shape[-1]), labels.reshape(-1), reduction="none" + ) + .reshape(-1, 2) + .mean(-1) + ) + + +def measure(model, data, layer, arm): + projection = model.blocks[layer].mlp.down + captured = {} + + def hook(module, inputs, output): + captured["z"], captured["h"] = inputs[0], output + + handle = projection.register_forward_hook(hook) + try: + with path_mode(model, layer, arm): + logits = model(data["tokens"], data["positions"]) + loss = losses(logits, data["labels"]) + actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) + z = captured["z"].detach() + delta = delta.detach() + per_position = torch.einsum("btd,btk->btdk", delta, z) + mask = torch.zeros(z.shape[:2], device=z.device, dtype=torch.bool) + mask.scatter_(1, data["positions"], True) + g = per_position.sum(1) + supervised = (per_position * mask[:, :, None, None]).sum(1) + unsupervised = (per_position * ~mask[:, :, None, None]).sum(1) + return { + "z": z, + "delta": delta, + "g": g, + "supervised": supervised, + "unsupervised": unsupervised, + "mask": mask, + "loss": loss.detach(), + "logits": logits.detach(), + "reconstruction_error": relative(g.sum(0), actual), + "decomposition_error": relative(supervised + unsupervised, g), + } + finally: + handle.remove() + + +@torch.no_grad() +def assess(model, data): + logits = model(data["tokens"], data["positions"]) + loss = losses(logits, data["labels"]) + first = model(data["prompts"], (data["lengths"] - 1)[:, None])[:, 0].argmax(-1) + continuation = data["tokens"].clone() + rows = torch.arange(len(first), device=first.device) + continuation[rows, data["lengths"]] = first + ended = model(continuation, data["lengths"][:, None])[:, 0].argmax(-1).eq(EOS) + return loss, first, ended + + +def frozen_files(config): + paths = [ + CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_path_transfer.py", + ROOT / "tests/test_bios_path_transfer.py", + ] + for name in ("bios_model.py", "bios_cross.py", "bios_cross_train.py", "bios_data.py"): + paths.append(ROOT / "src/llm_memory_editability" / name) + for world in config["worlds"]: + directory = ROOT / config["source_world_root"] / f"world-{world}" + paths += [ + directory / "world.npz", + directory / "metadata.json", + directory / "evaluation.npz", + ] + for world, seed in itertools.product(config["worlds"], config["seeds"]): + directory = ROOT / config["parent_root"] / f"world-{world}-seed-{seed}-neither" + paths += [directory / "config.json", directory / "learning-complete.json"] + paths += [directory / f"model-{step}.pt" for step in config["states"]] + return paths + + +def freeze(config): + directory = ROOT / config["artifacts"] + directory.mkdir(parents=True, exist_ok=True) + lock_path = directory / "preregistration-lock.json" + if lock_path.exists(): + raise FileExistsError("Cannot replace a prospective lock") + protocol = ( + "## 18. " + (ROOT / "docs/experimental-protocol.md").read_text().split("## 18. ", 1)[1] + ) + (directory / "preregistration.md").write_text(protocol) + manifests = {} + for world in config["worlds"]: + generated = make_cross_world(world, ROOT / config["source_world_root"]) + selected = cases(generated) + if len(selected) != config["cases_per_state"]: + raise ValueError("Case count mismatch") + manifests[str(world)] = { + "truth_sha256": array_hash(generated.answers), + "prompts_sha256": array_hash(generated.prompts), + "cases": selected, + } + write_json(directory / "cases.json", manifests) + sources = {} + for path in frozen_files(config): + relative_path = path.relative_to(ROOT) + sources[str(relative_path)] = sha(path) + if relative_path.parts[0] in ("src", "scripts", "tests", "configs"): + destination = directory / "frozen-files" / relative_path + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(path.read_bytes()) + lock = { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(directory / "preregistration.md"), + "cases_sha256": sha(directory / "cases.json"), + "torch": torch.__version__, + "numpy": np.__version__, + "python": platform.python_version(), + } + write_json(lock_path, lock) + return {"path": str(lock_path), "sha256": sha(lock_path)} + + +def verify_lock(config): + directory = ROOT / config["artifacts"] + path = directory / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Frozen config/runtime mismatch") + for name, digest in lock["sources"].items(): + if sha(ROOT / name) != digest: + raise ValueError("Frozen input changed: " + name) + for name, key in (("preregistration.md", "protocol_sha256"), ("cases.json", "cases_sha256")): + if sha(directory / name) != lock[key]: + raise ValueError("Prospective manifest changed") + return sha(path) + + +def save_factors(path, baseline, sources, data): + arrays = { + "positions": data["positions"].cpu().numpy(), + "labels": data["labels"].cpu().numpy(), + "tokens": data["tokens"].cpu().numpy(), + } + for prefix, result in [("evaluation", baseline), *sources.items()]: + for key in ("z", "delta", "loss"): + arrays[prefix + "_" + key] = result[key].cpu().numpy() + np.savez_compressed(path, **arrays) + + +def run_case(model, world, case, config, destination): + layer = config["target_layer"] + w = model.blocks[layer].mlp.down.weight + parent = w.detach().clone() + frozen_before = { + name: tensor_sha(value) + for name, value in model.state_dict().items() + if name != config["target_parameter"] + } + data = example_data(world, case, w.device) + baseline = measure(model, data, layer, "full") + before, old_prediction, old_ended = assess(model, data) + sources, diagnostics, updates = {}, [], [] + with torch.no_grad(): + if not torch.equal(before, baseline["loss"]): + raise ValueError("Evaluation/gradient forward mismatch") + for arm in config["arms"]: + source = measure(model, subset(data, slice(0, 1)), layer, arm) + sources[arm] = source + error = (source["logits"] - sources["full"]["logits"]).abs().max().item() + if error > config["forward_tolerance"]: + raise ValueError(f"Forward preservation failed: {error}") + if ( + max(source["reconstruction_error"], baseline["reconstruction_error"]) + > config["gradient_tolerance"] + ): + raise ValueError("Outer-product reconstruction failed") + direction = source["g"][0] + gfull = sources["full"]["g"][0] + if arm == "no_cross" and norm(source["unsupervised"]) > 1e-9: + raise ValueError("Cross-position cut did not eliminate unsupervised-position gradient") + for j, role in enumerate(case["roles"]): + row = { + "arm": arm, + "role": role, + "probe": j, + "forward_error": error, + "reconstruction_error": source["reconstruction_error"], + "gradient_norm": norm(direction), + "gradient_cosine_full": cosine(direction, gfull), + "supervised_norm": norm(source["supervised"]), + "unsupervised_norm": norm(source["unsupervised"]), + "kernel": inner(baseline["g"][j], direction), + "source_loss": source["loss"].item(), + "probe_loss": before[j].item(), + } + for left, right in itertools.product(("supervised", "unsupervised"), repeat=2): + row[f"kernel_{left}_{right}"] = inner(baseline[left][j], source[right][0]) + diagnostics.append(row) + for scale, fraction in itertools.product(config["scales"], config["step_fractions"]): + denominator = norm(gfull if scale == "shared_lr" else direction) + eta = fraction * norm(parent) / denominator if denominator else 0.0 + with torch.no_grad(): + w.copy_(parent - eta * direction) + displacement = w.detach() - parent + weight_hash = tensor_sha(w) + after, predicted_token, ended = assess(model, data) + predicted = (baseline["g"].double() * displacement.double()).sum((-1, -2)) + for j, role in enumerate(case["roles"]): + updates.append( + { + "arm": arm, + "scale": scale, + "fraction": fraction, + "eta": eta, + "update_norm": norm(displacement), + "weight_sha256": weight_hash, + "role": role, + "probe": j, + "id": case["ids"][j], + "target": case["targets"][j], + "old_target": case["old_targets"][j], + "before": before[j].item(), + "after": after[j].item(), + "observed_change": (after[j] - before[j]).item(), + "predicted_change": predicted[j].item(), + "ideal_predicted_change": -eta * inner(baseline["g"][j], direction), + "baseline_prediction": int(old_prediction[j]), + "baseline_ended": bool(old_ended[j]), + "prediction": int(predicted_token[j]), + "ended": bool(ended[j]), + } + ) + with torch.no_grad(): + w.copy_(parent) + if not torch.equal(w, parent): + raise ValueError("Parent weight was not restored") + frozen_after = { + name: tensor_sha(value) + for name, value in model.state_dict().items() + if name != config["target_parameter"] + } + if frozen_before != frozen_after: + raise ValueError("A frozen parameter changed") + destination.mkdir(parents=True, exist_ok=True) + save_factors(destination / "factors.npz", baseline, sources, data) + write_json( + destination / "measurements.json", + {"case": case, "diagnostics": diagnostics, "updates": updates}, + ) + write_json( + destination / "receipt.json", + { + "finished_at": stamp(), + "files": { + name: sha(destination / name) for name in ("factors.npz", "measurements.json") + }, + "baseline_reconstruction_error": baseline["reconstruction_error"], + "frozen_parameters_unchanged": True, + "parent_restored": True, + }, + ) + + +def verify_receipt(directory): + receipt = json.loads((directory / "receipt.json").read_text()) + for name, digest in receipt["files"].items(): + if sha(directory / name) != digest: + raise ValueError("Receipt mismatch: " + str(directory / name)) + + +def run(config, world_id, seed, device): + lock_hash = verify_lock(config) + if world_id not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("Worker outside the frozen matrix") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + world = make_cross_world(world_id, ROOT / config["source_world_root"]) + name = f"world-{world_id}-seed-{seed}-neither" + source = ROOT / config["parent_root"] / name + out = ROOT / config["output"] / name + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as stream: + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + started = time.monotonic() + write_json( + out / "runtime.json", + { + "started_at": stamp(), + "lock_sha256": lock_hash, + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if "cuda" in str(device) else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "torch": torch.__version__, + }, + ) + for step in config["states"]: + checkpoint = torch.load( + source / f"model-{step}.pt", map_location="cpu", weights_only=False + ) + if checkpoint["step"] != step: + raise ValueError("Parent step mismatch") + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + model.eval() + for pname, parameter in model.named_parameters(): + parameter.requires_grad_(pname == config["target_parameter"]) + selected = cases(world) + state_out = out / f"step-{step}" + state_out.mkdir(exist_ok=True) + # Original-forward repeated gradient, not a new scientific sample. + sham_data = subset(example_data(world, selected[0], device), slice(0, 1)) + first = measure(model, sham_data, config["target_layer"], "full") + second = measure(model, sham_data, config["target_layer"], "full") + sham_error = relative(first["g"], second["g"]) + if sham_error > config["gradient_tolerance"]: + raise ValueError("Sham gradient failed") + write_json(state_out / "sham.json", {"relative_gradient_error": sham_error}) + for case in selected: + destination = state_out / case["name"] + if (destination / "receipt.json").exists(): + verify_receipt(destination) + else: + run_case(model, world, case, config, destination) + print( + json.dumps( + { + "event": "case", + "world": world_id, + "seed": seed, + "step": step, + "case": case["name"], + } + ), + flush=True, + ) + del model, checkpoint + files = { + str(path.relative_to(out)): sha(path) + for path in out.rglob("*") + if path.is_file() and path.name not in (".lock", "complete.json") + } + write_json( + out / "complete.json", + { + "finished_at": stamp(), + "seconds": time.monotonic() - started, + "lock_sha256": lock_hash, + "cases": len(config["states"]) * len(selected), + "files": files, + }, + ) + + +def dispatch(config, gpus): + verify_lock(config) + output = ROOT / config["output"] + output.mkdir(parents=True, exist_ok=True) + jobs = list(itertools.product(config["worlds"], config["seeds"])) + active, finished = [], [] + with (output / ".dispatch.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + while jobs or active: + for gpu in gpus: + if jobs and not any(item["gpu"] == gpu for item in active): + world, seed = jobs.pop(0) + path = output / f"world-{world}-seed-{seed}-neither" + if (path / "complete.json").exists(): + finished.append({"world": world, "seed": seed, "reused": True}) + continue + log = (output / f"world-{world}-seed-{seed}.log").open("a") + env = { + **os.environ, + "CUDA_VISIBLE_DEVICES": str(gpu), + "PYTHONPATH": str(ROOT / "src"), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + command = [ + sys.executable, + str(ROOT / "scripts/run_bios_path_transfer.py"), + "worker", + "--world", + str(world), + "--seed", + str(seed), + "--device", + "cuda:0", + ] + proc = subprocess.Popen( + command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT + ) + active.append( + {"gpu": gpu, "world": world, "seed": seed, "process": proc, "log": log} + ) + for item in active[:]: + code = item["process"].poll() + if code is not None: + item["log"].close() + record = {k: item[k] for k in ("gpu", "world", "seed")} + finished.append({**record, "returncode": code}) + active.remove(item) + write_json( + output / "dispatch.json", + { + "updated_at": stamp(), + "pending": jobs, + "running": [{k: x[k] for k in ("gpu", "world", "seed")} for x in active], + "finished": finished, + }, + ) + if active: + time.sleep(2) + if any(item.get("returncode", 0) for item in finished): + raise RuntimeError("One or more workers failed; inspect preserved logs") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("freeze", "worker", "dispatch")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--gpus", type=int, nargs="+", default=[5, 8]) + args = parser.parse_args() + config = json.loads(CONFIG.read_text()) + if args.command == "freeze": + print(json.dumps(freeze(config))) + elif args.command == "worker": + run(config, args.world, args.seed, torch.device(args.device)) + else: + dispatch(config, args.gpus) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_readout_control.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_readout_control.py new file mode 100644 index 0000000000000000000000000000000000000000..877089e7e83d985cfb9e4b5e65920b2db8312d4d --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_readout_control.py @@ -0,0 +1,373 @@ +"""H5: original E93 exception edits of all weights except tied token/readout weights.""" + +import argparse +import fcntl +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_metrics, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +SCOPE = "all-freeze-embedding" +STUDY = { + "protocol": "v2.8-h5-readout-control-E93", + "widths": [256, 768], + "parent_step": 15360, + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kind": "exception", + "scope": SCOPE, + "frozen": "token.weight, shared by input embedding and output F.linear readout", + "trainable": "all other parameters, including absolute position embedding", + "lr": 3e-5, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 48, + "E": 93, + "D": 96, + "R": 4096, + "reference_scopes": ["mlp", "all"], + "selection": "all fixed512 endpoints; no best step", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("H5 configuration differs from the fixed contract") + + +def control_sources(): + return { + **source_hashes(), + "bios_cross_continue.py": file_hash(Path(__file__).with_name("bios_cross_continue.py")), + Path(__file__).name: file_hash(__file__), + } + + +def select_control_parameters(model): + """The ordinary model passes this same Parameter directly to F.linear.""" + excluded = id(model.token.weight) + selected = [] + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) != excluded) + parameter.grad = None + if parameter.requires_grad: + selected.append(parameter) + assert model.position.weight.requires_grad and not model.token.weight.requires_grad + return selected + + +def sampling_stream(world_seed, chain, steps=512, batch=128): + rng = rng_for(world_seed, 908, chain) + return rng.integers(93, size=(steps, batch)), rng.integers(4096, size=(steps, batch)) + + +def score_arrays(arrays, truth): + for key in ("prediction", "ended", "correct"): + if arrays[key].shape != truth.shape: + raise ValueError("H5 prediction array shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("H5 EOS/correct flags must be Boolean") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def validate_parent_config(config, world): + width = config["model"]["width"] + if width not in STUDY["widths"] or config["world"] not in (0, 1): + raise ValueError("H5 parent outside original size/world matrix") + expected = dict( + vocab_size=world.vocab_size, width=width, layers=8, heads=width // 64, context=128 + ) + if config["model"] != expected or config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("H5 needs original unrestricted low-prevalence architecture") + expected_study = dict( + steps=15360, + lr=1e-4, + documents_per_step=16, + facts_per_document=10, + QA_per_chain_per_step=20, + document_QA_weights=[0.8, 0.2], + ) + if any(config["study"][key] != value for key, value in expected_study.items()): + raise ValueError("H5 parent is not the original learning budget") + if config["seed"] not in (0, 1) or config["condition"] not in CONDITIONS: + raise ValueError("H5 parent outside original initialization/organization matrix") + if config["sources"] != source_hashes() or config["truth_sha256"] != array_hash(world.answers): + raise ValueError("H5 parent source or truth mismatch") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("H5 numerical software differs from parent") + + +def reference_contract(parent, world, old_arrays): + hashes = {} + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + assert len(pair["E"]) == 93 and len(pair["D"]) == 96 and len(pair["replay"]) == 4096 + e, r = sampling_stream(world.seed, chain) + for scope in ("mlp", "all"): + dest = parent / "edits" / f"{name}-exception-{scope}" + with np.load(dest / "sets.npz") as actual: + for key, value in pair.items(): + np.testing.assert_array_equal(actual[key], value) + np.testing.assert_array_equal(actual["old_correct"], old_arrays["correct"]) + np.testing.assert_array_equal(actual["edit_sampling"], e) + np.testing.assert_array_equal(actual["replay_sampling"], r) + points = json.loads((dest / "trajectory.json").read_text()) + if [point["step"] for point in points] != list(CHECKPOINTS): + raise ValueError("Original MLP/All reference checkpoint grid differs") + if json.loads((dest / "complete.json").read_text())["status"] != "complete": + raise ValueError("Original MLP/All reference incomplete") + for step in CHECKPOINTS: + with np.load(dest / f"predictions-{step}.npz") as saved: + arrays = score_arrays(dict(saved), pair["exception"]) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], old_arrays[key]) + for filename in ( + "sets.npz", + "trajectory.json", + "complete.json", + *(f"predictions-{step}.npz" for step in CHECKPOINTS), + ): + hashes[str((dest / filename).relative_to(parent))] = file_hash(dest / filename) + return hashes + + +def load_parent(parent): + config = json.loads((parent / "config.json").read_text()) + world = make_cross_world(config["world"]) + validate_parent_config(config, world) + with np.load(parent / "predictions-15360.npz") as saved: + arrays = score_arrays(dict(saved), world.answers) + references = reference_contract(parent, world, arrays) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if checkpoint["step"] != 15360 or checkpoint["config"] != config["model"]: + raise ValueError("H5 parent checkpoint identity differs") + if ( + complete["status"] != "complete" + or state_hash(checkpoint["model"]) != complete["model_sha256"] + ): + raise ValueError("H5 parent learning checkpoint is not verified complete") + provenance = dict( + directory=str(parent), + model_sha256=complete["model_sha256"], + reference_files_sha256=references, + files_sha256={ + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + ) + return config, world, arrays, checkpoint, provenance + + +def run_case(model, baseline, data, world, parent_arrays, chain, output, identity_hash, device): + dest = output / f"{CHAINS[chain]}-exception-{SCOPE}" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_control_parameters(model) + frozen = baseline["token.weight"] + pair = edit_pair(world, chain) + e, r = sampling_stream(world.seed, chain) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=parent_arrays["correct"], + edit_sampling=e, + replay_sampling=r, + ) + new_data = tensor_queries(world, device, pair["exception"]) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW(selected, lr=3e-5, weight_decay=0.1, fused=device.type == "cuda") + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("H5 resume identity differs") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("H5 resume step differs") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], 3e-5) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS: + if not torch.equal(model.token.weight.detach().cpu(), frozen): + raise ValueError("Frozen input/output token weights changed") + if not timeline or timeline[-1]["step"] != step: + arrays = score_arrays( + evaluate(model, new_data, pair["exception"]), pair["exception"] + ) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_arrays[key]) + timeline.append( + dict( + step=step, + edit_seconds=seconds, + **edit_metrics(world, pair, arrays, parent_arrays["correct"]), + ) + ) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e[step]], device=device) + ri = torch.as_tensor(pair["replay"][r[step]], device=device) + choices = torch.as_tensor(r[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - start + atomic_torch_save( + dict(model=model.state_dict(), config=model.config_dict(), step=512), + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + dict( + status="complete", + scope=SCOPE, + kind="exception", + chain=CHAINS[chain], + final=timeline[-1], + model_sha256=state_hash(model.state_dict()), + frozen_token_sha256=state_hash({"token.weight": frozen}), + ), + ) + print( + json.dumps(dict(event="H5_edit_complete", case=dest.name, final=timeline[-1])), flush=True + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("H5 output must be separate from immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, world, arrays, checkpoint, provenance = load_parent(parent) + device = torch.device(args.device) + identity = dict( + world=world.seed, + seed=config["seed"], + condition=config["condition"], + width=config["model"]["width"], + study=STUDY, + sources=control_sources(), + parent=provenance, + torch=torch.__version__, + cuda=torch.version.cuda, + numpy=np.__version__, + device_type=device.type, + ) + path = output / "config.json" + if path.exists() and json.loads(path.read_text()) != identity: + raise ValueError("Frozen H5 worker contract changed") + if not path.exists(): + write_json(path, identity) + if (output / "complete.json").exists(): + return + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()} + data = tensor_queries(world, device) + try: + observed = score_arrays(evaluate(model, data, world.answers), world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], arrays[key]) + for chain in range(2): + run_case( + model, baseline, data, world, arrays, chain, output, file_hash(path), device + ) + write_json( + output / "complete.json", + dict(status="complete", edit_cases=2, steps=512, scope=SCOPE, finished=time.time()), + ) + except Exception as error: + write_json( + output / "failure.json", + dict(type=type(error).__name__, message=str(error), time=time.time()), + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-readout-control-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_relation_response.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_relation_response.py new file mode 100644 index 0000000000000000000000000000000000000000..2e69b15143ef5b90779481035823b06102c3b5ab --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_relation_response.py @@ -0,0 +1,187 @@ +"""A paired four-cell test of which fact controls a composite answer. + +The editor is unchanged. Derivative probes use answer contrasts, never a +composite target loss. Isolated directions preserve the OTHER direct query's +two a/c and b/c contrasts to first order, not its entire output distribution. +""" + +from dataclasses import replace + +import torch + +from .bios_direction import Suffix +from .bios_direction_cross import cross_tasks + +CELLS = ("aa", "ab", "ba", "bb") +LAYER = 4 + + +def factorial_tasks(world, seed, device): + """Rows select root targets; columns select personal targets; a/b stay fixed.""" + originals = cross_tasks(world, seed, device) + result = [] + for pair_index in range(6): + base = originals[2 * pair_index] + for cell in CELLS: + labels, tokens = base.labels.clone(), base.tokens.clone() + root, actual = base.sets["E"] + labels[root, 0] = base.metadata[cell[0]] + labels[actual, 0] = base.metadata[cell[1]] + labels[base.sets["D"], 0] = base.metadata[cell[0]] + rows = torch.arange(len(tokens), device=tokens.device) + tokens[rows, base.positions[:, 0] + 1] = labels[:, 0] + metadata = dict( + base.metadata, + cell=cell, + pair_index=pair_index, + kind="coherent" if cell[0] == cell[1] else "independent", + root_target=base.metadata[cell[0]], + actual_target=base.metadata[cell[1]], + ) + result.append( + replace( + base, + name=base.name.rsplit("-", 1)[0] + "-" + cell, + labels=labels, + tokens=tokens, + metadata=metadata, + ) + ) + return result + + +def check_reused_task(task, manifest): + """Compare actual information, including teacher-forced EOS prefixes.""" + current = task.manifest() + for key in ("sets", "labels", "old_labels", "tokens_sha256"): + assert current[key] == manifest[key], key + for key in ("world", "seed", "chain", "group", "person", "a", "b", "c", "original_ids"): + assert current["metadata"][key] == manifest["metadata"][key], key + + +def make_probe(model, task): + ids = task.sets["E"] + task.sets["D_focal"] + positions = task.positions[ids, :1] + tokens = task.tokens[ids, :5].clone() + # No desired answer is present even at masked future positions. + tokens.masked_fill_(torch.arange(5, device=tokens.device)[None] > positions, 0) + return Suffix(model, LAYER, tokens, positions) + + +def values(probe, weight, metadata): + logits = probe(weight[None])[0, :, 0] + a, b, c = (metadata[k] for k in ("a", "b", "c")) + contrasts = torch.stack((logits[:, a] - logits[:, c], logits[:, b] - logits[:, c]), -1) + return logits, contrasts + + +def derivatives(probe, weight, metadata): + w = weight.detach().clone().requires_grad_() + logits, contrasts = values(probe, w, metadata) + gradients = torch.stack( + [ + torch.autograd.grad(contrasts[i, j], w, retain_graph=True)[0] + for i in range(3) + for j in range(2) + ] + ).reshape(3, 2, *w.shape) + return logits.detach(), contrasts.detach(), gradients.detach() + + +def isolated_directions(gradients): + """Minimum-norm direct-fact controls; D is excluded from construction. + + A unit control changes the chosen fact's (a-c,b-c) by (+.5,-.5), + hence its a-b contrast by 1; the other fact has both contrasts fixed. + """ + g = gradients[:2].flatten(0, 1).flatten(1).double() + gram = g @ g.T + eig, vec = torch.linalg.eigh(gram) + keep = eig > eig[-1].clamp_min(1e-30) * 1e-10 + inverse = (vec * torch.where(keep, 1 / eig.clamp_min(1e-300), 0)[None]) @ vec.T + targets = torch.tensor([[0.5, -0.5, 0, 0], [0, 0, 0.5, -0.5]], device=g.device) + controls = targets.double() @ inverse @ g + achieved = controls @ g.T + gd = (gradients[2, 0] - gradients[2, 1]).flatten().double() + coefficients = controls @ gd + residual = gd - (gd @ g.T) @ inverse @ g + summary = { + "rank": int(keep.sum()), + "spectrum": eig.cpu().tolist(), + "control_residual": float((achieved - targets).abs().max()), + "root_response": float(coefficients[0]), + "actual_response": float(coefficients[1]), + "unexplained_D_gradient_fraction": float(residual.norm() / gd.norm().clamp_min(1e-30)), + "root_control_norm": float(controls[0].norm()), + "actual_control_norm": float(controls[1].norm()), + } + return controls.reshape(2, *gradients.shape[-2:]).to(gradients.dtype), summary + + +@torch.no_grad() +def calibrate_controls(probe, weight, metadata, gradients, magnitudes): + controls, summary = isolated_directions(gradients) + baseline_logits, baseline = values(probe, weight, metadata) + rows = [] + if summary["control_residual"] > 1e-5: + return summary, rows + for index, name in enumerate(("root", "actual")): + for magnitude in magnitudes: + for sign in (-1, 1): + delta = sign * magnitude * controls[index] + cap = min(1.0, float(1e-3 * weight.norm() / delta.norm().clamp_min(1e-30))) + delta = delta * cap + changed, after = values(probe, weight + delta, metadata) + observed = after - baseline + predicted = (gradients.double() * delta.double()).sum((-1, -2)) + other = 1 - index + logp = baseline_logits.double().log_softmax(-1) + new_logp = changed.double().log_softmax(-1) + kl = (logp.exp() * (logp - new_logp)).sum(-1) + rows.append( + dict( + control=name, + magnitude=magnitude, + sign=sign, + cap=cap, + actual_target_increment=sign * magnitude * cap, + delta_norm=float(delta.norm()), + predicted_ab=(predicted[:, 0] - predicted[:, 1]).cpu().tolist(), + observed_ab=(observed[:, 0] - observed[:, 1]).cpu().tolist(), + other_ac_bc_drift=float(observed[other].abs().max()), + other_output_kl=float(kl[other]), + direct_argmax_changes=int( + (changed[:2].argmax(-1) != baseline_logits[:2].argmax(-1)).sum() + ), + ) + ) + return summary, rows + + +def first_adam_update(model, task, config): + """Exact first-step algebra of the frozen soft-functional Adam editor.""" + ids = task.sets["E"] + task.sets["R"] + suffix = Suffix(model, LAYER, task.tokens[ids], task.positions[ids]) + w = model.blocks[LAYER].mlp.down.weight.detach().clone().requires_grad_() + logits = suffix(w[None])[0] + logp = logits.double().log_softmax(-1) + labels = task.labels[ids] + ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1) + n = len(task.sets["E"]) + # The original-parent KL has exactly zero derivative at the parent. + loss = ce[:n].mean() + ce[n:].mean() + gradient = torch.autograd.grad(loss, w)[0] + m, v = 0.1 * gradient, 0.001 * gradient.square() + t = torch.ones((), device=w.device) + raw = -(m / (1 - 0.9**t)) / ((v / (1 - 0.999**t)).sqrt() + 1e-8) + return config["lr"] * raw + + +def factorial_effects(margins): + aa, ab, ba, bb = (float(margins[cell]) for cell in CELLS) + return dict( + intercept=(aa + ab + ba + bb) / 4, + root=(aa + ab - ba - bb) / 4, + actual=(aa - ab + ba - bb) / 4, + interaction=(aa - ab - ba + bb) / 4, + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..3943eb3bac42c3c9c13d8b3c40061fc830348860 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py @@ -0,0 +1,372 @@ +"""Locked independent-world behavioral confirmation, never a route-mediation claim. + +The original learning implementation and the audited E39 update implementation +are called directly. An external prospective lock is mandatory before execution. +""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_train import learning, source_hashes +from .bios_data import write_json +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import autonomous_two_step +from .bios_shortcut_confirmation_sets import make_confirmation_edit_pair +from .bios_shortcut_control import high_exception_world +from .bios_shortcut_edit_v2 import STUDY as DEVELOPMENT_EDIT_STUDY +from .bios_shortcut_edit_v2 import run_case +from .bios_shortcut_matched_edit import KINDS, PHASES + +PROTOCOL = "v2.9-shortcut-behavior-confirmation" +WORLDS = tuple(range(100, 108)) +LEARNING_CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360) + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + while chunk := stream.read(4 * 1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def confirmation_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + "scripts/prepare_bios_shortcut_confirmation.py": file_hash( + directory.parents[1] / "scripts/prepare_bios_shortcut_confirmation.py" + ), + **{ + name: file_hash(directory / name) + for name in ( + "bios_shortcut_confirmation.py", + "bios_shortcut_confirmation_sets.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit_v2.py", + "bios_cross_continue.py", + "bios_path_diagnostics.py", + ) + }, + } + + +def validate_config(config): + expected = { + "protocol": PROTOCOL, + "worlds": list(WORLDS), + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "phases": list(PHASES), + "chains": list(CHAINS), + "supports": [0, 1], + "width": 256, + "layers": 8, + "heads": 4, + "steps": 15360, + "checkpoints": list(LEARNING_CHECKPOINTS), + "lr": 0.0001, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "learning_runs": 96, + "edit_cases": 768, + "edit_steps": 512, + "edit_checkpoints": [0, 32, 128, 512], + "edit_lr": 0.00003, + "retention_kl": 1.0, + "edit_scope": "mlp", + "edit_mlp_layers": [3, 4, 5], + "edit_batch": 128, + "replay_batch": 128, + "edit_weight_decay": 0.1, + "E": 39, + "D": 96, + "R": 4096, + "base_world_root": "data/bios-shortcut-confirmation-v1", + "source_root": "data/bios-source", + } + for key, value in expected.items(): + if config.get(key) != value: + raise ValueError(f"Prospective confirmation contract differs: {key}") + for key in ("steps", "checkpoints", "lr", "retention_kl", "E", "D", "R"): + source = {"steps": "edit_steps", "checkpoints": "edit_checkpoints", "lr": "edit_lr"} + if DEVELOPMENT_EDIT_STUDY[key] != config[source.get(key, key)]: + raise ValueError(f"Imported E39 scientific update differs: {key}") + if config.get("edit_sampling") != "shared original world932chain stream across supports": + raise ValueError("The two supports retain the original paired sampling stream") + + +def validate_frozen_design(config_path, lock_path): + config = json.loads(Path(config_path).read_text()) + validate_config(config) + lock = json.loads(Path(lock_path).read_text()) + if lock.get("status") != "frozen_before_any_confirmation_model_or_outcome": + raise ValueError("A prospective confirmation lock is required") + if lock["config_sha256"] != file_hash(config_path): + raise ValueError("Confirmation configuration changed after locking") + if lock["sources"] != confirmation_sources(): + raise ValueError("Confirmation scientific sources changed after locking") + environment = {"torch": torch.__version__, "cuda": torch.version.cuda, "numpy": np.__version__} + if lock["environment"] != environment: + raise ValueError("Confirmation numerical environment changed after locking") + if not lock.get("analysis_sources"): + raise ValueError("The prospective analysis implementation must also be locked") + root = Path(__file__).resolve().parents[2] + for relative, checksum in lock["analysis_sources"].items(): + if file_hash(root / relative) != checksum: + raise ValueError(f"Prospective analysis source changed: {relative}") + if not lock.get("data_source_files"): + raise ValueError("Original data source files must be prospectively locked") + for relative, checksum in lock["data_source_files"].items(): + if file_hash(root / relative) != checksum: + raise ValueError(f"Original data source changed: {relative}") + return config, lock + + +def validate_lock(config_path, lock_path, args): + config, lock = validate_frozen_design(config_path, lock_path) + if torch.device(args.device).type != "cuda" or lock.get("device_type") != "cuda": + raise ValueError("Confirmation requires CUDA BF16 execution, never mixed CPU precision") + if args.world not in WORLDS or args.seed not in (0, 1): + raise ValueError("Only the eight reserved worlds and two initializations are allowed") + if args.phase not in PHASES or args.condition not in CONDITIONS: + raise ValueError("Condition outside the prospective matrix") + expected_output = ( + Path(lock["output_root"]) + / args.phase + / "width-256" + / f"world-{args.world}-seed-{args.seed}-{args.condition}" + ).resolve() + if Path(args.output).resolve() != expected_output: + raise ValueError("Output differs from the prospective matrix") + return config, lock + + +def validate_prepared_world(config, config_path, lock_path, world): + if world not in WORLDS: + raise ValueError("Requested world is outside the prospective preparation matrix") + root = Path(__file__).resolve().parents[2] / config["base_world_root"] + receipt = json.loads((root / "preparation-audit.json").read_text()) + lock = json.loads(Path(lock_path).read_text()) + if ( + receipt.get("complete") is not True + or receipt["config_sha256"] != file_hash(config_path) + or receipt["lock_sha256"] != file_hash(lock_path) + or receipt["worlds"] != list(WORLDS) + ): + raise ValueError("Base worlds lack a complete prospectively locked preparation") + if receipt.get("source_files_sha256") != lock["data_source_files"]: + raise ValueError("Prepared world source files differ from the prospective lock") + filenames = ("world.npz", "metadata.json", "audit.json") + expected_files = {f"world-{seed}/{name}" for seed in WORLDS for name in filenames} + if set(receipt.get("files_sha256", {})) != expected_files: + raise ValueError("Prepared world file manifest differs from the prospective matrix") + for name in filenames: + relative = f"world-{world}/{name}" + if receipt["files_sha256"].get(relative) != file_hash(root / relative): + raise ValueError(f"Prepared world changed: {relative}") + metadata = json.loads((root / f"world-{world}/metadata.json").read_text()) + if type(metadata.get("seed")) is not int or metadata["seed"] != world: + raise ValueError("Prepared world metadata seed differs from the requested world") + return root, receipt + + +def case_identity(worker_identity, chain, support, kind, pair): + payload = { + "worker_identity": worker_identity, + "chain": chain, + "support": support, + "kind": kind, + "pair_contract": pair["contract"], + } + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + + +def expected_weight_artifacts(): + names = [f"learning/model-{step}.pt" for step in LEARNING_CHECKPOINTS] + names.append("learning/resume.pt") + names.extend( + f"edits/support-{support}/{chain}-{kind}-mlp/{filename}" + for support in (0, 1) + for chain in CHAINS + for kind in KINDS + for filename in ("model-final.pt", "resume.pt") + ) + return names + + +def scientific_artifacts(output): + for relative in expected_weight_artifacts(): + if not (output / relative).is_file(): + raise ValueError(f"Required confirmation weight artifact is missing: {relative}") + paths = [output / "launch-contract.json", output / "manipulation.npz"] + paths.extend(p for p in (output / "learning").iterdir() if p.is_file()) + paths.extend(p for p in (output / "edits").rglob("*") if p.is_file()) + return { + str(p.relative_to(output)): {"bytes": p.stat().st_size, "sha256": file_hash(p)} + for p in sorted(paths) + } + + +def run(args): + config, _ = validate_lock(args.config, args.lock, args) + output = Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=True) + with (output / ".worker.lock").open("w") as handle: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + base_root, data_receipt = validate_prepared_world( + config, args.config, args.lock, args.world + ) + if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported(): + raise ValueError("A healthy CUDA device with BF16 support is required") + identity = { + "protocol": PROTOCOL, + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "phase": args.phase, + "config_sha256": file_hash(args.config), + "preregistration_lock_sha256": file_hash(args.lock), + "sources": confirmation_sources(), + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": "cuda", + "precision": "BF16 autocast; FP32 model and optimizer", + "prepared_worlds_audit_sha256": file_hash(base_root / "preparation-audit.json"), + "world_files_sha256": { + name: checksum + for name, checksum in data_receipt["files_sha256"].items() + if name.startswith(f"world-{args.world}/") + }, + } + path = output / "launch-contract.json" + if path.exists() and json.loads(path.read_text()) != identity: + raise ValueError("Confirmation worker identity changed") + if not path.exists(): + write_json(path, identity) + if (output / "complete.json").exists(): + return + try: + low = make_cross_world(args.world, source_root=base_root) + high, manipulation, selected, donors = high_exception_world(low) + world = low if args.phase == "low" else high + pairs = { + (chain, support): make_confirmation_edit_pair(low, high, chain, support) + for chain in range(2) + for support in (0, 1) + } + for chain in range(2): + for key in ("groups", "E", "D", "selected_people"): + if np.intersect1d(pairs[chain, 0][key], pairs[chain, 1][key]).size: + raise ValueError(f"The two supports overlap: {key}") + atomic_numpy_save( + output / "manipulation.npz", + selections=selected, + donors=donors, + low_answers=low.answers, + high_answers=high.answers, + high_exceptions=high.exceptions, + ) + study = { + **config, + "confirmation_sources": identity["sources"], + "phase": args.phase, + "manipulation": manipulation, + } + learning_output = output / "learning" + learning_output.mkdir(exist_ok=True) + device = torch.device(args.device) + model, data = learning(args, world, learning_output, study, device) + with np.load(learning_output / "predictions-15360.npz") as saved: + baseline_predictions = { + key: saved[key] for key in ("prediction", "ended", "correct", "value_nll") + } + np.testing.assert_array_equal( + baseline_predictions["correct"], + (baseline_predictions["prediction"] == world.answers) + & baseline_predictions["ended"], + ) + completed = json.loads((learning_output / "learning-complete.json").read_text()) + if completed["model_sha256"] != state_hash(model.state_dict()): + raise ValueError("Learning baseline differs from completed weights") + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update( + {f"direct_{key}": value[ids] for key, value in baseline_predictions.items()} + ) + atomic_numpy_save(learning_output / f"two-step-{name}.npz", **arrays) + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + identity_hash = file_hash(path) + for support in (0, 1): + edit_output = output / "edits" / f"support-{support}" + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain, support], + args.phase, + kind, + chain, + edit_output, + case_identity( + identity_hash, chain, support, kind, pairs[chain, support] + ), + baseline_predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "protocol": PROTOCOL, + "learning_steps": 15360, + "edit_cases": 8, + "edit_steps": 512, + "lock_sha256": file_hash(args.lock), + "artifacts": scientific_artifacts(output), + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--config", required=True) + parser.add_argument("--lock", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py new file mode 100644 index 0000000000000000000000000000000000000000..8535796aba3f18178d69d214c04bc922b0dfa21d --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py @@ -0,0 +1,192 @@ +"""Two prospectively fixed E39 supports; preparation never launches a model. + +Support zero exactly preserves development selection. Support one uses a +separate deterministic stream and excludes the first support's entire groups. +The original E39 audit validates both; all training and target budgets match. +""" + +import numpy as np + +from .bios_data import array_hash, rng_for +from .bios_shortcut_control import audit_high_exception +from .bios_shortcut_matched_edit import ( + KINDS, + PHASES, + U_STRATA, + audit_matched_edit_pair, +) +from .bios_shortcut_matched_edit import ( + make_matched_edit_pair as development_pair, +) + +BUDGET = { + "prevalence_levels": 2, + "worlds": 8, + "initializations": 2, + "organizations": 3, + "models": 96, + "chains": 2, + "update_types": 2, + "supports_per_chain": 2, + "scopes": ["mlp"], + "edit_cases": 768, +} + + +def make_confirmation_edit_pair(low, high, chain, support=0): + """Three roots + 36 actual facts; same IDs and support labels across phases. + + Each selected group contributes six QA-trained and six QA-heldout people + who remain ordinary in the high-prevalence world. Coherent assigns all 12 + to the new default. Exception assigns three default/three alternative in + each split. Histograms match ACROSS all three groups, not within a group. + """ + if chain not in (0, 1) or support not in (0, 1): + raise ValueError("Confirmation fixes two chains and two disjoint supports") + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high worlds must share their identity and query layout") + audit_high_exception(low, high) + first = development_pair(low, high, chain) + if support == 0: + first["contract"].update( + protocol="v2.9-shortcut-behavior-confirmation-E39", + status="prospectively_fixed_confirmation_support", + budget=BUDGET.copy(), + model_checkpoint="width256, independent-world 15360-step low/high learning", + ) + return first + eligible_groups = np.setdiff1d(np.arange(64), first["groups"]) + rng = rng_for(low.seed, 931, chain + 2 * support) + for _ in range(10000): + groups = rng.choice(eligible_groups, 3, replace=False) + if len(np.unique(low.defaults[chain, groups])) == 3: + break + else: + raise RuntimeError("Could not find three groups with distinct default cities") + selected = np.empty((3, 12), dtype=np.int64) + conflict = np.zeros((3, 12), dtype=bool) + conflict[:, :3] = conflict[:, 6:9] = True + targets = { + f"{phase}_{kind}": world.answers.copy() + for phase, world in (("low", low), ("high", high)) + for kind in KINDS + } + new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + for index, group in enumerate(groups): + ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] + if len(eligible) != 8: + raise ValueError("Expected eight still-ordinary people in each QA split") + selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] + actual = low.actual_ids[chain, selected[index]] + derived = low.derived_ids[chain, low.memberships[chain] == group] + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + target[low.root_ids[chain, group]] = new_default[index] + target[derived] = new_default[index] + target[actual] = new_default[index] + if kind == "exception": + target[actual[conflict[index]]] = alternative[index] + edited_people = selected.ravel() + selected_people = np.isin(low.memberships[chain], groups) + original = selected_people & low.exceptions[chain] + newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] + unedited_ordinary = ( + selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) + ) + e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) + d = low.derived_ids[chain, selected_people] + unchanged = np.ones(len(low.answers), dtype=bool) + unchanged[np.concatenate([e, d])] = False + affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] + original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) + newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) + relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(low.answers), -1, dtype=np.int64) + strata[unchanged & original_actual] = 0 + strata[unchanged & newly_actual] = 1 + strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 + strata[unchanged & ~affected_facts & relevant] = 3 + strata[unchanged & ~affected_facts & ~relevant] = 4 + heldout = [] + for stratum in range(5): + ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) + heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) + heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) + heldout = np.array(sorted(heldout), dtype=np.int64) + common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) + common_pool = np.setdiff1d(common_pool, heldout) + if len(common_pool) < 4096: + raise ValueError("Insufficient shared unchanged base facts for R4096") + replay = rng.choice(common_pool, 4096, replace=False) + paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) + pair = { + **targets, + "groups": groups, + "selected_people": selected, + "alternative_assignments": conflict, + "new_default": new_default, + "alternative": alternative, + "E": e, + "D": d, + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, edited_people]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), + "paired_reference_D": paired_reference, + "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "exception_conflict_D": paired_reference.copy(), + "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, original], + "D_newly_exception": low.derived_ids[chain, newly], + "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], + "R": replay, + "U_full": np.flatnonzero(unchanged), + "U_heldout": heldout, + "U_strata": strata, + } + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + actual_for_d = target[low.actual_ids[chain, selected_people]] + pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] + pair["contract"] = { + "protocol": "v2.9-shortcut-behavior-confirmation-E39", + "world": low.seed, + "chain": chain, + "support": support, + "status": "prospectively_fixed_confirmation_support", + "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, + "model_checkpoint": ("width256, independent-world 15360-step low/high learning"), + "histogram_matching_scope": ( + "all three groups combined; also separately for trained/heldout QA" + ), + "coherent_actuals_per_group": "12 new-default (six in each QA split)", + "exception_actuals_per_group": ( + "6 new-default + 6 alternative (three + three in each QA split)" + ), + "paired_reference_semantics": ( + "same 18 people; conflict only in exception, reference only in coherent" + ), + "R_semantics": ( + "4096 identical query IDs with identical original truths " + "and unchanged under all four targets" + ), + "U_semantics": ( + "common query IDs; score each phase against its own truth and old-correct coverage" + ), + "U_strata": U_STRATA.copy(), + "historical_E93_comparable": False, + "low_truth_sha256": array_hash(low.answers), + "high_truth_sha256": array_hash(high.answers), + "array_sha256": {key: array_hash(value) for key, value in pair.items()}, + } + audit_matched_edit_pair(low, high, chain, pair) + return pair diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_control.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_control.py new file mode 100644 index 0000000000000000000000000000000000000000..60ee531b9c2a08e1cf2cfba210a312300b93480d --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_control.py @@ -0,0 +1,242 @@ +"""P3: alter shortcut reliability while preserving marginal answer counts. + +The archived crossover generator and trainer are imported, never rewritten. +The two chains are manipulated simultaneously; QA identities remain unchanged. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import time +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CONDITIONS, audit, documents, make_cross_world, qa_schedule +from .bios_cross_train import learning, source_hashes +from .bios_data import array_hash, rng_for, write_json +from .bios_organization_train import atomic_numpy_save + + +def high_exception_world(old): + """Raise both chains from two to sixteen exceptions per 32-member group.""" + audit(old) + answers, exceptions = old.answers.copy(), old.exceptions.copy() + selections = np.empty((2, 64, 14), dtype=np.int64) + donors = np.empty((2, 14, 64), dtype=np.int64) + for chain in range(2): + rng = rng_for(old.seed, 930, chain) + for group in range(64): + ordinary = np.flatnonzero((old.memberships[chain] == group) & ~old.exceptions[chain]) + people = [] + for query_pool in (old.train_ids[chain], old.heldout_ids[chain]): + eligible = ordinary[np.isin(old.derived_ids[chain, ordinary], query_pool)] + people.extend(rng.permutation(eligible)[:7]) + selections[chain, group] = people + # Every lane contains one ordinary member per group. A city-deranged + # bijection preserves the histogram exactly, separately in each QA split. + for lane in range(14): + for _ in range(10000): + donor = rng.permutation(64) + if np.all(old.defaults[chain, donor] != old.defaults[chain]): + break + else: + raise RuntimeError("Could not construct a city-deranged permutation") + donors[chain, lane] = donor + selected = selections[chain, :, lane] + answers[old.actual_ids[chain, selected]] = old.city_tokens[old.defaults[chain, donor]] + exceptions[chain, selected] = True + world = replace(old, answers=answers, exceptions=exceptions) + record = audit_high_exception(old, world) + record["selection_sha256"] = array_hash(selections) + record["donors_sha256"] = array_hash(donors) + return world, record, selections, donors + + +def audit_high_exception(old, new): + """Fail if the manipulation changes anything outside its declared contract.""" + allowed = old.actual_ids.ravel() + unchanged = np.setdiff1d(np.arange(len(old.answers)), allowed) + np.testing.assert_array_equal(old.answers[unchanged], new.answers[unchanged]) + for field in ( + "prompts", + "lengths", + "relation", + "person", + "memberships", + "defaults", + "membership_ids", + "root_ids", + "actual_ids", + "derived_ids", + "train_ids", + "heldout_ids", + "city_tokens", + ): + np.testing.assert_array_equal(getattr(old, field), getattr(new, field)) + if old.token_labels != new.token_labels: + raise ValueError("Vocabulary changed") + records = [] + for chain in range(2): + ids = old.actual_ids[chain] + np.testing.assert_array_equal(np.sort(old.answers[ids]), np.sort(new.answers[ids])) + truth_exception = ( + new.answers[ids] != new.city_tokens[new.defaults[chain, new.memberships[chain]]] + ) + np.testing.assert_array_equal(truth_exception, new.exceptions[chain]) + if np.any(old.exceptions[chain] & ~new.exceptions[chain]): + raise ValueError("An original exception was removed") + for group in range(64): + members = new.memberships[chain] == group + if int(new.exceptions[chain, members].sum()) != 16: + raise ValueError("Expected sixteen exceptions per group") + for pool in (new.train_ids[chain], new.heldout_ids[chain]): + people = np.flatnonzero(members & np.isin(new.derived_ids[chain], pool)) + if len(people) != 16 or new.exceptions[chain, people].sum() != 8: + raise ValueError("QA split no longer has eight exceptions per group") + for pool in (new.train_ids[chain], new.heldout_ids[chain]): + people = np.flatnonzero(np.isin(new.derived_ids[chain], pool)) + np.testing.assert_array_equal( + np.sort(old.answers[ids[people]]), np.sort(new.answers[ids[people]]) + ) + records.append( + { + "chain": chain, + "old_exceptions": int(old.exceptions[chain].sum()), + "new_exceptions": int(new.exceptions[chain].sum()), + "changed_actual_facts": int((old.answers[ids] != new.answers[ids]).sum()), + "answer_histogram_preserved": True, + "split_histograms_preserved": True, + } + ) + for condition in CONDITIONS: + np.testing.assert_array_equal(documents(old, condition), documents(new, condition)) + np.testing.assert_array_equal(qa_schedule(old, 1280), qa_schedule(new, 1280)) + return { + "passed": True, + "world": old.seed, + "old_truth_sha256": array_hash(old.answers), + "new_truth_sha256": array_hash(new.answers), + "prompts_sha256": array_hash(new.prompts), + "chains": records, + "changed_total": int((old.answers != new.answers).sum()), + "document_identities_and_QA_split_preserved": True, + } + + +def shortcut_sources(): + diagnostic = Path(__file__).with_name("bios_path_diagnostics.py") + return { + **source_hashes(), + Path(__file__).name: hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + diagnostic.name: hashlib.sha256(diagnostic.read_bytes()).hexdigest(), + } + + +def run(args): + out = Path(args.output).resolve() + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + study = json.loads(Path(args.config).read_text()) + if study["width"] != 256 or study["steps"] != 15360: + raise ValueError("P3 freezes width 256 and 15360 steps") + old = make_cross_world(args.world) + world, manipulation, selected, donors = high_exception_world(old) + contract = { + "protocol": "v2.8-p3-shortcut-reliability", + "study": study, + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "sources": shortcut_sources(), + "manipulation": manipulation, + "environment": { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + } + contract_path = out / "launch-contract.json" + if contract_path.exists(): + frozen = json.loads(contract_path.read_text()) + for key in ( + "protocol", + "study", + "world", + "seed", + "condition", + "sources", + "manipulation", + ): + if frozen[key] != contract[key]: + raise ValueError(f"Frozen shortcut contract changed: {key}") + else: + write_json(contract_path, contract) + atomic_numpy_save( + out / "manipulation.npz", + selections=selected, + donors=donors, + old_answers=old.answers, + answers=world.answers, + exceptions=world.exceptions, + train_ids=world.train_ids, + heldout_ids=world.heldout_ids, + ) + if (out / "complete.json").exists(): + return + # Include adapter provenance in the archived trainer's own run identity. + study = {**study, "shortcut_contract": contract["sources"]} + torch.set_num_threads(args.threads) + try: + from .bios_path_diagnostics import autonomous_two_step + + device = torch.device(args.device) + model, _ = learning(args, world, out, study, device) + with np.load(out / f"predictions-{study['steps']}.npz") as saved: + direct = {k: saved[k] for k in ("prediction", "ended", "correct")} + for chain, name in enumerate(("company", "project")): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) + atomic_numpy_save(out / f"two-step-{name}.npz", **arrays) + write_json( + out / "complete.json", + { + "status": "complete", + "phase": "P3-learning-only", + "learning_steps": study["steps"], + "edit_cases": 0, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + { + "type": type(error).__name__, + "message": str(error), + "time": time.time(), + }, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--config", default="configs/bios-shortcut-control-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_edit.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..856a9a8a4fd753c498c4b965d5c30a057bdebffd --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_edit.py @@ -0,0 +1,446 @@ +"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents.""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_shortcut_control import high_exception_world, shortcut_sources +from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +STUDY = { + "protocol": "v2.8-p3-shortcut-matched-E39", + "width": 256, + "parent_step": 15360, + "phases": list(PHASES), + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kinds": list(KINDS), + "scope": "mlp", + "mlp_layers": [3, 4, 5], + "lr": 0.00003, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 96, + "E": 39, + "D": 96, + "R": 4096, + "primary_reference_D": 18, + "primary_reference_D_heldout": 9, + "status": "prepared conditional branch; no best-step selection", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("E39 editing configuration differs from the frozen prepared contract") + + +def editing_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ( + "bios_cross_continue.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit.py", + ) + }, + } + + +def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): + """No phase, organization, initialization, or update-type dependence.""" + rng = rng_for(world_seed, 932, chain) + return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch)) + + +def score_arrays(arrays, truth): + if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): + raise ValueError("Prediction shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("EOS and correctness must be Boolean arrays") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def query_metrics(correct, ids): + n = len(ids) + count = int(correct[ids].sum()) + return {"n": n, "correct": count, "accuracy": count / n if n else None} + + +def retention_metrics(correct, old_correct, ids): + n = len(ids) + known_ids = ids[old_correct[ids]] + broken = int((~correct[known_ids]).sum()) + return { + "n": n, + "known": len(known_ids), + "coverage": len(known_ids) / n if n else None, + "broken": broken, + "damage": broken / len(known_ids) if len(known_ids) else None, + } + + +def edit_metrics(pair, phase, kind, arrays, old_correct): + correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] + if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: + raise ValueError("Old-correct coverage array mismatch") + result = { + key: query_metrics(correct, pair[key]) + for key in ( + "E", + "E_roots", + "E_actual", + "D", + "D_trained", + "D_heldout", + "paired_reference_D", + "paired_reference_D_heldout", + "D_edited_actual", + "D_edited_aligned", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + } + if kind == "exception": + result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) + result["exception_conflict_D_heldout"] = query_metrics( + correct, pair["exception_conflict_D_heldout"] + ) + result["factual_conflict_D"] = query_metrics( + correct, pair[f"{phase}_{kind}_factual_conflict_D"] + ) + for pool in ("U_full", "U_heldout"): + ids = pair[pool] + result[pool] = { + **retention_metrics(correct, old_correct, ids), + "strata": { + str(group): retention_metrics( + correct, old_correct, ids[pair["U_strata"][ids] == group] + ) + for group in range(5) + }, + } + return result + + +def load_parent(parent, phase): + config = json.loads((parent / "config.json").read_text()) + expected_model = dict(vocab_size=4804, width=256, layers=8, heads=4, context=128) + if config["model"] != expected_model or config["study"]["steps"] != 15360: + raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") + if any( + config["study"][key] != value + for key, value in { + "lr": 1e-4, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + }.items() + ): + raise ValueError("E39 parent exposure or learning budget differs") + if ( + config["world"] not in (0, 1) + or config["seed"] not in (0, 1) + or config["condition"] not in CONDITIONS + ): + raise ValueError("Parent is outside the fixed development matrix") + if config["sources"] != source_hashes(): + raise ValueError("Parent frozen trainer sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent numerical software differs") + if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("Low parent is not an original unrestricted-context run") + if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): + raise ValueError("High parent manipulation/source provenance changed") + low = make_cross_world(config["world"]) + high, _, _, _ = high_exception_world(low) + world = low if phase == "low" else high + if config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent truth differs from its declared prevalence phase") + with np.load(parent / "predictions-15360.npz") as saved: + predictions = score_arrays( + {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, + world.answers, + ) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if ( + checkpoint["step"] != 15360 + or checkpoint["config"] != config["model"] + or complete["status"] != "complete" + ): + raise ValueError("Parent learning has not completed the specified checkpoint") + if state_hash(checkpoint["model"]) != complete["model_sha256"]: + raise ValueError("Parent checkpoint differs from completed learning weights") + provenance = { + "directory": str(parent), + "files_sha256": { + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + "model_sha256": complete["model_sha256"], + } + return config, checkpoint, predictions, low, high, world, provenance + + +def run_case( + model, + baseline, + data, + world, + pair, + phase, + kind, + chain, + output, + identity_hash, + parent_predictions, + device, +): + dest = output / f"{CHAINS[chain]}-{kind}-mlp" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + e_choices, r_choices = sampling_stream(world.seed, chain) + saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} + saved_sets.update( + old_correct=parent_predictions["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + atomic_numpy_save(dest / "sets.npz", **saved_sets) + write_json(dest / "data-contract.json", pair["contract"]) + target = pair[f"{phase}_{kind}"] + new_data = tensor_queries(world, device, target) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["R"]), 256): + ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW( + selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("E39 resume identity mismatch") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("E39 resume step mismatch") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, new_data, target) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_predictions[key]) + point = { + "step": step, + "edit_seconds": seconds, + **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "phase": phase, + "chain": CHAINS[chain], + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + print( + json.dumps( + { + "event": "E39_edit_complete", + "case": dest.name, + "E": timeline[-1]["E"]["accuracy"], + "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], + } + ), + flush=True, + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("E39 output must be separate from its immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, checkpoint, predictions, low, high, world, provenance = load_parent( + parent, args.phase + ) + pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] + identity = { + "phase": args.phase, + "world": world.seed, + "seed": config["seed"], + "condition": config["condition"], + "study": STUDY, + "sources": editing_sources(), + "parent": provenance, + "data_contracts": [pair["contract"] for pair in pairs], + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": torch.device(args.device).type, + } + identity_path = output / "config.json" + if identity_path.exists() and json.loads(identity_path.read_text()) != identity: + raise ValueError("E39 editing identity or sources changed") + if not identity_path.exists(): + write_json(identity_path, identity) + if (output / "complete.json").exists(): + return + device = torch.device(args.device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_queries(world, device) + try: + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + observed = evaluate(model, data, world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], predictions[key]) + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain], + args.phase, + kind, + chain, + output, + file_hash(identity_path), + predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": args.phase, + "edit_cases": 4, + "steps": 512, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..52dd3441331f501688eedfe95286f26462de3625 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py @@ -0,0 +1,446 @@ +"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents.""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_shortcut_control import high_exception_world, shortcut_sources +from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +STUDY = { + "protocol": "v2.8-p3-shortcut-matched-E39", + "width": 256, + "parent_step": 15360, + "phases": list(PHASES), + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kinds": list(KINDS), + "scope": "mlp", + "mlp_layers": [3, 4, 5], + "lr": 0.00003, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 96, + "E": 39, + "D": 96, + "R": 4096, + "primary_reference_D": 18, + "primary_reference_D_heldout": 9, + "status": "prepared conditional branch; no best-step selection", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("E39 editing configuration differs from the frozen prepared contract") + + +def editing_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ( + "bios_cross_continue.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit_v2.py", + ) + }, + } + + +def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): + """No phase, organization, initialization, or update-type dependence.""" + rng = rng_for(world_seed, 932, chain) + return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch)) + + +def score_arrays(arrays, truth): + if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): + raise ValueError("Prediction shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("EOS and correctness must be Boolean arrays") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def query_metrics(correct, ids): + n = len(ids) + count = int(correct[ids].sum()) + return {"n": n, "correct": count, "accuracy": count / n if n else None} + + +def retention_metrics(correct, old_correct, ids): + n = len(ids) + known_ids = ids[old_correct[ids]] + broken = int((~correct[known_ids]).sum()) + return { + "n": n, + "known": len(known_ids), + "coverage": len(known_ids) / n if n else None, + "broken": broken, + "damage": broken / len(known_ids) if len(known_ids) else None, + } + + +def edit_metrics(pair, phase, kind, arrays, old_correct): + correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] + if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: + raise ValueError("Old-correct coverage array mismatch") + result = { + key: query_metrics(correct, pair[key]) + for key in ( + "E", + "E_roots", + "E_actual", + "D", + "D_trained", + "D_heldout", + "paired_reference_D", + "paired_reference_D_heldout", + "D_edited_actual", + "D_edited_aligned", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + } + if kind == "exception": + result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) + result["exception_conflict_D_heldout"] = query_metrics( + correct, pair["exception_conflict_D_heldout"] + ) + result["factual_conflict_D"] = query_metrics( + correct, pair[f"{phase}_{kind}_factual_conflict_D"] + ) + for pool in ("U_full", "U_heldout"): + ids = pair[pool] + result[pool] = { + **retention_metrics(correct, old_correct, ids), + "strata": { + str(group): retention_metrics( + correct, old_correct, ids[pair["U_strata"][ids] == group] + ) + for group in range(5) + }, + } + return result + + +def load_parent(parent, phase): + config = json.loads((parent / "config.json").read_text()) + low = make_cross_world(config["world"]) + expected_model = dict(vocab_size=low.vocab_size, width=256, layers=8, heads=4, context=128) + if config["model"] != expected_model or config["study"]["steps"] != 15360: + raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") + if any( + config["study"][key] != value + for key, value in { + "lr": 1e-4, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + }.items() + ): + raise ValueError("E39 parent exposure or learning budget differs") + if ( + config["world"] not in (0, 1) + or config["seed"] not in (0, 1) + or config["condition"] not in CONDITIONS + ): + raise ValueError("Parent is outside the fixed development matrix") + if config["sources"] != source_hashes(): + raise ValueError("Parent frozen trainer sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent numerical software differs") + if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("Low parent is not an original unrestricted-context run") + if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): + raise ValueError("High parent manipulation/source provenance changed") + high, _, _, _ = high_exception_world(low) + world = low if phase == "low" else high + if config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent truth differs from its declared prevalence phase") + with np.load(parent / "predictions-15360.npz") as saved: + predictions = score_arrays( + {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, + world.answers, + ) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if ( + checkpoint["step"] != 15360 + or checkpoint["config"] != config["model"] + or complete["status"] != "complete" + ): + raise ValueError("Parent learning has not completed the specified checkpoint") + if state_hash(checkpoint["model"]) != complete["model_sha256"]: + raise ValueError("Parent checkpoint differs from completed learning weights") + provenance = { + "directory": str(parent), + "files_sha256": { + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + "model_sha256": complete["model_sha256"], + } + return config, checkpoint, predictions, low, high, world, provenance + + +def run_case( + model, + baseline, + data, + world, + pair, + phase, + kind, + chain, + output, + identity_hash, + parent_predictions, + device, +): + dest = output / f"{CHAINS[chain]}-{kind}-mlp" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + e_choices, r_choices = sampling_stream(world.seed, chain) + saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} + saved_sets.update( + old_correct=parent_predictions["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + atomic_numpy_save(dest / "sets.npz", **saved_sets) + write_json(dest / "data-contract.json", pair["contract"]) + target = pair[f"{phase}_{kind}"] + new_data = tensor_queries(world, device, target) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["R"]), 256): + ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW( + selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("E39 resume identity mismatch") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("E39 resume step mismatch") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, new_data, target) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_predictions[key]) + point = { + "step": step, + "edit_seconds": seconds, + **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "phase": phase, + "chain": CHAINS[chain], + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + print( + json.dumps( + { + "event": "E39_edit_complete", + "case": dest.name, + "E": timeline[-1]["E"]["accuracy"], + "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], + } + ), + flush=True, + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("E39 output must be separate from its immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, checkpoint, predictions, low, high, world, provenance = load_parent( + parent, args.phase + ) + pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] + identity = { + "phase": args.phase, + "world": world.seed, + "seed": config["seed"], + "condition": config["condition"], + "study": STUDY, + "sources": editing_sources(), + "parent": provenance, + "data_contracts": [pair["contract"] for pair in pairs], + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": torch.device(args.device).type, + } + identity_path = output / "config.json" + if identity_path.exists() and json.loads(identity_path.read_text()) != identity: + raise ValueError("E39 editing identity or sources changed") + if not identity_path.exists(): + write_json(identity_path, identity) + if (output / "complete.json").exists(): + return + device = torch.device(args.device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_queries(world, device) + try: + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + observed = evaluate(model, data, world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], predictions[key]) + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain], + args.phase, + kind, + chain, + output, + file_hash(identity_path), + predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": args.phase, + "edit_cases": 4, + "steps": 512, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..684e672ca551a48aacb2f4bc81db94092282f4cf --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py @@ -0,0 +1,327 @@ +"""Prepared E39 update sets shared by low/high shortcut-reliability worlds. + +This file generates and audits data only. It neither trains nor edits a model. +The 96 proposed MLP edits are distinct from the archived E93 experiment. +""" + +import numpy as np + +from .bios_data import array_hash, rng_for +from .bios_shortcut_control import audit_high_exception + +KINDS = ("coherent", "exception") +PHASES = ("low", "high") +BUDGET = { + "prevalence_levels": 2, + "worlds": 2, + "initializations": 2, + "organizations": 3, + "models": 24, + "chains": 2, + "update_types": 2, + "supports_per_chain": 1, + "scopes": ["mlp"], + "edit_cases": 96, +} +U_STRATA = { + "0": "original_exception_actual_in_affected_groups", + "1": "newly_exception_actual_in_affected_groups", + "2": "other_unchanged_facts_of_affected_people", + "3": "remaining_same_chain_facts", + "4": "remaining_cross_chain_or_independent_facts", +} + + +def make_matched_edit_pair(low, high, chain, support=0): + """Three roots + 36 actual facts; same IDs and support labels across phases. + + Each selected group contributes six QA-trained and six QA-heldout people + who remain ordinary in the high-prevalence world. Coherent assigns all 12 + to the new default. Exception assigns three default/three alternative in + each split. Histograms match ACROSS all three groups, not within a group. + """ + if chain not in (0, 1) or support != 0: + raise ValueError("The prepared contract fixes two chains and support zero") + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high worlds must share their identity and query layout") + audit_high_exception(low, high) + rng = rng_for(low.seed, 931, chain) + for _ in range(10000): + groups = rng.choice(64, 3, replace=False) + if len(np.unique(low.defaults[chain, groups])) == 3: + break + else: + raise RuntimeError("Could not find three groups with distinct default cities") + selected = np.empty((3, 12), dtype=np.int64) + conflict = np.zeros((3, 12), dtype=bool) + conflict[:, :3] = conflict[:, 6:9] = True + targets = { + f"{phase}_{kind}": world.answers.copy() + for phase, world in (("low", low), ("high", high)) + for kind in KINDS + } + new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + for index, group in enumerate(groups): + ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] + if len(eligible) != 8: + raise ValueError("Expected eight still-ordinary people in each QA split") + selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] + actual = low.actual_ids[chain, selected[index]] + derived = low.derived_ids[chain, low.memberships[chain] == group] + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + target[low.root_ids[chain, group]] = new_default[index] + target[derived] = new_default[index] + target[actual] = new_default[index] + if kind == "exception": + target[actual[conflict[index]]] = alternative[index] + edited_people = selected.ravel() + selected_people = np.isin(low.memberships[chain], groups) + original = selected_people & low.exceptions[chain] + newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] + unedited_ordinary = ( + selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) + ) + e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) + d = low.derived_ids[chain, selected_people] + unchanged = np.ones(len(low.answers), dtype=bool) + unchanged[np.concatenate([e, d])] = False + affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] + original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) + newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) + relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(low.answers), -1, dtype=np.int64) + strata[unchanged & original_actual] = 0 + strata[unchanged & newly_actual] = 1 + strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 + strata[unchanged & ~affected_facts & relevant] = 3 + strata[unchanged & ~affected_facts & ~relevant] = 4 + heldout = [] + for stratum in range(5): + ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) + heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) + heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) + heldout = np.array(sorted(heldout), dtype=np.int64) + common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) + common_pool = np.setdiff1d(common_pool, heldout) + if len(common_pool) < 4096: + raise ValueError("Insufficient shared unchanged base facts for R4096") + replay = rng.choice(common_pool, 4096, replace=False) + paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) + pair = { + **targets, + "groups": groups, + "selected_people": selected, + "alternative_assignments": conflict, + "new_default": new_default, + "alternative": alternative, + "E": e, + "D": d, + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, edited_people]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), + "paired_reference_D": paired_reference, + "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "exception_conflict_D": paired_reference.copy(), + "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, original], + "D_newly_exception": low.derived_ids[chain, newly], + "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], + "R": replay, + "U_full": np.flatnonzero(unchanged), + "U_heldout": heldout, + "U_strata": strata, + } + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + actual_for_d = target[low.actual_ids[chain, selected_people]] + pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] + pair["contract"] = { + "protocol": "v2.8-p3-shortcut-matched-E39-prepared", + "world": low.seed, + "chain": chain, + "support": support, + "status": "data_only_not_executed", + "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, + "model_checkpoint": ( + "width256, original 15360-step learning; not P2 30720-step continuation" + ), + "histogram_matching_scope": ( + "all three groups combined; also separately for trained/heldout QA" + ), + "coherent_actuals_per_group": "12 new-default (six in each QA split)", + "exception_actuals_per_group": ( + "6 new-default + 6 alternative (three + three in each QA split)" + ), + "paired_reference_semantics": ( + "same 18 people; conflict only in exception, reference only in coherent" + ), + "R_semantics": ( + "4096 identical query IDs with identical original truths " + "and unchanged under all four targets" + ), + "U_semantics": ( + "common query IDs; score each phase against its own truth and old-correct coverage" + ), + "U_strata": U_STRATA.copy(), + "historical_E93_comparable": False, + "low_truth_sha256": array_hash(low.answers), + "high_truth_sha256": array_hash(high.answers), + "array_sha256": {key: array_hash(value) for key, value in pair.items()}, + } + audit_matched_edit_pair(low, high, chain, pair) + return pair + + +def audit_matched_edit_pair(low, high, chain, pair): + """Verify ID, target, split, marginal, primary-subset, and replay contracts.""" + audit_high_exception(low, high) + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high world identities differ") + e, d, selected, groups = (pair[key] for key in ("E", "D", "selected_people", "groups")) + if len(e) != 39 or len(np.unique(e)) != 39 or len(d) != 96 or len(np.unique(d)) != 96: + raise ValueError("E39/D96 support changed") + if len(groups) != 3 or len(np.unique(low.defaults[chain, groups])) != 3: + raise ValueError("Expected three groups with distinct original defaults") + if selected.shape != (3, 12) or len(np.unique(selected)) != 36: + raise ValueError("Expected twelve distinct people in each selected group") + if high.exceptions[chain, selected].any(): + raise ValueError("Selected edit people must be ordinary in both worlds") + np.testing.assert_array_equal( + pair["new_default"], low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + ) + np.testing.assert_array_equal( + pair["alternative"], low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + ) + np.testing.assert_array_equal( + d, low.derived_ids[chain, np.isin(low.memberships[chain], groups)] + ) + np.testing.assert_array_equal( + e, np.sort(np.r_[low.root_ids[chain, groups], low.actual_ids[chain, selected.ravel()]]) + ) + conflict = pair["alternative_assignments"] + if conflict.shape != (3, 12) or conflict.dtype != np.bool_: + raise ValueError("Invalid alternative assignment mask") + for index, group in enumerate(groups): + if not np.all(low.memberships[chain, selected[index]] == group): + raise ValueError("Selected person belongs to the wrong group") + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + people = selected[index, split * 6 : (split + 1) * 6] + if not np.isin(low.derived_ids[chain, people], pool).all(): + raise ValueError("Selected QA split changed") + if conflict[index, split * 6 : (split + 1) * 6].sum() != 3: + raise ValueError("Each group/split must have three default and three alternative") + root = low.root_ids[chain, group] + derived = low.derived_ids[chain, low.memberships[chain] == group] + actual = low.actual_ids[chain, selected[index]] + for phase in PHASES: + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + if target[root] != pair["new_default"][index] or not np.all( + target[derived] == target[root] + ): + raise ValueError( + "The three root rotations and their full propagation targets must agree" + ) + expected = np.full(12, target[root], dtype=np.int64) + if kind == "exception": + expected[conflict[index]] = pair["alternative"][index] + np.testing.assert_array_equal(target[actual], expected) + changed = np.union1d(e, d) + for phase, world in (("low", low), ("high", high)): + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + np.testing.assert_array_equal(np.flatnonzero(target != world.answers), changed) + for kind in KINDS: + np.testing.assert_array_equal(pair[f"low_{kind}"][changed], pair[f"high_{kind}"][changed]) + for _split, pool in ( + ("all", low.derived_ids[chain]), + ("trained", low.train_ids[chain]), + ("heldout", low.heldout_ids[chain]), + ): + people = selected.ravel()[np.isin(low.derived_ids[chain, selected.ravel()], pool)] + actual = low.actual_ids[chain, people] + np.testing.assert_array_equal( + np.sort(pair["low_coherent"][actual]), np.sort(pair["low_exception"][actual]) + ) + reference = np.sort(low.derived_ids[chain, selected[conflict]]) + np.testing.assert_array_equal(pair["paired_reference_D"], reference) + np.testing.assert_array_equal(pair["exception_conflict_D"], reference) + heldout_reference = np.intersect1d(reference, low.heldout_ids[chain]) + np.testing.assert_array_equal(pair["exception_conflict_D_heldout"], heldout_reference) + np.testing.assert_array_equal(pair["paired_reference_D_heldout"], heldout_reference) + if len(reference) != 18 or len(heldout_reference) != 9: + raise ValueError("Expected eighteen primary exception conflicts, nine heldout") + partition = [ + pair[key] + for key in ( + "D_edited_actual", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + ] + if [len(ids) for ids in partition] != [36, 6, 42, 12]: + raise ValueError("Incorrect fixed propagation strata") + np.testing.assert_array_equal(np.sort(np.concatenate(partition)), d) + affected = np.isin(low.memberships[chain], groups) + expected_subsets = { + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, selected.ravel()]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, selected.ravel()]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, affected & low.exceptions[chain]], + "D_newly_exception": low.derived_ids[ + chain, affected & high.exceptions[chain] & ~low.exceptions[chain] + ], + } + for key, expected in expected_subsets.items(): + np.testing.assert_array_equal(pair[key], expected) + for phase in PHASES: + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + conflicts = d[target[d] != target[low.actual_ids[chain, affected]]] + np.testing.assert_array_equal(pair[f"{phase}_{kind}_factual_conflict_D"], conflicts) + u = np.setdiff1d(np.arange(len(low.answers)), changed) + np.testing.assert_array_equal(pair["U_full"], u) + np.testing.assert_array_equal(pair["U_strata"] >= 0, np.isin(np.arange(len(low.answers)), u)) + replay = pair["R"] + if len(replay) != 4096 or len(np.unique(replay)) != 4096 or np.any(replay >= low.n_base): + raise ValueError("R must contain 4096 unique base-fact IDs") + if not np.isin(replay, u).all() or np.intersect1d(replay, pair["U_heldout"]).size: + raise ValueError("Replay leaks changed support/propagation or heldout retention") + if not np.isin(pair["U_heldout"], u).all(): + raise ValueError("Heldout retention includes changed targets") + np.testing.assert_array_equal(low.answers[replay], high.answers[replay]) + for phase in PHASES: + for kind in KINDS: + np.testing.assert_array_equal(pair[f"{phase}_{kind}"][replay], low.answers[replay]) + for key, value in pair.items(): + if isinstance(value, np.ndarray) and pair["contract"]["array_sha256"][key] != array_hash( + value + ): + raise ValueError(f"Matched update array provenance changed: {key}") + return { + "passed": True, + "E": 39, + "D": 96, + "exception_conflict_D": 18, + "exception_conflict_D_heldout": 9, + "R": 4096, + "budget_edit_cases": 96, + "histograms_match_across_three_groups_and_within_QA_split": True, + } diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_train.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_train.py new file mode 100644 index 0000000000000000000000000000000000000000..958bf5b4de4feec20d76d07a5d28016fec584d7a --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bios_train.py @@ -0,0 +1,353 @@ +"""Reproducible symbolic development trajectories for bioS-Work-v1. + +Every evaluated answer is greedily generated without a correct-answer prefix. +Two generated tokens is the fixed symbolic grammar budget (one value plus EOS). +""" + +import argparse +import hashlib +import json +import os +import platform +import subprocess +import time +from contextlib import nullcontext +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import ( + EOS, + N_BASE, + N_QUERIES, + RELATIONS, + array_hash, + curriculum, + load_world, + write_json, +) +from .bios_model import CausalLM, ModelConfig, matmul_flops + + +def precision(device): + return ( + torch.autocast(device_type="cuda", dtype=torch.bfloat16) + if device.type == "cuda" + else nullcontext() + ) + + +def tensor_data(world, device, answers=None): + answer = torch.as_tensor(world.answers if answers is None else answers, device=device) + prompts = torch.as_tensor(world.prompts, device=device) + lengths = torch.as_tensor(world.lengths, device=device) + tokens = torch.zeros((N_QUERIES, 6), dtype=torch.long, device=device) + tokens[:, :5] = prompts + rows = torch.arange(N_QUERIES, device=device) + tokens[rows, lengths] = answer + tokens[lengths == 4, 5] = EOS + positions = torch.stack([lengths - 1, lengths], dim=1) + labels = torch.stack([answer, torch.full_like(answer, EOS)], dim=1) + return { + "prompts": prompts, + "lengths": lengths, + "tokens": tokens, + "positions": positions, + "labels": labels, + } + + +@torch.no_grad() +def evaluate(model, data, world, batch_size=512, answers=None): + device = data["tokens"].device + targets = world.answers if answers is None else answers + predictions, ended, nll = [], [], [] + model.eval() + for begin in range(0, N_QUERIES, batch_size): + end = min(begin + batch_size, N_QUERIES) + lengths = data["lengths"][begin:end] + rows = torch.arange(end - begin, device=device) + with precision(device): + logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float() + first = logits.argmax(-1) + continuation = torch.zeros((end - begin, 6), dtype=torch.long, device=device) + continuation[:, :5] = data["prompts"][begin:end] + continuation[rows, lengths] = first + second = model(continuation, lengths[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + labels = torch.as_tensor(targets[begin:end], device=device) + nll.append(F.cross_entropy(logits, labels, reduction="none").cpu().numpy()) + predictions, ended, nll = ( + np.concatenate(predictions), + np.concatenate(ended), + np.concatenate(nll), + ) + correct = (predictions == targets) & ended + strata = { + "employer": world.relation == 0, + "company_default": world.relation == 1, + "actual_nonexception": (world.relation == 2) + & ~world.exceptions[np.maximum(world.person, 0)], + "actual_old_exception": (world.relation == 2) + & world.exceptions[np.maximum(world.person, 0)], + "independent_attributes": np.isin(world.relation, [3, 4, 5, 6]), + } + metrics = { + "base_accuracy": float(correct[:N_BASE].mean()), + "derived_accuracy": float(correct[N_BASE:].mean()), + "value_nll": float(nll[:N_BASE].mean()), + "nontermination_rate": float((~ended).mean()), + "strata": {k: float(correct[v].mean()) for k, v in strata.items()}, + "learning_threshold_passed": bool( + correct[:N_BASE].mean() >= 0.99 and correct[N_BASE:].mean() >= 0.99 + ), + } + return metrics, { + "prediction": predictions, + "ended": ended, + "correct": correct, + "value_nll": nll, + } + + +def code_fingerprint(): + root = Path(__file__).resolve().parents[2] + files = sorted((root / "src" / "llm_memory_editability").glob("*.py")) + return { + "git_revision": subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=root, text=True + ).strip(), + "git_dirty": bool( + subprocess.check_output(["git", "status", "--porcelain"], cwd=root, text=True).strip() + ), + "source_sha256": { + str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in files + }, + } + + +def train(args): + device = torch.device(args.device) + torch.set_num_threads(args.threads) + torch.manual_seed(args.seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + world = load_world(args.world) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + resume = torch.load(out / "resume.pt", weights_only=False) if args.resume else None + if resume is None and (out / "config.json").exists(): + raise ValueError("Output already contains a run; use a fresh output directory") + schedule = curriculum(world, args.order, args.steps) + model = CausalLM(ModelConfig(world.vocab_size)).to(device) + data = tensor_data(world, device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + checkpoints = sorted( + {0, *range(660, 5281, 660), *range(7280, args.steps + 1, 2000), args.steps} + ) + config = { + **vars(args), + "model": model.config_dict(), + "protocol": "v2.3", + "phase": "development", + "world_seed": world.seed, + "parameters": sum(p.numel() for p in model.parameters()), + "torch": torch.__version__, + "python": platform.python_version(), + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast, FP32 weights/loss/Adam moments", + "checkpoints": checkpoints, + "schedule_sha256": array_hash(schedule), + "truth_sha256": array_hash(world.answers), + "flops_method": "executed-shape matmul estimate; elementwise and evaluation excluded", + **code_fingerprint(), + } + timeline, anchors = [], {} + counts = np.zeros(N_QUERIES, dtype=np.int64) + weighted_exposure = np.zeros(8) + train_seconds = 0.0 + losses = [] + steps_since_checkpoint = 0 + first_step = 0 + if resume is None: + write_json(out / "config.json", config) + np.save(out / "schedule.npy", schedule) + else: + # Exact continuation from the last predefined checkpoint's full training state. + original = json.loads((out / "config.json").read_text()) + for key in ("schedule_sha256", "truth_sha256", "seed", "order", "steps", "lr"): + if original[key] != config[key]: + raise ValueError(f"Resume mismatch on {key}") + model.load_state_dict(resume["model"]) + optimizer.load_state_dict(resume["optimizer"]) + torch.set_rng_state(resume["torch_rng"]) + if device.type == "cuda" and resume["cuda_rng"] is not None: + torch.cuda.set_rng_state(resume["cuda_rng"], device) + timeline, anchors = resume["timeline"], resume["anchors"] + counts, weighted_exposure = resume["counts"], resume["weighted_exposure"] + train_seconds = resume["train_seconds"] + first_step = resume["step"] + resumes = ( + json.loads((out / "resumes.json").read_text()) + if (out / "resumes.json").exists() + else [] + ) + resumes.append({"from_step": first_step, **code_fingerprint()}) + write_json(out / "resumes.json", resumes) + if device.type == "cuda": + torch.cuda.reset_peak_memory_stats(device) + for step in range(first_step, args.steps + 1): + if step in checkpoints and not (resume is not None and step == first_step): + start_eval = time.perf_counter() + metrics, arrays = evaluate(model, data, world) + for anchor, known in anchors.items(): + metrics[f"forgetting_since_{anchor}"] = ( + float((~arrays["correct"][known]).mean()) if known.any() else None + ) + if step in (2640, 5280): + anchors[step] = arrays["correct"].copy() + np.savez_compressed(out / f"predictions-{step}.npz", **arrays, exposure=counts) + # CPU state for portability; all predefined checkpoints retained. + torch.save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + record = { + "step": step, + **metrics, + "train_seconds": train_seconds, + "train_matmul_flops_estimate": step * matmul_flops(model.config, 128), + "presentations": int(counts.sum()), + "coverage_base": float((counts[:N_BASE] > 0).mean()), + "coverage_derived": float((counts[N_BASE:] > 0).mean()), + "world_tokens": int((counts * (world.lengths + 2)).sum()), + "input_tokens_including_padding": step * 128 * 6, + "supervised_tokens": step * 128 * 2, + "lr_weighted_exposure_by_relation": dict( + zip((*RELATIONS, "derived"), weighted_exposure.tolist(), strict=True) + ), + "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "eval_and_checkpoint_seconds": time.perf_counter() - start_eval, + "mean_training_loss_since_previous": float(np.mean(losses)) if losses else None, + } + timeline.append(record) + write_json(out / "learning.json", timeline) + print( + json.dumps( + { + "event": "checkpoint", + "step": step, + "base": metrics["base_accuracy"], + "derived": metrics["derived_accuracy"], + "train_seconds": train_seconds, + } + ), + flush=True, + ) + losses = [] + steps_since_checkpoint = 0 + state = { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "timeline": timeline, + "anchors": anchors, + "counts": counts, + "weighted_exposure": weighted_exposure, + "train_seconds": train_seconds, + "step": step, + } + torch.save(state, out / "resume.pt.tmp") + os.replace(out / "resume.pt.tmp", out / "resume.pt") + if step == args.steps: + break + model.train() + lr = args.lr * min((step + 1) / 2000, 1.0) + for group in optimizer.param_groups: + group["lr"] = lr + ids_np = schedule[step] + ids = torch.as_tensor(ids_np, device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(data["tokens"][ids], data["positions"][ids]) + loss = F.cross_entropy( + logits.float().reshape(-1, world.vocab_size), data["labels"][ids].reshape(-1) + ) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(loss) or not torch.isfinite(norm): + write_json( + out / "failure.json", + { + "step": step, + "reason": "nonfinite loss or gradient", + "train_seconds": train_seconds, + }, + ) + raise FloatingPointError("Nonfinite loss or gradient") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - started + losses.append(loss.item()) + np.add.at(counts, ids_np, 1) + weighted_exposure += np.bincount(world.relation[ids_np], minlength=8) * lr + steps_since_checkpoint += 1 + if (step + 1) % 100 == 0: + print( + json.dumps( + { + "event": "progress", + "step": step + 1, + "loss": float(np.mean(losses[-100:])), + "train_seconds": train_seconds, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "step": args.steps, + "status": "complete", + "final": timeline[-1], + "exposure_sha256": array_hash(counts), + }, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--order", choices=["SA", "AS"], required=True) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--steps", type=int, default=13280) + parser.add_argument("--lr", type=float, default=1e-4) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--resume", action="store_true") + train(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bridge_reencoding.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bridge_reencoding.py new file mode 100644 index 0000000000000000000000000000000000000000..1dbbe769879cff4d2b00a6c39164102b50d035e3 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bridge_reencoding.py @@ -0,0 +1,438 @@ +"""Fixed-weight, self-decoded bridge re-encoding in existing small GPTs. + +The intervention uses the original tied readout over the complete vocabulary. +Only the explicitly named oracle condition accesses graph answers at inference. +The wrong_entity control is an alternative to the model's decoded token, not a +guaranteed incorrect answer: its accidental agreement with truth is reported. +""" + +from __future__ import annotations + +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import build_world, model_digest +from .representation_alignment import RepresentationGPT, new_model +from .storage_composition import data_digest, evaluate, file_hash, generate_rows +from .text_pretrain import WORDS, composite_sentence + +CONDITIONS = ("baseline", "self_decode", "wrong_entity", "oracle") + + +def reencode_state(state, embedding, alpha, variant="norm_matched"): + """Interpolate residual and normalized embedding, without renormalizing the sum. + + norm_matched gives the replacement embedding the original state's norm. + paper_unit uses a unit embedding directly. Neither preserves the mixture's + norm in general; alpha=0 returns the original tensor exactly. + """ + if not 0 <= alpha <= 1: + raise ValueError("alpha must be between zero and one") + if variant not in ("norm_matched", "paper_unit"): + raise ValueError("Unknown re-encoding variant") + if alpha == 0: + return state + replacement = F.normalize(embedding, dim=-1) + if variant == "norm_matched": + replacement = state.norm(dim=-1, keepdim=True) * replacement + return (1 - alpha) * state + alpha * replacement + + +def alternative_entity(decoded, bridge_start, bridge_count): + """A non-self bridge-entity choice, independent of the true bridge identity.""" + if bridge_count < 2: + raise ValueError("At least two bridge entity tokens are required") + return bridge_start + torch.remainder(decoded - bridge_start + 1, bridge_count) + + +class ReencodingGPT(RepresentationGPT): + """Original computation with a single intervention at block 0, position 3.""" + + def configure(self, condition, alpha, oracle_table=None, variant="norm_matched"): + if condition not in CONDITIONS: + raise ValueError(f"Unknown condition: {condition}") + if not 0 <= alpha <= 1: + raise ValueError("alpha must be between zero and one") + if variant not in ("norm_matched", "paper_unit"): + raise ValueError("Unknown re-encoding variant") + if condition == "oracle" and oracle_table is None: + raise ValueError("Oracle condition requires an explicit diagnostic truth table") + self.condition, self.alpha, self.variant = condition, float(alpha), variant + # Deliberately outside state_dict: neither weights nor model hashes change. + self.oracle_table = oracle_table if condition == "oracle" else None + + def _choice(self, state, tokens): + decoded = F.linear(self.ln_final(state), self.token.weight).argmax(-1) + selected = decoded + oracle_available = torch.zeros_like(decoded, dtype=torch.bool) + if self.condition == "wrong_entity": + selected = alternative_entity(decoded, self.bridge_start, self.bridge_count) + elif self.condition == "oracle": + oracle = self.oracle_table[tokens[:, 1], tokens[:, 3]] + oracle_available = oracle >= 0 + # Invalid autonomously generated heads have no graph truth. Do not + # fabricate an oracle answer; retain the model's decoded token. + selected = torch.where(oracle_available, oracle, decoded) + return decoded, selected, oracle_available + + def forward(self, tokens, positions=None, repeats=None, return_bridge=False): + if not return_bridge and (self.condition == "baseline" or self.alpha == 0): + return super().forward(tokens, positions=positions, repeats=repeats) + if tokens.shape[1] < 4: + raise ValueError("The intervention requires the causal first-relation prefix") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + info = None + for index, block in enumerate(self.iter_blocks(repeats)): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + if index == 0: + state = x[:, 3] + decoded, selected, oracle_available = self._choice(state, tokens) + replacement = ( + state + if self.condition == "baseline" + else reencode_state(state, self.token(selected), self.alpha, self.variant) + ) + if self.condition != "baseline" and self.alpha: + x = x.clone() + x[:, 3] = replacement + info = { + "state": state, + "replacement": replacement, + "decoded": decoded, + "selected": selected, + "oracle_available": oracle_available, + } + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, self.token.weight) + return (logits, info) if return_bridge else logits + + +def _device_settings(device): + device = torch.device(device) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + return device + + +def _load(spec, device): + parent = Path(spec["parent_dir"]).resolve() + checkpoint = parent / "model.pt" + payload = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = new_model(payload["spec"], device) + model.load_state_dict(payload["model"]) + model.__class__ = ReencodingGPT + model.bridge_start = len(WORDS) + payload["spec"]["heads_n"] + model.bridge_count = payload["spec"]["bridges_n"] + model.configure("baseline", 0) + model.eval().requires_grad_(False) + world = dict(np.load(parent / "world.npz")) + rebuilt = build_world(payload["spec"]) + if data_digest(world) != data_digest(rebuilt): + raise AssertionError("Saved world differs from the parent specification") + oracle = torch.full( + (model.config.vocab_size, model.config.vocab_size), -1, device=device, dtype=torch.long + ) + for h, r, target in np.concatenate((world["common_atomic"], world["extra_atomic"])): + oracle[h, r] = int(target) + return model, world, oracle, payload["spec"], checkpoint + + +@torch.no_grad() +def _diagnostics(model, rows, device, batch_size): + prompts = np.asarray([composite_sentence(row)[:7] for row in rows]) + collected = {} + model.eval() + for start in range(0, len(rows), batch_size): + tokens = torch.as_tensor(prompts[start : start + batch_size], device=device) + _, info = model(tokens, return_bridge=True) + values = { + "decoded_bridge": info["decoded"], + "selected_bridge": info["selected"], + "oracle_available": info["oracle_available"], + "state_norm": info["state"].norm(dim=-1), + "replacement_norm": info["replacement"].norm(dim=-1), + } + for key, value in values.items(): + collected.setdefault(key, []).append(value.cpu().numpy()) + result = {key: np.concatenate(value) for key, value in collected.items()} + result["decoded_bridge_correct"] = result["decoded_bridge"] == rows[:, 2] + result["selected_bridge_correct"] = result["selected_bridge"] == rows[:, 2] + result["decoded_is_entity"] = result["decoded_bridge"] >= len(WORDS) + return result + + +def _subset_metric(correct, mask): + return { + "n": int(mask.sum()), + "coverage": float(mask.mean()), + "accuracy": float(correct[mask].mean()) if mask.any() else None, + } + + +@torch.no_grad() +def _evaluate_condition(model, world, device, batch_size): + # Reuse the established complete answer/period/EOS scorer unchanged. Its + # canonical batch is 512; diagnostics use the same shapes for exact decoding. + if batch_size != 512: + raise ValueError("Use batch_size=512 to preserve established evaluation arithmetic") + metrics, predictions = evaluate(model, world, "low", device) + model.eval() + for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): + generated = predictions[name + "_generated"] + metrics[name]["period_accuracy"] = float((generated[:, 1] == 5).mean()) + metrics[name]["eos_accuracy"] = float((generated[:, 2] == 1).mean()) + metrics[name]["format_accuracy"] = float( + ((generated[:, 1] == 5) & (generated[:, 2] == 1)).mean() + ) + for name in ("familiar_test", "strict_test"): + rows = world[name] + info = _diagnostics(model, rows, device, batch_size) + predictions.update({name + "_" + key: value for key, value in info.items()}) + for key in ("decoded_bridge_correct", "selected_bridge_correct", "decoded_is_entity"): + metrics[name][key + "_coverage"] = float(info[key].mean()) + if model.condition == "wrong_entity": + metrics[name]["alternative_accidental_gold_match"] = float( + info["selected_bridge_correct"].mean() + ) + correct = predictions[name + "_correct"] + metrics[name]["self_bridge_correct_subset"] = _subset_metric( + correct, info["decoded_bridge_correct"] + ) + first = rows[:, [0, 1, 2]] + second = rows[:, [2, 3, 4]] + for role, atoms in (("first", first), ("second", second)): + _, raw = generate_rows(model, atoms, device, batch_size=batch_size) + predictions.update({f"{name}_{role}_{key}": value for key, value in raw.items()}) + autonomous_second = second.copy() + autonomous_second[:, 0] = predictions[name + "_first_generated"][:, 0] + _, raw = generate_rows(model, autonomous_second, device, batch_size=batch_size) + predictions.update({f"{name}_autonomous_{key}": value for key, value in raw.items()}) + return metrics, predictions + + +def cases(spec): + """One baseline and the frozen alpha/variant/condition matrix.""" + conditions = list(spec.get("conditions", CONDITIONS)) + if len(conditions) != len(set(conditions)) or any(c not in CONDITIONS for c in conditions): + raise ValueError("Conditions must be distinct known names") + alphas = spec.get("alphas", [spec.get("alpha", 0)]) + variants = spec.get("variants", ["norm_matched"]) + if len(alphas) != len(set(alphas)) or not alphas or any(not 0 <= a <= 1 for a in alphas): + raise ValueError("alphas must contain distinct values in [0,1]") + if len(variants) != len(set(variants)) or not variants: + raise ValueError("variants must be distinct and nonempty") + if any(v not in ("norm_matched", "paper_unit") for v in variants): + raise ValueError("Unknown re-encoding variant") + matrix = {"baseline": {"condition": "baseline", "alpha": 0, "variant": "norm_matched"}} + for variant in variants: + for alpha in alphas: + for condition in conditions: + if condition == "baseline": + continue + name = f"{variant}-a{float(alpha):g}-{condition}" + matrix[name] = {"condition": condition, "alpha": float(alpha), "variant": variant} + return matrix + + +def _evaluate_all(model, world, oracle, spec, callback=None): + matrix = cases(spec) + metrics, arrays = {}, {} + for name, case in matrix.items(): + model.configure( + case["condition"], + case["alpha"], + oracle if case["condition"] == "oracle" else None, + case["variant"], + ) + metrics[name], predictions = _evaluate_condition( + model, world, next(model.parameters()).device, spec.get("batch_size", 512) + ) + arrays.update({name + "__" + key: value for key, value in predictions.items()}) + if callback is not None: + callback(name, case, metrics[name], predictions) + for name in ("familiar_test", "strict_test"): + baseline = arrays[f"baseline__{name}_coverage"] + # This is the fixed pre-intervention prerequisite pool for every case. + # In particular, the destructive alternative-entity control cannot + # determine which chains enter the main conditional comparison. + arrays[f"common__{name}_atomic_correct"] = baseline + for condition in matrix: + correct = arrays[f"{condition}__{name}_correct"] + arrays[f"{condition}__{name}_baseline_common_atoms"] = baseline + metrics[condition][name]["fixed_baseline_atoms_subset"] = _subset_metric( + correct, baseline + ) + self_ok = arrays[f"{condition}__{name}_decoded_bridge_correct"] + joint = baseline & self_ok + arrays[f"{condition}__{name}_common_atoms_and_self_bridge"] = joint + metrics[condition][name]["common_atoms_and_self_bridge_subset"] = _subset_metric( + correct, joint + ) + model.configure("baseline", 0) + return metrics, arrays + + +def run(spec, out, device="cuda:2"): + """Evaluate one existing checkpoint; never train or overwrite an attempt.""" + out = Path(out) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + out.mkdir(parents=True, exist_ok=True) + device = _device_settings(device) + started = time.perf_counter() + model, world, oracle, parent_spec, checkpoint = _load(spec, device) + digest = model_digest(model) + source = { + str(Path(__file__).resolve()): file_hash(__file__), + "parent_checkpoint": file_hash(checkpoint), + } + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "source": source, + "world_sha256": data_digest(world), + "model_sha256": digest, + "pid": os.getpid(), + "device": str(device), + "started_utc": utc(), + "new_training_updates": 0, + "optimizer_updates": 0, + "cases": cases(spec), + "formula_norm_matched": "(1-alpha)*h + alpha*||h||*normalize(E_decoded)", + "formula_paper_unit": "(1-alpha)*h + alpha*normalize(E_decoded)", + "decoder": "original ln_final and tied output, argmax over the full vocabulary", + "wrong_entity_scope": "non-self bridge entity, independent of gold; may equal true bridge", + "bridge_token_start": model.bridge_start, + "bridge_token_count": model.bridge_count, + "main_prerequisite_subset": "both necessary atoms correct under the fixed baseline", + "alpha_zero_exact_bypass": True, + "allow_tf32": True, + } + write_json(out / "run.json", manifest) + np.savez_compressed(out / "world.npz", **world) + history = [] + + def record(name, case, metrics, predictions): + history.append( + { + "step": len(history) + 1, + "case": name, + **case, + "metrics": metrics, + "optimizer_updates": 0, + "wall_seconds": time.perf_counter() - started, + "created_utc": utc(), + } + ) + # Each condition is durable before the next one starts. + np.savez_compressed(out / f"predictions-{name}.npz", **predictions) + write_json(out / "learning.json", history) + write_json( + out / "status.json", + { + "state": "running", + "step": len(history), + "budget": len(manifest["cases"]), + "optimizer_updates": 0, + }, + ) + + metrics, predictions = _evaluate_all(model, world, oracle, spec, record) + assert model_digest(model) == digest, "Evaluation changed model parameters" + # Final common-prerequisite subsets are known only after the full matrix. + write_json(out / "learning.json", history) + # At zero weight all conditions must recover complete baseline generation. + for key, value in predictions.items(): + if key.endswith(("_generated", "_answer_nll")): + case, suffix = key.split("__", 1) + if manifest["cases"][case]["alpha"] == 0: + np.testing.assert_array_equal(value, predictions["baseline__" + suffix]) + np.savez_compressed(out / "predictions.npz", **predictions) + write_json(out / "metrics.json", metrics) + result = { + "state": "evaluation-complete-awaiting-independent-audit", + "finished_utc": utc(), + "wall_seconds": time.perf_counter() - started, + "model_sha256": digest, + "new_training_updates": 0, + "optimizer_updates": 0, + "conditions": list(metrics), + "prediction_arrays": len(predictions), + "step": len(history), + } + write_json(out / "evaluation-complete.json", result) + write_json(out / "status.json", {**result, "step": len(history)}) + return result + + +def audit(out, device="cuda:2"): + """Reload weights and independently recompute every saved prediction array.""" + out = Path(out) + device = _device_settings(device) + manifest = json.loads((out / "run.json").read_text()) + model, world, oracle, _, checkpoint = _load(manifest["spec"], device) + assert file_hash(checkpoint) == manifest["source"]["parent_checkpoint"] + assert model_digest(model) == manifest["model_sha256"] + assert data_digest(world) == manifest["world_sha256"] + metrics, actual = _evaluate_all(model, world, oracle, manifest["spec"]) + saved = dict(np.load(out / "predictions.npz")) + assert set(saved) == set(actual), "Prediction array set changed" + max_error = 0.0 + for key, value in actual.items(): + if value.dtype.kind == "f": + max_error = max(max_error, float(np.max(np.abs(value - saved[key])))) + np.testing.assert_allclose(value, saved[key], atol=1e-5, rtol=1e-5) + else: + np.testing.assert_array_equal(value, saved[key]) + # Recount complete-answer accuracy independently of the established scorer. + for condition, groups in metrics.items(): + for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): + pred = actual[f"{condition}__{name}_generated"] + correct = (pred[:, 0] == world[name][:, -1]) & (pred[:, 1] == 5) & (pred[:, 2] == 1) + np.testing.assert_array_equal(correct, actual[f"{condition}__{name}_correct"]) + assert float(correct.mean()) == groups[name]["accuracy"] + assert model_digest(model) == manifest["model_sha256"] + result = { + "passed": True, + "independently_reloaded": True, + "raw_predictions_recounted": True, + "prediction_arrays": len(actual), + "max_float_error": max_error, + "audit_pid": os.getpid(), + "independent_process": os.getpid() != manifest["pid"], + "finished_utc": utc(), + "metrics": metrics, + } + write_json(out / "audit.json", result) + complete = json.loads((out / "evaluation-complete.json").read_text()) + complete.update(state="complete", independently_reloaded=True, audit_finished_utc=utc()) + write_json(out / "complete.json", complete) + write_json(out / "status.json", {**complete, "step": len(metrics), "optimizer_updates": 0}) + return result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bridge_workspace.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bridge_workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3ee68821631607b4922cfce3654cd2784d82ba --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/bridge_workspace.py @@ -0,0 +1,1112 @@ +"""Causal entity-coordinate interventions using an averaged prefix Jacobian. + +This is a restricted adaptation of Anthropic's Jacobian lens: calibration and +donors contain only the first fact's query prefix. No relation suffix or answer +gradient is used to construct a direction. Execution layers count shared block +occurrences separately. All model parameters remain frozen. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import time +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import file_hash + +SWAPS = ("swap", "swap_x2", "random_swap", "full_prefix", "swap_back") +ERASURES = ( + "erase_state", + "erase_mlp", + "erase_attention", + "random_state", + "random_mlp", + "random_attention", + "restore_mlp", + "fixed_entity_mlp", + "fixed_entity_random_mlp", +) + + +class ModelView: + """Expose native attention/MLP increments without replacing trained modules.""" + + def __init__(self, model): + if model.training: + raise ValueError("Interventions require eval mode") + self.model = model + self.large = hasattr(model, "transformer") + if self.large: + t = model.transformer + self.embedding, self.position, self.norm = t.wte, t.wpe, t.ln_f + self.blocks = list(t.h) * model.repeats + self.heads = model.config.n_head + else: + self.embedding, self.position, self.norm = model.token, model.position, model.ln_final + self.blocks = list(model.iter_blocks()) + self.heads = model.config.heads + self.width = self.embedding.weight.shape[1] + self.device = self.embedding.weight.device + + def embed(self, tokens): + return self.embedding(tokens) + self.position( + torch.arange(tokens.shape[1], device=self.device) + ) + + def parts(self, x, block, *, math_attention=False): + if self.large: + z = block.ln_1(x) + q, k, v = block.attn.c_attn(z).split(self.width, dim=-1) + project, ln2 = block.attn.c_proj, block.ln_2 + else: + z = block.ln1(x) + q, k, v = block.attention.qkv(z).chunk(3, dim=-1) + project, ln2 = block.attention.proj, block.ln2 + shape = (len(x), x.shape[1], self.heads, self.width // self.heads) + q, k, v = (a.reshape(shape).transpose(1, 2) for a in (q, k, v)) + if math_attention: + # The explicit FP32 expression permits batched VJPs on torch 2.6. + scores = q @ k.transpose(-1, -2) / (self.width // self.heads) ** 0.5 + mask = torch.ones(x.shape[1], x.shape[1], device=self.device, dtype=torch.bool).tril() + y = scores.masked_fill(~mask, -torch.inf).softmax(-1) @ v + else: + y = F.scaled_dot_product_attention(q, k, v, is_causal=True) + attention = project(y.transpose(1, 2).reshape(len(x), x.shape[1], self.width)) + after_attention = x + attention + mlp = block.mlp(ln2(after_attention)) + return after_attention + mlp, attention, mlp + + def hidden( + self, tokens, *, layer=None, sender=None, delta=None, capture=False, math_attention=False + ): + x, states, attentions, mlps = self.embed(tokens), [], [], [] + for index, block in enumerate(self.blocks): + x, attention, mlp = self.parts(x, block, math_attention=math_attention) + if capture: + states.append(x[:, sender].detach()) + attentions.append(attention[:, sender].detach()) + mlps.append(mlp[:, sender].detach()) + if index == layer: + if sender is None or delta is None or delta.shape != x[:, sender].shape: + raise ValueError("A patch requires one delta per example at a fixed sender") + mask = F.one_hot(torch.tensor(sender, device=self.device), x.shape[1]).to(x.dtype) + x = x + mask[None, :, None] * delta[:, None, :] + if capture: + return x, tuple(torch.stack(a) for a in (states, attentions, mlps)) + return x + + def logits(self, tokens, **patch): + return F.linear(self.norm(self.hidden(tokens, **patch)[:, -1]), self.embedding.weight) + + +def average_prefix_jacobian(view, prefixes, sender, *, chunk=32): + """E[d h_final,sender / d h_layer,sender], with labels absent from the graph. + + A shared shift applied to all independent calibration prompts differentiates + their mean output, exactly averaging their Jacobians. Parameters need no + gradients. The endpoint is the residual before the final LayerNorm. + """ + if any(p.requires_grad for p in view.model.parameters()): + raise ValueError("Freeze model parameters before constructing the lens") + with torch.no_grad(): + x, boundaries = view.embed(prefixes), [] + for block in view.blocks: + x, _, _ = view.parts(x, block, math_attention=True) + boundaries.append(x.detach()) + jacobians = [] + identity = torch.eye(view.width, device=view.device) + for layer, boundary in enumerate(boundaries): + shift = torch.zeros(view.width, device=view.device, requires_grad=True) + mask = F.one_hot(torch.tensor(sender, device=view.device), prefixes.shape[1]).float() + x = boundary + mask[None, :, None] * shift[None, None, :] + for block in view.blocks[layer + 1 :]: + x, _, _ = view.parts(x, block, math_attention=True) + endpoint = x[:, sender].mean(0) + rows = [] + for start in range(0, view.width, chunk): + rows.append( + torch.autograd.grad( + endpoint, + shift, + grad_outputs=identity[start : start + chunk], + is_grads_batched=True, + retain_graph=start + chunk < view.width, + )[0].detach() + ) + jacobians.append(torch.cat(rows)) + return torch.stack(jacobians) + + +def swap_coordinates(state, basis): + """Swap two coefficients in a nonorthogonal frame, preserving its complement.""" + if basis.shape != (*state.shape, 2): + raise ValueError("Expected [example, width, two semantic axes]") + coefficients = (torch.linalg.pinv(basis.double()) @ state.double()[..., None]).squeeze(-1) + difference = coefficients.flip(-1) - coefficients + return state + (basis.double() @ difference[..., None]).squeeze(-1).to(state.dtype) + + +def projection(state, direction): + direction = F.normalize(direction, dim=-1) + return (state * direction).sum(-1, keepdim=True) * direction + + +def match_norm(delta, reference): + norm = delta.norm(dim=-1, keepdim=True) + if bool(((norm < 1e-12) & (reference.norm(dim=-1, keepdim=True) > 1e-6)).any()): + raise ValueError("Degenerate random control") + return delta * reference.norm(dim=-1, keepdim=True) / norm.clamp_min(1e-12) + + +def control_observation(changed, baseline): + """Record numerical control outcomes without silently dropping sensitive cases.""" + mask = np.any(changed != baseline, axis=1) + return { + "n_queries": len(baseline), + "generated_rows_changed": int(mask.sum()), + "answer_rows_changed": int((changed[:, 0] != baseline[:, 0]).sum()), + "changed_query_indices": np.flatnonzero(mask).tolist(), + "changed_fraction": float(mask.mean()), + "exact": bool(not mask.any()), + } + + +def _rank(seed, *values): + return hashlib.sha256(json.dumps([seed, *map(int, values)]).encode()).digest() + + +def select_pairs(atoms, first_families, seed, per_family, *, ood=None): + """Choose prefixes/donors and all shared continuations using graph truth only. + + Donors use the same r1 and first-fact family. Every pair has at least two + distinct shared r2 with different original/counterfactual tails. A pair is + selected before scoring; its exact same prefix intervention serves every r2. + """ + atoms = np.asarray(atoms, dtype=np.int64) + outgoing, relation = defaultdict(dict), defaultdict(list) + for index, (head, r, tail) in enumerate(atoms): + if int(r) in outgoing[int(head)]: + raise ValueError("Ambiguous atomic truth") + outgoing[int(head)][int(r)] = (int(tail), index) + relation[int(r)].append(index) + groups, queries, coverage = [], [], {} + for name, indices in first_families.items(): + allowed = set(map(int, indices)) + eligible = [] + for first in sorted(allowed): + head, r1, bridge = map(int, atoms[first]) + candidates = [] + for donor in relation[r1]: + dh, _, db = map(int, atoms[donor]) + if donor not in allowed or dh == head or db == bridge: + continue + common = sorted(set(outgoing[bridge]) & set(outgoing[db])) + common = [ + r + for r in common + if outgoing[bridge][r][0] != outgoing[db][r][0] + and not {outgoing[bridge][r][0], outgoing[db][r][0]} & {head, dh, bridge, db} + ] + if len(common) >= 2: + candidates.append((donor, common)) + if candidates: + donor, common = min(candidates, key=lambda v: _rank(seed, first, v[0])) + eligible.append((first, donor, common)) + eligible.sort(key=lambda v: _rank(seed, v[0])) + coverage[name] = {"candidate_first_facts": len(allowed), "eligible": len(eligible)} + for first, donor, common in eligible[:per_family]: + head, r1, bridge = map(int, atoms[first]) + dh, _, db = map(int, atoms[donor]) + group = len(groups) + groups.append([head, r1, bridge, dh, db, first, donor]) + for r2 in common: + tail, second = outgoing[bridge][r2] + ct, cf_second = outgoing[db][r2] + kind = ( + name + if ood is None + else ("ood" if ood[first] else "id") + ("_ood" if ood[second] else "_id") + ) + queries.append((group, r2, tail, ct, second, cf_second, kind)) + coverage[name]["selected"] = min(len(eligible), per_family) + if not groups: + raise ValueError("No graph-eligible cross-relation pairs; do not reroll") + return { + "groups": np.asarray(groups, dtype=np.int64), + "queries": np.asarray([r[:6] for r in queries], dtype=np.int64), + "strata": np.asarray([r[6] for r in queries]), + "counterfactual_strata": np.asarray( + [ + r[6] + if ood is None + else ("ood" if ood[groups[r[0]][6]] else "id") + ("_ood" if ood[r[5]] else "_id") + for r in queries + ] + ), + "coverage": coverage, + } + + +def prefixes(facts, large, metadata): + facts = np.asarray(facts) + if large: + return np.column_stack( + (facts[:, 0] + metadata["entity_offset"], facts[:, 1] + metadata["relation_offset"]) + ) + return np.column_stack( + (np.full(len(facts), 2), facts[:, 0], np.full(len(facts), 3), facts[:, 1]) + ) + + +def prompts(rows, large, metadata): + if large: + from .grokking_reproduction import encode_rows + + return encode_rows(rows, metadata)[0][:, : rows.shape[1] - 1] + from .text_pretrain import atomic_sentence, composite_sentence + + render = atomic_sentence if rows.shape[1] == 3 else composite_sentence + length = 5 if rows.shape[1] == 3 else 7 + return np.asarray([render(row)[:length] for row in rows]) + + +def query_training_masks(world, payload, groups, queries, large): + """Count composition exposure without using scores or answer correctness.""" + if large: + support = round(payload["spec"]["phi"] * (~world["ood"]).sum()) + trained = world["chains"][world["train_order"][:support]][:, :3] + else: + trained = world["train_composite"][:, [0, 1, 3]] + trained = set(map(tuple, trained)) + recipient = np.asarray([(groups[g, 0], groups[g, 1], r2) in trained for g, r2, *_ in queries]) + donor = np.asarray([(groups[g, 3], groups[g, 1], r2) in trained for g, r2, *_ in queries]) + return { + "recipient_query_trained": recipient, + "counterfactual_query_trained": donor, + "both_queries_untrained": ~recipient & ~donor, + } + + +def load_task(spec, device): + payload = torch.load(spec["checkpoint"], map_location="cpu", weights_only=False) + if "checkpoint_step" in spec: + saved_step = payload.get("step", payload["spec"].get("steps")) + assert saved_step == spec["checkpoint_step"], "Wrong checkpoint training step" + if spec["family"] == "reproduction": + from .grokking_reproduction import construct + + data = Path(spec["data"]) + metadata = json.loads((data / "complete.json").read_text()) + model = construct(payload["spec"], metadata, device) + world = dict(np.load(data / "world.npz")) + panels = dict(np.load(data / "panels.npz")) + atoms = world["atoms"].astype(np.int64) + families = {"id": np.flatnonzero(~world["ood"]), "ood": np.flatnonzero(world["ood"])} + ood = world["ood"] + entities = np.arange( + metadata["entity_offset"], metadata["entity_offset"] + metadata["entities"] + ) + else: + from .representation_alignment import new_model + + model = new_model(payload["spec"], device) + world = dict(np.load(Path(spec["checkpoint"]).parent / "world.npz")) + metadata = {"entity_offset": 0} + atoms = np.concatenate((world["common_atomic"], world["anchor_atomic"])) + families = {} + for name in ("familiar_test", "strict_test"): + firsts = set(map(tuple, world[name][:, :3])) + families[name] = np.asarray([i for i, a in enumerate(atoms) if tuple(a) in firsts]) + ood = None + entities = np.arange(21, model.config.vocab_size) + panels = {k: world[k] for k in ("familiar_test", "strict_test")} + model.load_state_dict(payload["model"]) + model.eval().requires_grad_(False) + return ModelView(model), payload, metadata, world, atoms, families, ood, entities, panels + + +@torch.no_grad() +def trace_in_batches(view, tokens, sender, batch_size, amp): + collected = [] + for start in range(0, len(tokens), batch_size): + batch = torch.as_tensor(tokens[start : start + batch_size], device=view.device) + with torch.autocast("cuda", dtype=torch.bfloat16, enabled=amp): + _, trace = view.hidden(batch, sender=sender, capture=True) + collected.append(tuple(a.float() for a in trace)) + return tuple(torch.cat([a[j] for a in collected], dim=1) for j in range(3)) + + +@torch.no_grad() +def generate( + view, + tokens, + targets, + counterfactual, + metadata, + batch_size, + *, + layer=None, + sender=None, + delta=None, +): + """Greedy generation with feedback; scoring retains both target probabilities.""" + offset = metadata["entity_offset"] + targets, counterfactual = targets + offset, counterfactual + offset + generated, original_logp, cf_logp, top_ids, top_scores = [], [], [], [], [] + for start in range(0, len(tokens), batch_size): + x = torch.as_tensor(tokens[start : start + batch_size], device=view.device) + patch = ( + {} + if layer is None + else {"layer": layer, "sender": sender, "delta": delta[start : start + batch_size]} + ) + draws = [] + for index in range(2 if view.large else 3): + with torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): + logits = view.logits(x, **patch).float() + if index == 0: + logs = logits.log_softmax(-1) + arange = torch.arange(len(x), device=view.device) + original_logp.append( + logs[ + arange, + torch.as_tensor(targets[start : start + batch_size], device=view.device), + ] + .cpu() + .numpy() + ) + cf_logp.append( + logs[ + arange, + torch.as_tensor( + counterfactual[start : start + batch_size], device=view.device + ), + ] + .cpu() + .numpy() + ) + scores, ids = logs.topk(min(10, logs.shape[-1]), dim=-1) + top_ids.append(ids.cpu().numpy()) + top_scores.append(scores.cpu().numpy()) + answer = logits.argmax(-1) + draws.append(answer.cpu().numpy()) + x = torch.cat((x, answer[:, None]), dim=1) + generated.append(np.stack(draws, axis=1)) + return { + "generated": np.concatenate(generated), + "original_logp": np.concatenate(original_logp), + "cf_logp": np.concatenate(cf_logp), + "top_ids": np.concatenate(top_ids), + "top_logp": np.concatenate(top_scores), + } + + +def summarize(result, targets, counterfactual, metadata, strata, groups=None): + generated = result["generated"] + original = generated[:, 0] == targets + metadata["entity_offset"] + cf = generated[:, 0] == counterfactual + metadata["entity_offset"] + format_ok = ( + generated[:, 1] == metadata["end_marker"] + if "end_marker" in metadata + else (generated[:, 1] == 5) & (generated[:, 2] == 1) + ) + output = {} + for name in ("all", *sorted(set(strata))): + mask = np.ones(len(strata), dtype=bool) if name == "all" else strata == name + row = { + "n_queries": int(mask.sum()), + "answer_accuracy": float(original[mask].mean()), + "accuracy": float((original & format_ok)[mask].mean()), + "cf_answer_accuracy": float(cf[mask].mean()), + "cf_accuracy": float((cf & format_ok)[mask].mean()), + "format_accuracy": float(format_ok[mask].mean()), + "answer_nll": float(-result["original_logp"][mask].mean()), + "cf_nll": float(-result["cf_logp"][mask].mean()), + } + if groups is not None: + unique = np.unique(groups[mask]) + row["n_first_facts"] = len(unique) + row["all_relations_cf_accuracy"] = float( + np.mean([cf[mask & (groups == g)].all() for g in unique]) + ) + row["mean_first_fact_cf_accuracy"] = float( + np.mean([cf[mask & (groups == g)].mean() for g in unique]) + ) + output[name] = row + return output + + +def run(spec, settings, out, gpu): + """Run one checkpoint with all execution layers, including failed interventions.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device(f"cuda:{gpu}") + began = time.perf_counter() + view, payload, metadata, world, atoms, families, ood, entities, panels = load_task(spec, device) + digest_before = model_digest(view.model) + write_json( + out / "run.json", + { + "spec": { + **spec, + "settings": settings, + "checkpoint_step": payload.get("step", payload["spec"].get("steps")), + }, + "checkpoint_sha256": file_hash(spec["checkpoint"]), + "initial_model_sha256": digest_before, + "world_sha256": file_hash(Path(spec["data"]) / "world.npz") + if view.large + else file_hash(Path(spec["checkpoint"]).parent / "world.npz"), + "job_type": "causal-intervention", + "pid": os.getpid(), + "gpu": gpu, + "gpu_name": torch.cuda.get_device_name(gpu), + "dtype": "BF16 native / FP32 Jacobian" if view.large else "FP32", + "parameters": sum(p.numel() for p in view.model.parameters()), + "vocab_size": len(view.embedding.weight), + "tags": ["bridge-workspace", spec["phase"], "no-training"], + "created_utc": utc(), + }, + ) + history, cursor = [], 0 + + def log(stage, metrics): + nonlocal cursor + history.append( + { + "step": cursor, + "metrics": metrics, + "wall_seconds": time.perf_counter() - began, + "checkpoint_training_step": payload.get("step", payload["spec"].get("steps", 0)), + } + ) + write_json(out / "learning.json", history) + write_json(out / "status.json", {"state": "running", "stage": stage, "step": cursor}) + print( + json.dumps( + { + "run": spec["name"], + "stage": stage, + "index": cursor, + "wall_seconds": history[-1]["wall_seconds"], + } + ), + flush=True, + ) + cursor += 1 + + log("loaded", {}) + pairs = select_pairs( + atoms, families, settings["selection_seed"], settings["prefixes_per_family"], ood=ood + ) + groups, q = pairs["groups"], pairs["queries"] + used_first = set(groups[:, 5]) | set(groups[:, 6]) + calibration = np.asarray([i for i in range(len(atoms)) if i not in used_first]) + calibration = sorted(calibration, key=lambda i: _rank(settings["calibration_seed"], i))[ + : settings["calibration_prompts"] + ] + sender = 1 if view.large else 3 + cp = prefixes(atoms[calibration], view.large, metadata) + tensors = torch.as_tensor(cp, device=device) + jacobians = average_prefix_jacobian(view, tensors, sender, chunk=settings["jacobian_chunk"]) + torch.save( + {"jacobians": jacobians.cpu(), "calibration_atomic_indices": calibration, "prefixes": cp}, + out / "lens.pt", + ) + log("jacobian_lens", {"calibration_prompts": len(cp), "executed_layers": len(view.blocks)}) + trace = trace_in_batches( + view, + prefixes(groups[:, :3], view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + donor_facts = np.column_stack((groups[:, 3], groups[:, 1], groups[:, 4])) + donor_states = trace_in_batches( + view, + prefixes(donor_facts, view.large, metadata), + sender, + settings["batch_size"], + view.large, + )[0] + rows = ( + np.column_stack((groups[q[:, 0], 0], groups[q[:, 0], 1], q[:, 1], q[:, 2])) + if view.large + else np.column_stack( + (groups[q[:, 0], 0], groups[q[:, 0], 1], groups[q[:, 0], 2], q[:, 1], q[:, 2]) + ) + ) + tokens = prompts(rows, view.large, metadata) + training_masks = query_training_masks(world, payload, groups, q, view.large) + # Fix a native panel per stratum without consulting any predictions. + native_rows, native_strata = [], [] + for name in ( + ("test_ii", "test_io", "test_oi", "test_oo") + if view.large + else ("familiar_test", "strict_test") + ): + selected = panels[name][: settings["native_per_stratum"]] + native_rows.append(selected) + native_strata.extend([name] * len(selected)) + native_rows, native_strata = np.concatenate(native_rows), np.asarray(native_strata) + lookup = {(int(h), int(r)): (int(t), i) for i, (h, r, t) in enumerate(atoms)} + native_facts = np.asarray([(h, r, lookup[int(h), int(r)][0]) for h, r in native_rows[:, :2]]) + unique_bridges, bridge_counts = np.unique(native_facts[:, 2], return_counts=True) + fixed_entity = int(unique_bridges[bridge_counts.argmax()]) + fixed_target = native_facts[:, 2] == fixed_entity + ntokens = prompts(native_rows, view.large, metadata) + ntrace = trace_in_batches( + view, + prefixes(native_facts, view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + all_needed = set(groups[:, 5]) | set(groups[:, 6]) | set(q[:, 4]) | set(q[:, 5]) + for row, fact in zip(native_rows, native_facts, strict=True): + r2 = row[2] if view.large else row[3] + all_needed.add(lookup[int(fact[0]), int(fact[1])][1]) + all_needed.add(lookup[int(fact[2]), int(r2)][1]) + needed_ids = np.asarray(sorted(all_needed)) + needed = atoms[needed_ids] + atrace = trace_in_batches( + view, prefixes(needed, view.large, metadata), sender, settings["batch_size"], view.large + ) + torch.save( + { + "recipient": tuple(a.cpu() for a in trace), + "donor_states": donor_states.cpu(), + "native": tuple(a.cpu() for a in ntrace), + "atomic": tuple(a.cpu() for a in atrace), + }, + out / "prefix-traces.pt", + ) + atomic = generate( + view, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + metadata, + settings["batch_size"], + ) + atomic_ok = atomic["generated"][:, 0] == needed[:, -1] + metadata["entity_offset"] + atomic_correct = dict(zip(needed_ids, atomic_ok, strict=True)) + prereq = np.asarray( + [ + all(atomic_correct[int(i)] for i in (groups[g, 5], groups[g, 6], second, cf_second)) + for g, _, _, _, second, cf_second in q + ] + ) + np.savez_compressed( + out / "selection.npz", + **{k: v for k, v in pairs.items() if k != "coverage"}, + rows=rows, + native_rows=native_rows, + native_strata=native_strata, + fixed_entity=np.asarray(fixed_entity), + fixed_entity_target=fixed_target, + **training_masks, + prerequisite_correct=prereq, + needed_atomic_indices=needed_ids, + **{"atomic_" + k: v for k, v in atomic.items()}, + ) + write_json(out / "coverage.json", pairs["coverage"]) + # Independent native implementation equivalence and prefix-causality audit. + audit_tokens = torch.as_tensor(tokens[: min(8, len(tokens))], device=device) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): + native = view.model( + audit_tokens, + positions=torch.full((len(audit_tokens), 1), audit_tokens.shape[1] - 1, device=device), + )[:, 0].float() + traced = view.logits(audit_tokens).float() + _, full_trace = view.hidden(audit_tokens, sender=sender, capture=True) + causal_error = float( + (full_trace[0].float() - trace[0][:, q[: len(audit_tokens), 0]]).abs().max() + ) + torch.testing.assert_close( + full_trace[0].float(), + trace[0][:, q[: len(audit_tokens), 0]], + atol=0.05 if view.large else 2e-5, + rtol=0.005 if view.large else 2e-5, + ) + torch.testing.assert_close( + native, traced, atol=0.05 if view.large else 1e-5, rtol=0.005 if view.large else 1e-5 + ) + if not torch.equal(native.argmax(-1), traced.argmax(-1)): + raise AssertionError("Native/traced greedy answers differ") + summary = {} + + def measure( + family, + condition, + layer, + input_tokens, + target, + cf_target, + strata, + delta=None, + query_groups=None, + ): + result = generate( + view, + input_tokens, + target, + cf_target, + metadata, + settings["batch_size"], + layer=layer if delta is not None else None, + sender=sender, + delta=delta, + ) + np.savez_compressed(out / f"{family}-{condition}-l{layer:02d}.npz", **result) + metrics = summarize(result, target, cf_target, metadata, strata, query_groups) + if family == "swap" and prereq.any(): + metrics["prerequisites_correct"] = summarize( + {k: a[prereq] for k, a in result.items()}, + target[prereq], + cf_target[prereq], + metadata, + strata[prereq], + query_groups[prereq], + )["all"] + if family == "swap" and training_masks["both_queries_untrained"].any(): + mask = training_masks["both_queries_untrained"] + metrics["both_queries_untrained"] = summarize( + {k: a[mask] for k, a in result.items()}, + target[mask], + cf_target[mask], + metadata, + strata[mask], + query_groups[mask], + )["all"] + if family == "native" and (condition.startswith("fixed_entity") or condition == "baseline"): + for label, mask in ( + ("fixed_entity_target", fixed_target), + ("fixed_entity_unrelated", ~fixed_target), + ): + if mask.any(): + metrics[label] = summarize( + {k: a[mask] for k, a in result.items()}, + target[mask], + cf_target[mask], + metadata, + strata[mask], + )["all"] + summary[f"{family}/{condition}/{layer}"] = metrics + write_json(out / "summary.json", summary) + log(f"{family}-{condition}-l{layer}", {family: {condition: {f"layer_{layer}": metrics}}}) + + measure("swap", "baseline", -1, tokens, q[:, 2], q[:, 3], pairs["strata"], query_groups=q[:, 0]) + measure( + "native", "baseline", -1, ntokens, native_rows[:, -1], native_rows[:, -1], native_strata + ) + measure( + "atomic", + "baseline", + -1, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + np.full(len(needed), "needed_atoms"), + ) + states, attentions, mlps = trace + rng = torch.Generator(device=device).manual_seed(settings["rotation_seed"]) + rotation, _ = torch.linalg.qr(torch.randn(view.width, view.width, device=device, generator=rng)) + swap_errors, restore_errors = [], [] + diagnostics = [] + axis_families = settings.get("axis_families", ["prefix_jacobian"]) + if not set(axis_families) <= {"prefix_jacobian", "input_embedding"}: + raise ValueError("Unknown direction family") + for layer, jacobian, axis_family in ( + (layer, j, family) for layer, j in enumerate(jacobians) for family in axis_families + ): + suffix = "_embedding" if axis_family == "input_embedding" else "" + directions = F.normalize( + view.embedding.weight[torch.as_tensor(entities, device=device)].float() + @ (torch.eye(view.width, device=device) if suffix else jacobian), + dim=-1, + ) + index = {int(e): i for i, e in enumerate(entities)} + source = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 2]]] + dest = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 4]]] + basis = torch.stack((source, dest), dim=-1) + swapped = swap_coordinates(states[layer], basis) + restored = swap_coordinates(swapped, basis) + swap_errors.append(float((restored - states[layer]).abs().max())) + random_basis = rotation[None] @ basis + swap_delta = swapped - states[layer] + torch.save( + { + "basis": basis.cpu(), + "rotation": rotation.cpu(), + "swap_delta": swap_delta.cpu(), + "axis_family": axis_family, + }, + out / f"patch-{axis_family}-l{layer:02d}.pt", + ) + deltas = { + "swap": swap_delta, + "swap_x2": 2 * swap_delta, + "random_swap": match_norm( + swap_coordinates(states[layer], random_basis) - states[layer], swap_delta + ), + "full_prefix": donor_states[layer] - states[layer], + "swap_back": restored - states[layer], + } + for condition in SWAPS: + measure( + "swap", + condition + suffix, + layer, + tokens, + q[:, 2], + q[:, 3], + pairs["strata"], + deltas[condition][q[:, 0]], + q[:, 0], + ) + native_direction = directions[ + [index[int(b + metadata["entity_offset"])] for b in native_facts[:, 2]] + ] + native_state, native_attention, native_mlp = (a[layer] for a in ntrace) + fixed_direction = directions[index[fixed_entity + metadata["entity_offset"]]][ + None + ].expand_as(native_direction) + fixed_mlp = projection(native_mlp, fixed_direction) + removed_mlp = projection(native_mlp, native_direction) + # All sublayers still execute. Only the selected sender's semantic component + # is subtracted from the actual local update at the boundary. + local_restore = native_state - removed_mlp + removed_mlp + restore_errors.append(float((local_restore - native_state).abs().max())) + erasures = { + "erase_state": -projection(native_state, native_direction), + "erase_mlp": -removed_mlp, + "erase_attention": -projection(native_attention, native_direction), + "random_state": match_norm( + -projection(native_state, native_direction @ rotation.T), + -projection(native_state, native_direction), + ), + "random_mlp": match_norm( + -projection(native_mlp, native_direction @ rotation.T), -removed_mlp + ), + "random_attention": match_norm( + -projection(native_attention, native_direction @ rotation.T), + -projection(native_attention, native_direction), + ), + "restore_mlp": local_restore - native_state, + "fixed_entity_mlp": -fixed_mlp, + "fixed_entity_random_mlp": match_norm( + -projection(native_mlp, fixed_direction @ rotation.T), + -fixed_mlp, + ), + } + for condition in ERASURES: + measure( + "native", + condition + suffix, + layer, + ntokens, + native_rows[:, -1], + native_rows[:, -1], + native_strata, + erasures[condition], + ) + # Relevant single-hop facts are scored under exactly the same local deletion. + adirection = directions[[index[int(b + metadata["entity_offset"])] for b in needed[:, 2]]] + atomic_delta = -projection(atrace[2][layer], adirection) + measure( + "atomic", + "erase_mlp" + suffix, + layer, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + np.full(len(needed), "needed_atoms"), + atomic_delta, + ) + with torch.no_grad(): + raw = F.linear(view.norm(states[layer]), view.embedding.weight).argmax(-1) + lens = F.linear(view.norm(states[layer] @ jacobian.T), view.embedding.weight).argmax(-1) + diagnostics.append( + { + "layer": layer, + "axis_family": axis_family, + "native_bridge_readout_accuracy": float( + ( + raw + == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) + ) + .float() + .mean() + ), + "prefix_jacobian_bridge_readout_accuracy": float( + ( + lens + == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) + ) + .float() + .mean() + ), + "swap_norm_mean": float(swap_delta.norm(dim=-1).mean()), + "native_mlp_removed_norm_mean": float(removed_mlp.norm(dim=-1).mean()), + } + ) + digest_after = model_digest(view.model) + if digest_before != digest_after or any(p.grad is not None for p in view.model.parameters()): + raise AssertionError("Intervention changed model parameters or accumulated gradients") + write_json( + out / "implementation-audit.json", + { + "parameters_unchanged": True, + "native_tracer_max_logit_error": float((native - traced).abs().max()), + "prefix_causal_state_max_error": causal_error, + "swap_inverse_max_errors": swap_errors, + "mlp_restore_max_errors": restore_errors, + "n_needed_atomic_facts": len(needed), + "needed_atomic_answer_accuracy": float(atomic_ok.mean()), + "swap_prerequisite_query_coverage": float(prereq.mean()), + "scoring": ( + "greedy feedback, original/counterfactual answer plus termination; " + "query and first-fact denominators separate" + ), + }, + ) + write_json(out / "diagnostics.json", diagnostics) + log("complete", {"complete": {"evaluations": len(summary)}}) + write_json( + out / "interventions-complete.json", + { + "finished_utc": utc(), + "evaluations": len(summary), + "model_sha256": digest_after, + "wall_seconds": time.perf_counter() - began, + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device), + "new_training_updates": 0, + }, + ) + write_json(out / "status.json", {"state": "awaiting_reload_audit", "step": cursor - 1}) + + +def audit_run(out, gpu): + """Reload in an independent process and reproduce fixed raw prediction subsets.""" + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + metadata_run = json.loads((out / "run.json").read_text()) + spec = metadata_run["spec"] + settings = spec["settings"] + view, _, metadata, _, atoms, _, _, entities, _ = load_task(spec, f"cuda:{gpu}") + assert model_digest(view.model) == metadata_run["initial_model_sha256"] + assert os.getpid() != metadata_run["pid"], "Reload must use a separate process" + selection = dict(np.load(out / "selection.npz")) + groups, queries = selection["groups"], selection["queries"] + jacobians = torch.load(out / "lens.pt", map_location=view.device, weights_only=False)[ + "jacobians" + ] + sender = 1 if view.large else 3 + trace = trace_in_batches( + view, + prefixes(groups[:, :3], view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + states = trace[0] + native_rows = selection["native_rows"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + facts = np.asarray([(h, r, lookup[int(h), int(r)]) for h, r in native_rows[:, :2]]) + ntrace = trace_in_batches( + view, prefixes(facts, view.large, metadata), sender, settings["batch_size"], view.large + ) + swap_indices = np.unique(np.linspace(0, len(queries) - 1, min(32, len(queries)), dtype=int)) + native_indices = np.unique( + np.linspace(0, len(native_rows) - 1, min(32, len(native_rows)), dtype=int) + ) + summary = json.loads((out / "summary.json").read_text()) + comparisons, max_logp_error, identity_controls = [], 0.0, [] + + def check(family, condition, layer, indices, rows, target, cf, delta=None): + nonlocal max_logp_error + + # Baseline is independently executed through the model's own forward. + class NativeView(ModelView): + def logits(self, tokens, **_): + positions = torch.full((len(tokens), 1), tokens.shape[1] - 1, device=self.device) + return self.model(tokens, positions=positions)[:, 0] + + actual = generate( + NativeView(view.model) if condition == "baseline" else view, + prompts(rows, view.large, metadata), + target, + cf, + metadata, + settings["batch_size"], + layer=layer if delta is not None else None, + sender=sender, + delta=delta, + ) + # Preserve original batch shapes: compacting selected rows changes BF16 + # GEMM rounding. Select the audit subset only after the full generation. + actual = {key: value[indices] for key, value in actual.items()} + expected = dict(np.load(out / f"{family}-{condition}-l{layer:02d}.npz")) + if not np.array_equal(actual["generated"], expected["generated"][indices]): + raise AssertionError(f"Reload generation mismatch: {family}/{condition}/{layer}") + for key in ("original_logp", "cf_logp"): + error = float(np.max(np.abs(actual[key] - expected[key][indices]))) + max_logp_error = max(max_logp_error, error) + np.testing.assert_allclose( + actual[key], + expected[key][indices], + atol=0.04 if view.large else 3e-5, + rtol=0.002 if view.large else 2e-5, + ) + comparisons.append( + {"family": family, "condition": condition, "layer": layer, "queries": len(indices)} + ) + + check("swap", "baseline", -1, swap_indices, selection["rows"], queries[:, 2], queries[:, 3]) + check( + "native", + "baseline", + -1, + native_indices, + native_rows, + native_rows[:, -1], + native_rows[:, -1], + ) + entity_index = {int(e): i for i, e in enumerate(entities)} + for layer, jacobian in enumerate(jacobians): + for axis_family in settings.get("axis_families", ["prefix_jacobian"]): + suffix = "_embedding" if axis_family == "input_embedding" else "" + directions = F.normalize( + view.embedding.weight[torch.as_tensor(entities, device=view.device)].float() + @ (torch.eye(view.width, device=view.device) if suffix else jacobian), + dim=-1, + ) + source = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 2]] + ] + dest = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 4]] + ] + delta = ( + swap_coordinates(states[layer], torch.stack((source, dest), dim=-1)) - states[layer] + ) + check( + "swap", + "swap" + suffix, + layer, + swap_indices, + selection["rows"], + queries[:, 2], + queries[:, 3], + delta[queries[:, 0]], + ) + native_direction = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in facts[:, 2]] + ] + native_delta = -projection(ntrace[2][layer], native_direction) + check( + "native", + "erase_mlp" + suffix, + layer, + native_indices, + native_rows, + native_rows[:, -1], + native_rows[:, -1], + native_delta, + ) + # Structural and numerical controls must retain native generation. + for family, condition in ( + ("swap", "swap_back" + suffix), + ("native", "restore_mlp" + suffix), + ): + raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] + baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] + identity_controls.append( + { + "family": family, + "condition": condition, + "layer": layer, + **control_observation(raw, baseline), + } + ) + if layer == len(view.blocks) - 1: + for key in summary: + family, condition, occurrence = key.split("/") + if int(occurrence) != layer or family == "atomic": + continue + raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] + baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] + assert np.array_equal(raw, baseline), ( + key, + "final sender must not affect later positions", + ) + assert model_digest(view.model) == metadata_run["initial_model_sha256"] + previous = out / "implementation-audit.json" + if not previous.exists() and (out / "audit.json").exists(): + previous.write_bytes((out / "audit.json").read_bytes()) + write_json( + out / "audit.json", + { + "independent_process": True, + "pid": os.getpid(), + "gpu": gpu, + "finished_utc": utc(), + "parameters_unchanged": True, + "generations_exact": True, + "identity_controls_exact": all(c["exact"] for c in identity_controls), + "identity_control_observations": identity_controls, + "scope": ( + "Fixed subset reload predictions exact; numerical inverse/restore " + "outcomes recorded separately" + ), + "max_log_probability_error": max_logp_error, + "evaluations": comparisons, + "implementation_audit_sha256": file_hash(previous), + "audit_source_sha256": file_hash(__file__), + }, + ) + if (out / "interventions-complete.json").exists(): + complete = json.loads((out / "interventions-complete.json").read_text()) + complete["independently_reloaded"] = True + complete["audit_finished_utc"] = utc() + write_json(out / "complete.json", complete) + write_json( + out / "status.json", + { + "state": "complete", + "independently_reloaded": True, + "step": json.loads((out / "learning.json").read_text())[-1]["step"], + }, + ) + print( + json.dumps( + { + "run": out.name, + "independent_reload": "passed", + "evaluations": len(comparisons), + "max_log_probability_error": max_logp_error, + } + ), + flush=True, + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/capacity_controls.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/capacity_controls.py new file mode 100644 index 0000000000000000000000000000000000000000..3806e6b81fda1ae9bc25fd74e38f846ddd3a456d --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/capacity_controls.py @@ -0,0 +1,64 @@ +"""Controls separating knowledge load, derived supervision, and serial recall.""" + +from __future__ import annotations + +import numpy as np + +from .capacity_scaling import DIGIT, EOS, TYPE_B + + +def training_indices(world, spec, epoch): + """Keep the historical mixed stream exactly, or replace derived examples. + + Replay preserves the mixed stream's batch sizes/updates and each original + atomic slot. Extra slots carry balanced atomic replay, never held-out labels. + """ + atoms = len(world["atomic"]) + mixed = atoms + len(world["train_composition"]) + mode = spec.get("training_mode", "mixed") + if mode not in {"mixed", "atomic", "atomic_replay"}: + raise ValueError(mode) + n = atoms if mode == "atomic" else mixed + rng = np.random.default_rng(np.random.SeedSequence([spec["stream_seed"], epoch])) + order = rng.permutation(n) + if mode == "atomic_replay": + replay_rng = np.random.default_rng( + np.random.SeedSequence([spec["stream_seed"], epoch, 771]) + ) + replacements = np.resize(replay_rng.permutation(atoms), mixed - atoms) + source = np.concatenate((np.arange(atoms), replacements)) + return source[order] + return order + + +def decode_bridge(predictions): + """Reject malformed/out-of-domain predictions instead of oracle repairing.""" + p = np.asarray(predictions) + d = p[:, 1:5] - DIGIT + valid = ( + (p[:, 0] == TYPE_B) + & (p[:, 5] == EOS) + & ((d >= 0) & (d < 16)).all(1) + & (d[:, :2] == 0).all(1) + ) + values = (np.clip(d, 0, 15) * np.array([4096, 256, 16, 1])).sum(1) + return np.where(valid, values, 0), valid + + +def first_queries(compositions): + rows = np.zeros_like(compositions) + rows[:, 0] = 0 + rows[:, 1:3] = compositions[:, 1:3] + rows[:, 3] = -1 + rows[:, 5:] = -1 + return rows + + +def second_queries(compositions, bridges): + rows = np.zeros_like(compositions) + rows[:, 0] = 1 + rows[:, 1] = bridges + rows[:, 2] = compositions[:, 3] + rows[:, 3] = -1 + rows[:, 5:] = -1 + return rows diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/capacity_scaling.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/capacity_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c152e8710de107c8fb2f4ba2275cdea5cbdcf3 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/capacity_scaling.py @@ -0,0 +1,193 @@ +"""Fixed-vocabulary random worlds for the capacity development experiment. + +Knowledge is in independent A->B and B->C maps. Composition labels are derived, +never counted as independent information. This is a QA adaptation, not bioS. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +PAD, BOS, EOS, ANSWER = 0, 1, 2, 3 +TYPE_A, TYPE_B, TYPE_C = 4, 5, 6 +DIGIT, REL_A, REL_B = 7, 23, 27 +VOCAB, CONTEXT, ANSWER_LENGTH = 31, 14, 6 + + +def digest_arrays(arrays): + h = hashlib.sha256() + for key, value in sorted(arrays.items()): + value = np.ascontiguousarray(value) + h.update(key.encode()) + h.update(str(value.shape).encode()) + h.update(str(value.dtype).encode()) + h.update(value.tobytes()) + return h.hexdigest() + + +def generate_world(spec): + """Rows: kind, subject, r1, r2, answer, necessary_atom_1, necessary_atom_2. + + The maximum address universe and all maps are generated before choosing a + load. Prefix worlds are nested. Background controls keep the entire low-load + composition training/evaluation sets, including necessary facts, unchanged. + """ + seed, heads = spec["world_seed"], spec["heads_n"] + maximum, values, relations = spec["max_heads"], spec["values_n"], spec["relations"] + if not (1 <= heads <= maximum <= 65536 and values == 256 and relations == 4): + raise ValueError("This version requires 256 values, four relations, <=65536 heads") + support_heads = spec.get("support_heads_n", heads) + if not 1 <= support_heads <= heads: + raise ValueError("Invalid support prefix") + + def rng(part): + return np.random.default_rng(np.random.SeedSequence([seed, part])) + + first = rng(0).integers(values, size=(maximum, relations), dtype=np.int64)[:heads] + second = rng(1).integers(values, size=(values, relations), dtype=np.int64) + eligible_first = rng(2).random((maximum, relations))[:support_heads] < 0.75 + eligible_second = rng(3).random((values, relations)) < 0.75 + first_n = heads * relations + h, r = np.indices(first.shape).reshape(2, -1) + atoms_a = np.column_stack( + ( + np.zeros(first_n, dtype=int), + h, + r, + -np.ones(first_n, dtype=int), + first.ravel(), + np.arange(first_n), + -np.ones(first_n, dtype=int), + ) + ) + b, r2 = np.indices(second.shape).reshape(2, -1) + second_n = second.size + atoms_b = np.column_stack( + ( + np.ones(second_n, dtype=int), + b, + r2, + -np.ones(second_n, dtype=int), + second.ravel(), + first_n + np.arange(second_n), + -np.ones(second_n, dtype=int), + ) + ) + atoms = np.concatenate((atoms_a, atoms_b)).astype(np.int64) + h, r1, r2 = np.indices((support_heads, relations, relations)).reshape(3, -1) + bridge = first[h, r1] + a_id, b_id = h * relations + r1, first_n + bridge * relations + r2 + comps = np.column_stack((np.full(len(h), 2), h, r1, r2, second[bridge, r2], a_id, b_id)).astype( + np.int64 + ) + train_mask = ( + eligible_first[h, r1] & eligible_second[bridge, r2] & (((r2 - h - r1) % relations) < 2) + ) + trained = np.zeros(len(atoms), dtype=bool) + trained[comps[train_mask, 5:].ravel()] = True + seen1, seen2 = trained[a_id], trained[b_id] + world = { + "first": first, + "second": second, + "atomic": atoms, + "train_composition": comps[train_mask], + } + for name, mask in { + "II": seen1 & seen2, + "IO": seen1 & ~seen2, + "OI": ~seen1 & seen2, + "OO": ~seen1 & ~seen2, + }.items(): + ids = np.flatnonzero(mask & ~train_mask) + # Selection stream does not depend on load in fixed-target controls. + take = rng(20 + ["II", "IO", "OI", "OO"].index(name)).permutation(ids) + world[name] = comps[take[: spec["evaluation_per_pool"]]] + world[name + "_population"] = np.array([len(ids)], dtype=np.int64) + panel_rng = rng(30) + for name in ("atomic", "train_composition"): + ids = panel_rng.permutation(len(world[name]))[: spec["evaluation_per_pool"]] + world[name + "_panel"] = world[name][ids] + world["role_counts"] = np.stack( + [np.bincount(world["train_composition"][:, col], minlength=len(atoms)) for col in (5, 6)] + ) + return world + + +def digits(values): + values = np.asarray(values, dtype=np.int64) + return DIGIT + ((values[:, None] >> np.array([12, 8, 4, 0])) & 15) + + +def pack(rows): + """Right padding is causally downstream; only answer+EOS is supervised.""" + rows = np.asarray(rows, dtype=np.int64) + x = np.zeros((len(rows), CONTEXT), dtype=np.int64) + composition = rows[:, 0] == 2 + prefix_length = np.where(composition, 9, 8) + x[:, 0] = BOS + x[:, 1] = np.where(rows[:, 0] == 1, TYPE_B, TYPE_A) + x[:, 2:6] = digits(rows[:, 1]) + x[:, 6] = np.where(rows[:, 0] == 1, REL_B, REL_A) + rows[:, 2] + x[:, 7] = np.where(composition, REL_B + rows[:, 3], ANSWER) + x[composition, 8] = ANSWER + labels = np.column_stack( + (np.where(rows[:, 0] == 0, TYPE_B, TYPE_C), digits(rows[:, 4]), np.full(len(rows), EOS)) + ) + positions = prefix_length[:, None] - 1 + np.arange(ANSWER_LENGTH) + x[np.arange(len(rows))[:, None], positions[:, 1:]] = labels[:, :-1] + return x, positions, labels + + +def information_ledger(world, parameters, knowledge_nll=None): + facts = len(world["atomic"]) + bits = facts * math.log2(world["second"].shape[0]) + result = { + "independent_facts": facts, + "world_bits": bits, + "parameters": parameters, + "adjusted_parameters": parameters, + "data_bits_per_parameter": bits / parameters, + "composition_independent_bits": 0, + } + if knowledge_nll is not None: + learned = bits - facts * knowledge_nll / math.log(2) + result.update(learned_bits_raw=learned, learned_bits_per_parameter=learned / parameters) + return result + + +def model_parameter_count(width, layers=2): + # Tied token/output weights, learned positions, two biased projections each + # in attention/MLP, per-block and final LayerNorms. + return (VOCAB + CONTEXT) * width + layers * (12 * width**2 + 13 * width) + 2 * width + + +def prerequisite_pass(metrics, thresholds): + return all( + metrics[key]["accuracy"] >= thresholds[key] for key in ("atomic", "train_composition", "II") + ) + + +def grid_capacity(points, metric, threshold, atomic_threshold): + """Report sampled successes and censoring, never silently assume monotonicity.""" + points = sorted(points, key=lambda p: p["bits"]) + passed = [p["atomic"] >= atomic_threshold and p[metric] >= threshold for p in points] + reversals = any(passed[i] and not passed[i - 1] for i in range(1, len(passed))) + successes = [p["bits"] for p, ok in zip(points, passed, strict=True) if ok] + lower = max(successes) if successes else None + failures_above = [ + p["bits"] + for p, ok in zip(points, passed, strict=True) + if not ok and (lower is None or p["bits"] > lower) + ] + return { + "largest_observed_passing_bits": lower, + "next_observed_failing_bits": min(failures_above) if failures_above else None, + "nonmonotonic_grid": reversals, + "interpretation": "sampled_grid_only; bracket requires monotone interpolation", + "censoring": "below_grid" + if lower is None + else ("above_grid" if not failures_above else "bracketed_on_grid"), + } diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/cli.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..1aec4627fdf91a196893b3a6d47c8188da55d55b --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/cli.py @@ -0,0 +1,32 @@ +"""Command-line interface for the deterministic matrix illustration.""" + +import argparse +import json +from pathlib import Path + +from .experiments import run_minimal_example + + +def main(argv: list[str] | None = None) -> int: + """Print the analytical report as JSON and optionally save a copy.""" + parser = argparse.ArgumentParser(description="Run the analytical low-rank editability example.") + parser.add_argument( + "--rank", type=int, default=1, help="total rank budget: 0, 1 (default), or 2" + ) + parser.add_argument( + "--atol", type=float, default=1e-10, help="positive absolute singular-value tolerance" + ) + parser.add_argument( + "--output", type=Path, help="also save JSON to this path (creates parent directories)" + ) + args = parser.parse_args(argv) + try: + report = run_minimal_example(rank=args.rank, atol=args.atol) + serialized = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(serialized + "\n", encoding="utf-8") + except (ValueError, OSError) as exc: + parser.error(str(exc)) + print(serialized) + return 0 diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/composition_curves.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/composition_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..13009dcfa856d01722da32842dcc3a7fe078a635 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/composition_curves.py @@ -0,0 +1,477 @@ +"""Distinct composition support and knowledge-load curves on random relation graphs. + +The graph, answer/EOS objective, GPT blocks and optimizer reuse the previously +successful Wang et al. adaptation. A fixed maximum entity vocabulary keeps +parameters identical across loads. Development and confirmation worlds differ. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import ( + EpochStream, + GraphStep, + SmallGPT, + evaluate_rows, + make_optimizer, + pack_rows, + two_calls, + utc, + write_json, +) +from .grok_depth_data import audit_world, build_world + + +def sha256(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def array_hash(arrays): + digest = hashlib.sha256() + for name, value in sorted(arrays.items()): + digest.update(name.encode()) + digest.update(np.asarray(value.shape, dtype=" len(order): + raise ValueError("Distinct support request exceeds the reserved training pool") + arrays = { + key: base[key].copy() + for key in ("atomic", "id_atomic", "ood_atomic", "test_composite", "ood_composite") + } + eligible = base["unused_composite"][order].copy() + for rows in [*arrays.values(), eligible]: + rows[:, 1:-1] += maximum - n + identity = array_hash({**arrays, "eligible": eligible}) + arrays["train_composite"] = eligible[:requested].copy() + lookup = np.full((maximum, spec["relations"]), -1, dtype=np.int64) + atomic = arrays["atomic"] + lookup[atomic[:, 0] - 2, atomic[:, 1] - maximum - 2] = np.arange(len(atomic)) + first, second = constituent_indices(arrays["train_composite"], atomic, lookup, maximum) + first_counts = np.bincount(first, minlength=len(atomic)) + second_counts = np.bincount(second, minlength=len(atomic)) + role = {} + for name in ("test_composite", "ood_composite"): + one, two = constituent_indices(arrays[name], atomic, lookup, maximum) + role[name] = { + "n": len(one), + "both_facts_seen_in_required_roles": ( + float(((first_counts[one] > 0) & (second_counts[two] > 0)).mean()) + if len(one) + else None + ), + } + panel_rng = np.random.default_rng(np.random.SeedSequence([spec["world_seed"], n, 960602])) + panels = {} + for key, name in [ + ("atomic", "atomic"), + ("id_atomic", "atomic_id"), + ("ood_atomic", "atomic_ood"), + ("test_composite", "II"), + ("ood_composite", "OO"), + ]: + rows = arrays[key] + ids = panel_rng.choice(len(rows), min(spec["evaluation_size"], len(rows)), replace=False) + panels[name] = rows[ids].copy() + panels["train_composition"] = arrays["train_composite"][: spec["evaluation_size"]].copy() + metadata = { + "world_seed": spec["world_seed"], + "entities": n, + "max_entities": maximum, + "relations": spec["relations"], + "degree": spec["degree"], + "vocab_size": maximum + spec["relations"] + 2, + "atomic_examples": len(atomic), + "id_atomic_examples": len(arrays["id_atomic"]), + "composition_examples": requested, + "eligible_compositions": len(eligible), + "phi_actual": requested / len(arrays["id_atomic"]), + "world_sha256": identity, + "dataset_sha256": array_hash(arrays), + "knowledge_bits": len(atomic) * math.log2(n), + "entropy_condition": "independent uniform tails, conditional on head/relation keys", + "composition_additional_independent_bits": 0, + "role_coverage": role, + "panel_counts": {key: len(value) for key, value in panels.items()}, + "full_counts": {key: len(value) for key, value in arrays.items()}, + "graph_source": base["metadata"]["source_url"], + "graph_source_commit": base["metadata"]["source_commit"], + "graph_audit": base["metadata"]["dataset_sha256"], + } + return arrays, panels, metadata + + +def constituent_indices(rows, atomic, lookup, maximum): + first = lookup[rows[:, 0] - 2, rows[:, 1] - maximum - 2] + if np.any(first < 0): + raise ValueError("Unknown first-hop fact") + second = lookup[atomic[first, 2] - 2, rows[:, 2] - maximum - 2] + if np.any(second < 0) or not np.array_equal(atomic[second, 2], rows[:, -1]): + raise ValueError("Composition truth differs from graph traversal") + return first, second + + +def budget_nodes(spec, total): + matched = math.ceil(spec["target_exposures"] * total / spec["batch_size"]) + compute = spec["compute_steps"] + end = spec.get("fixed_steps", max(compute, matched)) + nodes = {0, end, *range(2000, min(end, 128000) + 1, 2000)} + nodes.update(s for s in (256, 512, 1000, compute, matched) if s <= end) + nodes.update(range(192000, end, 64000)) + return sorted(nodes), {"compute": compute, "exposure": matched, "end": end} + + +def construct(spec, device): + torch.manual_seed(spec["initialization"]) + cfg = ModelConfig( + vocab_size=spec["max_entities"] + spec["relations"] + 2, + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + return SmallGPT(cfg, dropout=spec["dropout"]).to(device), cfg + + +def model_hash(model): + digest = hashlib.sha256() + for name, tensor in model.state_dict().items(): + digest.update(name.encode()) + digest.update(tensor.detach().cpu().contiguous().numpy().tobytes()) + return digest.hexdigest() + + +def measure(model, panels, device): + metrics, predictions = {}, {} + for name, rows in panels.items(): + metrics[name], values = evaluate_rows(model, rows, device, batch_size=512) + if len(rows): + metrics[name]["answer_nll"] = float(values["nll"][:, 0].mean()) + predictions.update({name + "_" + key: value for key, value in values.items()}) + return metrics, predictions + + +def train(spec, out, resume=False): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device("cuda:0") + torch.cuda.set_device(device) + arrays, panels, data = prepare_world(spec) + model, cfg = construct(spec, device) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + packed = [pack_rows(arrays[key]) for key in ("atomic", "train_composite")] + table = tuple( + torch.as_tensor(np.concatenate([a, b]), device=device) for a, b in zip(*packed, strict=True) + ) + atomic_n, composition_n = data["atomic_examples"], data["composition_examples"] + total = atomic_n + composition_n + stream = EpochStream(total, spec["stream_seed"]) + nodes, budgets = budget_nodes(spec, total) + start, seconds = 0, 0.0 + counts = {"atomic": 0, "composition": 0} + initial_hash = model_hash(model) + if resume: + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if saved["spec"] != spec or saved["world_sha256"] != data["world_sha256"]: + raise ValueError("Resume identity mismatch") + model.load_state_dict(saved["model"]) + optimizer.load_state_dict(saved["optimizer"]) + lr = optimizer.param_groups[0]["lr"] + for group in optimizer.param_groups: + group["lr"] = lr + stream.load_state_dict(saved["stream"]) + counts, seconds, start = saved["counts"], saved["seconds"], saved["step"] + torch.set_rng_state(saved["cpu_rng"].cpu()) + torch.cuda.set_rng_state(saved["cuda_rng"].cpu()) + initial_hash = json.loads((out / "run.json").read_text())["initial_model_sha256"] + out.mkdir(parents=True, exist_ok=True) + metadata = { + "spec": spec, + "phase": spec["phase"], + "pid": os.getpid(), + "gpu": int(os.environ.get("PHYSICAL_GPU", 0)), + "gpu_name": torch.cuda.get_device_name(), + "parameters": sum(p.numel() for p in model.parameters()), + "initial_model_sha256": initial_hash, + "world_sha256": data["world_sha256"], + "dtype": "FP32 parameters/optimizer/forward; TF32 matmul", + "torch": torch.__version__, + "numpy": np.__version__, + "budgets": budgets, + "evaluation_nodes": nodes, + **data, + } + write_json(out / "run.json", metadata) + write_json(out / "data-audit.json", data) + np.savez_compressed(out / "world.npz", **arrays) + np.savez_compressed(out / "panels.npz", **panels) + t0 = time.perf_counter() + graph = GraphStep(model, optimizer, table, spec["batch_size"]) + capture = time.perf_counter() - t0 + per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) + history = json.loads((out / "learning.json").read_text()) if resume else [] + history = [record for record in history if record["step"] <= start] + begun = time.perf_counter() + + def checkpoint(step, loss=None): + metrics, predictions = measure(model, panels, device) + record = { + "step": step, + "utc": utc(), + "metrics": metrics, + "training_seconds": seconds, + "wall_seconds": time.perf_counter() - begun, + "capture_seconds": capture, + "examples": step * spec["batch_size"], + "atomic_examples_seen": counts["atomic"], + "composition_examples_seen": counts["composition"], + "atomic_epochs": counts["atomic"] / atomic_n, + "composition_epochs": counts["composition"] / composition_n if composition_n else 0, + "minimum_record_exposures": (step * spec["batch_size"]) // total, + "maximum_record_exposures": math.ceil(step * spec["batch_size"] / total), + "supervised_tokens": step * spec["batch_size"] * 2, + "executed_input_tokens": step * spec["batch_size"] * 4, + "estimated_matmul_training_flops": step * per_step, + "loss": loss, + "learning_rate": float(lr.detach()), + } + history.append(record) + write_json(out / "learning.json", history) + payload = { + "spec": spec, + "world_sha256": data["world_sha256"], + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "seconds": seconds, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(), + } + torch.save(payload, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in budgets.values(): + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step}.pt", + ) + np.savez_compressed(out / f"predictions-{step}.npz", **predictions) + status = { + "state": "trained" if step == budgets["end"] else "running", + "step": step, + "budget": budgets["end"], + "atomic": metrics["atomic"]["accuracy"], + "II": metrics["II"]["accuracy"], + "updated_utc": utc(), + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + + if not resume: + checkpoint(0) + for end in (node for node in nodes if node > start): + torch.cuda.synchronize() + t0 = time.perf_counter() + loss = None + step = start + while step < end: + length = min(256, end - step) + indices = stream.take(length * spec["batch_size"]).reshape(length, -1) + atom_count = int((indices < atomic_n).sum()) + counts["atomic"] += atom_count + counts["composition"] += indices.size - atom_count + gpu_indices = torch.as_tensor(indices, device=device) + for j in range(length): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + loss = graph(gpu_indices[j]) + step += length + torch.cuda.synchronize() + seconds += time.perf_counter() - t0 + value = float(loss.detach()) + if not math.isfinite(value): + raise FloatingPointError(f"Nonfinite loss at {end}") + checkpoint(end, value) + start = end + full_panels = { + "atomic": arrays["atomic"], + "atomic_id": arrays["id_atomic"], + "atomic_ood": arrays["ood_atomic"], + "II": arrays["test_composite"], + "OO": arrays["ood_composite"], + } + full, predictions = measure(model, full_panels, device) + full["external_two_calls"] = two_calls(model, panels["II"], device) + np.savez_compressed(out / "full-predictions.npz", **predictions) + write_json( + out / "complete.json", + { + "step": start, + "spec": spec, + "parameters": metadata["parameters"], + "training_seconds": seconds, + "wall_seconds": time.perf_counter() - begun, + "endpoint": history[-1], + "full_metrics": full, + "finished_utc": utc(), + }, + ) + + +def audit(spec, out): + """Reload both predeclared comparison checkpoints and independently recount.""" + out = Path(out) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + arrays, panels, data = prepare_world(spec) + recorded = dict(np.load(out / "world.npz")) + if array_hash(recorded) != data["dataset_sha256"]: + raise ValueError("Saved world differs from deterministic reconstruction") + meta = json.loads((out / "run.json").read_text()) + if meta["world_sha256"] != data["world_sha256"]: + raise ValueError("World identity mismatch") + history = json.loads((out / "learning.json").read_text()) + nodes, budgets = budget_nodes(spec, data["atomic_examples"] + data["composition_examples"]) + if [record["step"] for record in history] != nodes: + raise ValueError("Missing or reordered evaluation nodes") + model, cfg = construct(spec, "cuda:0") + if sum(p.numel() for p in model.parameters()) != meta["parameters"]: + raise ValueError("Parameter count mismatch") + per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) + for record in history: + examples = record["step"] * spec["batch_size"] + if record["examples"] != examples or examples != ( + record["atomic_examples_seen"] + record["composition_examples_seen"] + ): + raise ValueError("Exposure arithmetic mismatch") + if record["estimated_matmul_training_flops"] != record["step"] * per_step: + raise ValueError("Executed-shape FLOP mismatch") + reloaded = [] + for step in sorted(set(budgets.values()) & set(nodes)): + saved = torch.load(out / f"weights-{step}.pt", weights_only=False, map_location="cuda:0") + if saved["spec"] != spec or saved["step"] != step: + raise ValueError("Checkpoint identity mismatch") + model.load_state_dict(saved["model"]) + metrics, predictions = measure(model, panels, "cuda:0") + original = dict(np.load(out / f"predictions-{step}.npz")) + for key, values in predictions.items(): + if key.endswith("_nll"): + np.testing.assert_allclose(values, original[key], rtol=1e-5, atol=1e-6) + elif not np.array_equal(values, original[key]): + raise ValueError(f"Reloaded predictions changed: {step} {key}") + prior = next(record for record in history if record["step"] == step)["metrics"] + for name, metric in metrics.items(): + if metric["accuracy"] != prior[name]["accuracy"]: + raise ValueError("Metric recount mismatch") + reloaded.append(step) + full_panels = { + "atomic": arrays["atomic"], + "atomic_id": arrays["id_atomic"], + "atomic_ood": arrays["ood_atomic"], + "II": arrays["test_composite"], + "OO": arrays["ood_composite"], + } + full, predictions = measure(model, full_panels, "cuda:0") + original = dict(np.load(out / "full-predictions.npz")) + for key, value in predictions.items(): + np.testing.assert_allclose(value, original[key], rtol=1e-5, atol=1e-6) + full["external_two_calls"] = two_calls(model, panels["II"], "cuda:0") + write_json( + out / "audit.json", + {"passed": True, "reloaded_steps": reloaded, "full_metrics": full, "utc": utc()}, + ) + write_json(out / "status.json", {"state": "complete", "step": budgets["end"], "utc": utc()}) + + +def calibrated_choice(records, thresholds): + """Development-only success gate; prefer smaller registered model when both pass.""" + candidates = [] + for spec, metrics in records: + passed = all(metrics[key]["accuracy"] >= value for key, value in thresholds.items()) + if passed: + candidates.append(spec) + return min(candidates, key=lambda spec: spec["layers"]) if candidates else None + + +def confirmation_specs(config, selected): + specs = [] + for index, seed in enumerate(config["confirmation_worlds"]): + for phi in config["support_phi"]: + specs.append( + { + **selected, + "phase": "confirmation", + "world_seed": seed, + "initialization": config["initialization"] + index, + "stream_seed": config["stream_seed"] + index, + "name": f"support-w{index + 1}-phi{phi:g}", + "phi": phi, + "entities": config["base_spec"]["entities"], + } + ) + return specs + + +def anchors_pass(records, worlds, thresholds): + """Require exactly the registered independent worlds; no cherry-picked anchors.""" + observed = [spec["world_seed"] for spec, _ in records] + if len(observed) != len(worlds) or set(observed) != set(worlds): + return False + return all( + all(metrics[key]["accuracy"] >= threshold for key, threshold in thresholds.items()) + for _, metrics in records + ) + + +def load_specs(config, selected): + specs = [] + for index, seed in enumerate(config["confirmation_worlds"]): + for n in config["load_entities"][1:]: + specs.append( + { + **selected, + "phase": "confirmation", + "world_seed": seed, + "initialization": config["initialization"] + index, + "stream_seed": config["stream_seed"] + index, + "name": f"load-w{index + 1}-n{n}", + "phi": config["anchor_phi"], + "entities": n, + } + ) + return specs diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/curve_tracking.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/curve_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..526a40aecb32ed282e9de766f3162546d80403ac --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/curve_tracking.py @@ -0,0 +1,36 @@ +"""Retry transient W&B connection failures without changing scientific trajectories.""" + +import json +import time +import traceback +from datetime import datetime, timezone +from pathlib import Path + +from . import interface_tracking +from .experiment_tracking import write_json + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def main(): + import sys + + root = Path(sys.argv[sys.argv.index("--root") + 1]) + for attempt in range(1, 145): + try: + interface_tracking.main() + return + except Exception: + path = root / "tracking-retries.json" + history = json.loads(path.read_text()) if path.exists() else [] + history.append({"attempt": attempt, "utc": utc(), "error": traceback.format_exc()}) + write_json(path, history) + print(json.dumps({"tracking_retry": attempt, "utc": utc()}), flush=True) + time.sleep(min(60, 5 * attempt)) + raise RuntimeError("W&B retry budget exhausted; scientific artifacts remain intact") + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/depth_step.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/depth_step.py new file mode 100644 index 0000000000000000000000000000000000000000..8f828c9ccea5c225dd4fc257587afe3c0ff7c6bf --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/depth_step.py @@ -0,0 +1,669 @@ +"""Ordinary end-to-end GPT depth and optimization-time development experiment. + +The frozen random graph is shared across two-, three- and four-hop training. +Only terminal entities enter composition text; intermediate truth is used for +evaluation and audit. Existing experimental implementations remain unchanged. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_data import build_world as single_length_world +from .grok_loop_model import LoopGPT, flops +from .latent_scaling import model_digest +from .storage_composition import FullTokenStep, file_hash +from .storage_frontier import learning_rate + +BOS, EOS, PAD, ENTITY_OFFSET = 2, 1, 0, 3 +HOPS = (2, 3, 4) +TRAIN_SPLITS = ("atomic", "train_2", "train_3", "train_4") +EVALUATION_SPLITS = ("atomic",) + tuple( + f"{split}_{hop}" for hop in HOPS for split in ("train", "familiar", "strict") +) +DATA_DEFAULTS = { + "entities": 64, + "relations": 4, + "degree": 4, + "phi": 4.0, + "id_fraction": 0.75, + "id_test_fraction": 0.2, + "evaluation_size": 512, +} +SOURCE_FILES = [ + "src/llm_memory_editability/bios_model.py", + "src/llm_memory_editability/grok_depth.py", + "src/llm_memory_editability/grok_depth_data.py", + "src/llm_memory_editability/grok_loop_data.py", + "src/llm_memory_editability/grok_multihop_data.py", + "src/llm_memory_editability/grok_loop_model.py", + "src/llm_memory_editability/latent_scaling.py", + "src/llm_memory_editability/storage_composition.py", + "src/llm_memory_editability/storage_frontier.py", + "src/llm_memory_editability/text_pretrain.py", + "src/llm_memory_editability/depth_step.py", + "scripts/run_depth_step.py", + "tests/test_depth_step.py", +] + + +def data_digest(world): + digest = hashlib.sha256() + for name in EVALUATION_SPLITS: + rows = world[name] + digest.update(name.encode()) + digest.update(np.asarray(rows.shape, dtype="= relation_offset)): + raise ValueError("Invalid entity token: " + name) + if np.any( + (rows[:, 1:-1] < relation_offset) | (rows[:, 1:-1] >= relation_offset + relations) + ): + raise ValueError("Invalid relation token: " + name) + if len(set(map(tuple, rows[:, :-1]))) != len(rows): + raise ValueError("Duplicate complete query: " + name) + _, edges = truth_path_details(world, rows) + if name.startswith(("train_", "familiar_")) and not id_mask[edges].all(): + raise ValueError("Non-ID fact in familiar training/test: " + name) + if name.startswith("strict_") and id_mask[edges].any(): + raise ValueError("ID fact in strict composition: " + name) + counts[name] = len(rows) + if len(world["atomic"]) != entities * meta["degree"]: + raise ValueError("Atomic graph degree does not match the contract") + for hop in HOPS: + query_sets = [ + set(map(tuple, world[f"{split}_{hop}"][:, :-1])) + for split in ("train", "familiar", "strict") + ] + if any(query_sets[i] & query_sets[j] for i in range(3) for j in range(i)): + raise ValueError("Complete query leakage between length-specific splits") + trained_edges = set() + for hop in HOPS: + trained_edges.update(truth_path_details(world, world[f"train_{hop}"])[1].ravel()) + for hop in HOPS: + strict_edges = set(truth_path_details(world, world[f"strict_{hop}"])[1].ravel()) + if strict_edges & trained_edges: + raise ValueError("Strict facts participated in another length's composition training") + digest = data_digest(world) + if "dataset_sha256" in meta and meta["dataset_sha256"] != digest: + raise ValueError("Frozen dataset digest differs from actual arrays") + return { + "passed": True, + "counts": counts, + "dataset_sha256": digest, + "truth_edges_independently_traversed": True, + "complete_query_overlap": 0, + "all_strict_facts_absent_from_composition_training": True, + "cross_length_subpath_holdout": False, + } + + +def build_world(spec): + seed = spec.get("world_seed", spec.get("world")) + if seed is None: + raise ValueError("A fixed world_seed is required") + settings = {key: spec.get(key, value) for key, value in DATA_DEFAULTS.items()} + world, shared_atoms, shared_ids = {}, None, None + source_metadata = {} + for hop in HOPS: + original = single_length_world({"world_seed": seed, "hops": hop, **settings}) + # The historical graph reserves only PAD/EOS and uses entity offset 2. + # Shift every entity/relation token once to reserve the explicit BOS=2. + atoms = original["atomic"] + 1 + id_set = set(map(tuple, original["id_atomic"])) + id_mask = np.asarray([tuple(row) in id_set for row in original["atomic"]], dtype=bool) + if shared_atoms is None: + shared_atoms, shared_ids = atoms.copy(), id_mask.copy() + elif not np.array_equal(shared_atoms, atoms) or not np.array_equal(shared_ids, id_mask): + raise ValueError("Path lengths do not share identical graph and ID mask") + world[f"train_{hop}"] = original["train_composite"] + 1 + world[f"familiar_{hop}"] = original["test_full_composite"] + 1 + world[f"strict_{hop}"] = original["ood_composite"] + 1 + source_metadata[str(hop)] = original["metadata"] + world["atomic"] = shared_atoms + world["metadata"] = { + "world_seed": int(seed), + **settings, + "id_mask": shared_ids.tolist(), + "source_worlds": source_metadata, + "same_atomic_and_id_mask_all_lengths": True, + "source_entity_offset": 2, + "entity_offset": ENTITY_OFFSET, + "source_token_shift": 1, + "separator_token": ENTITY_OFFSET + settings["entities"] + settings["relations"], + "vocab_size": ENTITY_OFFSET + settings["entities"] + settings["relations"] + 1, + "evaluation_pools": "Complete test_full_composite and ood_composite", + "composition_supervision": "Terminal entity only; no intermediate entity", + "training_objective": "All nonpadding next tokens including EOS", + "holdout": "Complete queries held out within each length; not subpaths across lengths", + } + report = audit_world(world) + world["metadata"]["dataset_sha256"] = report["dataset_sha256"] + world["metadata"]["independent_audit"] = report + expected = spec.get("frozen_data_sha256") + if expected is not None and expected != report["dataset_sha256"]: + raise ValueError("Rebuilt data differ from the frozen specification") + return world + + +def construct(spec, device): + if spec.get("context", 9) < 9: + raise ValueError("Context must support four-hop answer and EOS") + config = ModelConfig( + vocab_size=ENTITY_OFFSET + spec.get("entities", 64) + spec.get("relations", 4) + 1, + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=spec.get("context", 9), + ) + if config.layers > 6: + raise ValueError("Canonical paired initialization is limited to six unique blocks") + torch.manual_seed(spec["initialization"]) + canonical = LoopGPT( + replace(config, layers=6), + repeats=1, + dropout=spec.get("dropout", 0.0), + initialization="scaled_effective", + ) + model = LoopGPT( + config, + repeats=spec["repeats"], + dropout=spec.get("dropout", 0.0), + initialization="scaled_effective", + ) + initial = canonical.state_dict() + state = {} + factor = math.sqrt(6 / (config.layers * spec["repeats"])) + for key in model.state_dict(): + value = initial[key].clone() + if key.endswith(("attention.proj.weight", "mlp.down.weight")): + value.mul_(factor) + state[key] = value + model.load_state_dict(state) + return model.to(device) + + +def prompt_rows(rows, separator=71): + rows = np.asarray(rows, dtype=np.int64) + return np.c_[ + np.full(len(rows), BOS, dtype=np.int64), + rows[:, :-1], + np.full(len(rows), separator, dtype=np.int64), + ] + + +def pack_rows(rows, sequence=8, separator=71): + """All nonpadding next-token labels; compact rows contain no intermediate nodes.""" + rows = np.asarray(rows, dtype=np.int64) + sentence = np.c_[ + prompt_rows(rows, separator), rows[:, -1], np.full(len(rows), EOS, dtype=np.int64) + ] + length = sentence.shape[1] - 1 + if length > sequence: + raise ValueError("Packed sequence is too short") + tokens = np.zeros((len(rows), sequence), dtype=np.int64) + labels = np.full_like(tokens, -100) + tokens[:, :length], labels[:, :length] = sentence[:, :-1], sentence[:, 1:] + return tokens, labels + + +def run_name(spec): + seed = spec.get("world_seed", spec.get("world")) + return ( + f"w{seed}-i{spec['initialization']}-d{spec['width']}" + f"-l{spec['layers']}-r{spec['repeats']}-s{spec['steps']}" + ) + + +def _mean(values): + return float(np.asarray(values).mean()) if len(values) else None + + +@torch.no_grad() +def generate_rows(model, rows, device, separator=71, batch_size=512): + """Ordinary full forward, then free tail/EOS generation with answer feedback.""" + rows = np.asarray(rows, dtype=np.int64) + generated, nll = [], [] + for start in range(0, len(rows), batch_size): + batch = rows[start : start + batch_size] + tokens = torch.as_tensor(prompt_rows(batch, separator), device=device) + first = model(tokens)[:, -1] + target = torch.as_tensor(batch[:, -1], device=device) + nll.append(F.cross_entropy(first, target, reduction="none").cpu().numpy()) + answer = first.argmax(-1) + tokens = torch.cat([tokens, answer[:, None]], dim=1) + stop = model(tokens)[:, -1].argmax(-1) + generated.append(torch.stack([answer, stop], dim=1).cpu().numpy()) + pred = np.concatenate(generated) if generated else np.empty((0, 2), dtype=np.int64) + nll = np.concatenate(nll) if nll else np.empty(0, dtype=np.float32) + answer_correct = pred[:, 0] == rows[:, -1] + correct = answer_correct & (pred[:, 1] == EOS) + return { + "n": len(rows), + "accuracy": _mean(correct), + "answer_accuracy": _mean(answer_correct), + "answer_nll": _mean(nll), + }, {"generated": pred, "correct": correct, "answer_nll": nll} + + +@torch.no_grad() +def evaluate(model, world, device): + before = model.training + model.eval() + metrics, predictions = {}, {} + separator = world["metadata"]["separator_token"] + try: + atomic_metrics, atomic_pred = generate_rows(model, world["atomic"], device, separator) + metrics["atomic"] = atomic_metrics + predictions.update({"atomic_" + key: value for key, value in atomic_pred.items()}) + for name in EVALUATION_SPLITS[1:]: + rows = world[name] + task_metrics, direct = generate_rows(model, rows, device, separator) + nodes, edges = truth_path_details(world, rows) + coverage = atomic_pred["correct"][edges].all(axis=1) + current = rows[:, 0].copy() + hops = rows.shape[1] - 2 + calls = np.empty((len(rows), hops, 2), dtype=np.int64) + for hop in range(hops): + query = np.c_[current, rows[:, hop + 1], nodes[:, hop + 1]] + _, result = generate_rows(model, query, device, separator) + calls[:, hop] = result["generated"] + current = result["generated"][:, 0] + formats = (calls[:, :, 1] == EOS).all(axis=1) + autonomous_correct = formats & (current == rows[:, -1]) + path_correct = formats & (calls[:, :, 0] == nodes[:, 1:]).all(axis=1) + task_metrics.update( + { + "atomic_correct_coverage": _mean(coverage), + "conditional_accuracy": _mean(direct["correct"][coverage]), + "autonomous_two_calls": _mean(autonomous_correct), + "autonomous_path_accuracy": _mean(path_correct), + "hop_count": hops, + } + ) + metrics[name] = task_metrics + direct.update( + { + "coverage": coverage, + "autonomous_generated": calls, + "autonomous_correct": autonomous_correct, + "autonomous_path_correct": path_correct, + } + ) + predictions.update({name + "_" + key: value for key, value in direct.items()}) + finally: + model.train(before) + return metrics, predictions + + +def _validate_spec(spec): + nodes = spec["nodes"] + if nodes != sorted(set(nodes)) or nodes[0] != 0 or nodes[-1] != spec["steps"]: + raise ValueError("Nodes must increase from initialization to the fixed endpoint") + if not set(spec["checkpoint_nodes"]) <= set(nodes) or not {0, spec["steps"]} <= set( + spec["checkpoint_nodes"] + ): + raise ValueError("Checkpoint nodes must include initialization and endpoint") + if spec["batch_size"] != 128 or spec.get("dropout", 0.0) != 0.0: + raise ValueError("The fixed design requires four 32-example streams and dropout zero") + if spec.get("model_initialization", "scaled_effective") != "scaled_effective": + raise ValueError("The batch uses scaled_effective residual initialization") + + +def _save_world(out, world): + np.savez_compressed(out / "world.npz", **{key: world[key] for key in EVALUATION_SPLITS}) + write_json(out / "world-metadata.json", world["metadata"]) + + +def _check_source(source): + if not source or any(file_hash(path) != digest for path, digest in source.items()): + raise RuntimeError("Actual source differs from the required frozen source hashes") + + +def _validate_output(out): + """Permit scheduler control files while preserving every existing experiment artifact.""" + out = Path(out) + if out.exists(): + for path in out.iterdir(): + allowed = path.is_file() and ( + path.name == "input-spec.json" or path.name.endswith("-process.log") + ) + if not allowed: + raise FileExistsError( + "Do not overwrite an existing experiment artifact: " + str(path) + ) + + +def train(spec, out, source, device="cuda:0"): + _validate_spec(spec) + _check_source(source) + if "frozen_data_sha256" not in spec: + raise ValueError("Training requires frozen_data_sha256") + out = Path(out) + _validate_output(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(torch.device(device)) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + started_process = time.perf_counter() + world = build_world(spec) + digest = data_digest(world) + _save_world(out, world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_digest = model_digest(model) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + strata = [world[name] for name in TRAIN_SPLITS] + sizes = [len(rows) for rows in strata] + if any(size == 0 for size in sizes): + raise ValueError("Do not reroll a world with an empty sampled training stratum") + packed = [pack_rows(rows, separator=world["metadata"]["separator_token"]) for rows in strata] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True) + ) + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + graph = FullTokenStep(model, optimizer, table, spec["batch_size"], clip=spec.get("clip", 1.0)) + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 8, output_positions=8) + token_step = 32 * sum(int((labels[0] >= 0).sum()) for _, labels in packed) + history, step, training_seconds = [], 0, 0.0 + + def measure(loss=None): + metrics, predictions = evaluate(model, world, device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0.0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + np.savez_compressed( + out / f"exposures-{step:06d}.npz", + **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, + ) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["checkpoint_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"model-{step:06d}.pt", + ) + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["atomic"]["accuracy"], + "familiar": {str(hop): metrics[f"familiar_{hop}"]["accuracy"] for hop in HOPS}, + } + ), + flush=True, + ) + return row + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize() + started = time.perf_counter() + while step < end: + updates = min(128, end - step) + indices = [] + for i, stream in enumerate(streams): + draws = stream.take(updates * 32).reshape(updates, 32) + counts[i] += np.bincount(draws.ravel(), minlength=sizes[i]) + indices.append(draws + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(updates): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += updates + torch.cuda.synchronize() + training_seconds += time.perf_counter() - started + loss_value = float(loss) + if not np.isfinite(loss_value): + raise FloatingPointError("Nonfinite loss at step " + str(step)) + endpoint = measure(loss_value) + np.savez_compressed( + out / "exposures.npz", + **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, + ) + result = { + "spec": spec, + "source": source, + "data_sha256": digest, + "initial_model_sha256": initial_digest, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "strata_counts": dict(zip(TRAIN_SPLITS, sizes, strict=True)), + "endpoint": endpoint, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + "estimated_training_flops": step * flop_step, + "training_seconds": training_seconds, + "process_seconds": time.perf_counter() - started_process, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device), + "tf32": True, + }, + } + write_json(out / "complete.json", result) + return result + + +def compare_metrics(actual, expected): + if set(actual) != set(expected): + raise AssertionError("Metric task keys differ") + for task, values in actual.items(): + if set(values) != set(expected[task]): + raise AssertionError("Metric field keys differ") + for key, value in values.items(): + if key == "answer_nll" and value is not None: + np.testing.assert_allclose(value, expected[task][key], rtol=1e-5, atol=1e-5) + elif value != expected[task][key]: + raise AssertionError(f"Saved metric differs: {task}.{key}") + + +def compare_predictions(actual, path): + maximum = 0.0 + with np.load(path) as saved: + if set(actual) != set(saved.files): + raise AssertionError("Prediction keys differ") + for key, value in actual.items(): + if key.endswith("answer_nll"): + np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) + if value.size: + maximum = max(maximum, float(np.abs(value - saved[key]).max())) + else: + np.testing.assert_array_equal(value, saved[key]) + return maximum + + +def audit(out, device="cuda:0"): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(torch.device(device)) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + result = json.loads((out / "complete.json").read_text()) + recorded = json.loads((out / "spec.json").read_text()) + source, spec = result["source"], result["spec"] + _check_source(source) + _validate_spec(spec) + if recorded["spec"] != spec or recorded["source"] != source: + raise AssertionError("Recorded specification/source differ") + if file_hash(out / "latest.pt") != result["checkpoint_sha256"]: + raise AssertionError("Latest checkpoint hash differs") + world = build_world(spec) + digest = data_digest(world) + if digest != result["data_sha256"] or digest != recorded["data_sha256"]: + raise AssertionError("Rebuilt data differ from records") + if json.loads((out / "world-metadata.json").read_text()) != world["metadata"]: + raise AssertionError("Archived world metadata differ") + with np.load(out / "world.npz") as archived: + if set(archived.files) != set(EVALUATION_SPLITS): + raise AssertionError("Archived world keys differ") + for name in EVALUATION_SPLITS: + np.testing.assert_array_equal(archived[name], world[name]) + model = construct(spec, device) + if model_digest(model) != result["initial_model_sha256"]: + raise AssertionError("Paired initialization differs") + history = json.loads((out / "learning.json").read_text()) + if [row["step"] for row in history] != spec["nodes"]: + raise AssertionError("Recorded learning nodes differ") + by_node = {row["step"]: row for row in history} + if by_node[spec["steps"]] != result["endpoint"]: + raise AssertionError("Endpoint differs from the learning curve") + maximum = 0.0 + for node in spec["checkpoint_nodes"]: + checkpoint = torch.load( + out / f"model-{node:06d}.pt", map_location=device, weights_only=False + ) + if checkpoint["spec"] != spec or checkpoint["step"] != node: + raise AssertionError("Checkpoint specification/node differ") + model.load_state_dict(checkpoint["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, by_node[node]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{node:06d}.npz") + ) + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if ( + saved["spec"] != spec + or saved["source"] != source + or saved["step"] != spec["steps"] + or saved["data_sha256"] != digest + ): + raise AssertionError("Latest state identity differs") + sizes = [len(world[name]) for name in TRAIN_SPLITS] + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + previous = 0 + for node in spec["nodes"]: + for i, stream in enumerate(streams): + draws = ( + stream.take((node - previous) * 32) + if node > previous + else np.empty(0, dtype=np.int64) + ) + counts[i] += np.bincount(draws, minlength=sizes[i]) + with np.load(out / f"exposures-{node:06d}.npz") as actual: + for name, count in zip(TRAIN_SPLITS, counts, strict=True): + np.testing.assert_array_equal(actual[name], count) + previous = node + with np.load(out / "exposures.npz") as actual: + for i, (name, count) in enumerate(zip(TRAIN_SPLITS, counts, strict=True)): + np.testing.assert_array_equal(actual[name], count) + np.testing.assert_array_equal(saved["counts"][i], count) + if count.sum() != spec["steps"] * 32 or np.ptp(count) > 1: + raise AssertionError("EpochStream actual exposures are unbalanced") + stream = EpochStream(sizes[i], spec["stream_seed"] + i) + stream.load_state_dict(saved["streams"][i]) + np.testing.assert_array_equal(stream.take(32), streams[i].take(32)) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, result["endpoint"]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{spec['steps']:06d}.npz") + ) + checked = { + "passed": True, + "dataset_rebuilt_and_archived_exact": True, + "initial_model_exact": True, + "checkpoint_nodes": spec["checkpoint_nodes"], + "endpoint_tokens_exact": True, + "all_nodes_exposure_counters_exact": True, + "stream_state_continuation_exact": True, + "max_nll_difference": maximum, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "utc": utc(), + } + write_json(out / "audit.json", checked) + return checked diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..fc14c085184dc030670f1eea92655b73d0eec7c8 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py @@ -0,0 +1,371 @@ +"""Answer-only MLP editing calibration with frozen parent-logit regularization. + +This development grid changes the editor objective and learning rate, preserving +the completed v1 experiment. KL on a finite replay set is a regularizer, not an +exact preservation constraint. Kdev checks the operation; U never selects it. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import EOS, pack_rows +from .depth_step import SOURCE_FILES as TRAIN_SOURCES +from .depth_step_mechanism import edit_cases, generate +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import file_hash + +SOURCE_FILES = list( + dict.fromkeys( + [ + *TRAIN_SOURCES, + "src/llm_memory_editability/depth_step_mechanism.py", + "src/llm_memory_editability/depth_step_edit_calibration.py", + "scripts/calibrate_depth_step_edit.py", + "tests/test_depth_step_edit_calibration.py", + ] + ) +) +PARAMETER = "blocks.0.mlp.down.weight" +NODES = (0, 20, 100, 200) +LEARNING_RATES = (0.0001, 0.001, 0.003) + + +def _array_hash(array): + array = np.asarray(array) + digest = hashlib.sha256(str(array.dtype).encode()) + digest.update(np.asarray(array.shape, dtype="answer and teacher-forced answer->EOS supervision.""" + rows = np.asarray(rows, dtype=np.int64) + tokens, labels = pack_rows(rows, separator=world["metadata"]["separator_token"]) + positions = np.tile([rows.shape[1], rows.shape[1] + 1], (len(rows), 1)) + batch_indices = np.arange(len(rows))[:, None] + selected = labels[batch_indices, positions] + if not np.array_equal(selected, np.c_[rows[:, -1], np.full(len(rows), EOS)]): + raise ValueError("Answer/EOS positions disagree with the packed sequence") + return tuple(torch.as_tensor(value, device=device) for value in (tokens, positions, selected)) + + +def answer_eos_logits(model, batch): + tokens, positions, _labels = batch + return model(tokens, positions=positions) + + +def target_and_replay_loss(model, target_batch, replay_batch, parent_log_probabilities): + """CE only on two factual-output tokens; KL(parent || edited), equally weighted.""" + if parent_log_probabilities.requires_grad: + raise ValueError("Parent logits must be detached") + target_logits = answer_eos_logits(model, target_batch) + ce = F.cross_entropy(target_logits.flatten(0, 1), target_batch[2].flatten()) + replay_log = answer_eos_logits(model, replay_batch).log_softmax(-1) + kl = F.kl_div( + replay_log.flatten(0, 1), + parent_log_probabilities.flatten(0, 1), + reduction="batchmean", + log_target=True, + ) + return ce + kl, ce, kl + + +def _measure(model, case, world, device, step): + metrics, raw = {}, {} + for name, rows in case["tasks"].items(): + values, predictions = generate(model, rows, world, device) + if name in case["original_d_rows"]: + original = case["original_d_rows"][name] + changed = rows[:, -1] != original[:, -1] + predicted = predictions["predictions"] + correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) + old_correct = (predicted[:, 0] == original[:, -1]) & (predicted[:, 1] == EOS) + values.update( + { + "changed_answer_n": int(changed.sum()), + "changed_answer_coverage": float(changed.mean()) if len(rows) else None, + "changed_answer_accuracy": float(correct[changed].mean()) + if changed.any() + else None, + "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None, + } + ) + metrics[name] = values + raw.update({f"step{step}_{name}_{key}": value for key, value in predictions.items()}) + return metrics, raw + + +def calibrated_edit_one(model, case, world, device, arm, lr, nodes=NODES): + """One independently initialized branch, with fixed parent KL reference.""" + if arm not in {"edit", "review"}: + raise ValueError("Arm must be edit or review") + if tuple(nodes) != tuple(sorted(set(nodes))) or not nodes or nodes[0] != 0: + raise ValueError("Nodes must increase from zero") + parent_hash = model_digest(model) + edited = copy.deepcopy(model).eval() + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == PARAMETER) + parameter.grad = None + before = {name: value.detach().clone() for name, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[PARAMETER] + optimizer = torch.optim.Adam([parameter], lr=lr) + target_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) + target_batch = answer_eos_batch(target_rows, world, device) + replay_batch = answer_eos_batch(case["tasks"]["R_atomic"], world, device) + with torch.no_grad(): + parent_log = answer_eos_logits(model, replay_batch).log_softmax(-1).detach() + raw = { + "parent_replay_log_probabilities": parent_log.cpu().numpy(), + "replay_teacherforced_labels": replay_batch[2].cpu().numpy(), + } + for name, old_rows in case["original_d_rows"].items(): + raw[name + "_original_rows"] = old_rows + raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] + step, history, loss_values = 0, [], None + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, ce, kl = target_and_replay_loss(edited, target_batch, replay_batch, parent_log) + loss.backward() + optimizer.step() + step += 1 + loss_values = { + "total": float(loss.detach()), + "target_ce": float(ce.detach()), + "replay_kl": float(kl.detach()), + } + metrics, predictions = _measure(edited, case, world, device, step) + raw.update(predictions) + target_name = "E_new" if arm == "edit" else "E_old" + keep_pass = metrics["Kdev_atomic"]["accuracy"] >= 0.95 + target_pass = metrics[target_name]["accuracy"] == 1.0 + history.append( + { + "step": step, + "loss": loss_values, + "metrics": metrics, + "Kdev_at_least_95_percent": keep_pass, + "target_atomic_success": target_pass, + "calibration_operation_pass": keep_pass and target_pass, + } + ) + changed = [ + name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) + ] + if set(changed) - {PARAMETER}: + raise ValueError("A frozen state tensor changed") + if model_digest(model) != parent_hash: + raise ValueError("Original checkpoint model changed") + delta = parameter.detach() - before[PARAMETER] + raw["mlp_down_weight_delta"] = delta.cpu().numpy() + record = { + "arm": arm, + "lr": lr, + "atomic_index": case["atomic_index"], + "old_fact": case["old_fact"], + "new_fact": case["new_fact"], + "replay_indices": case["replay_indices"], + "keep_dev_indices": case["keep_dev_indices"], + "unused_atomic_indices": case["unused_atomic_indices"], + "parent_model_sha256": parent_hash, + "final_model_sha256": model_digest(edited), + "initial_down_weight_sha256": _array_hash(before[PARAMETER].cpu().numpy()), + "final_down_weight_sha256": _array_hash(parameter.detach().cpu().numpy()), + "updated_parameter": PARAMETER, + "changed_state_tensors": changed, + "weight_delta_l2": float(delta.norm()), + "history": history, + } + return record, raw + + +def prepare_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): + """Freeze data, all arms, sources, and initial weights before any model inference.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + if any(lr <= 0 or not np.isfinite(lr) for lr in learning_rates): + raise ValueError("Invalid learning rate") + cases, remaining = calibration_cases(world, n_cases=n_cases) + serialized = [] + for case in cases: + entry = { + key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"} + } + entry["task_rows"] = {key: value.tolist() for key, value in case["tasks"].items()} + entry["task_sha256"] = {key: _array_hash(value) for key, value in case["tasks"].items()} + entry["original_d_rows"] = { + key: value.tolist() for key, value in case["original_d_rows"].items() + } + serialized.append(entry) + config = { + "phase": "development_calibration", + "created_utc": utc(), + "source_checkpoint": source, + "source": {path: file_hash(path) for path in SOURCE_FILES}, + "parent_model_sha256": model_digest(model), + "initial_down_weight_sha256": _array_hash( + model.blocks[0].mlp.down.weight.detach().cpu().numpy() + ), + "learning_rates": list(learning_rates), + "nodes": list(NODES), + "cases": serialized, + "n_cases": n_cases, + "matrix": [ + {"case": i, "lr": lr, "arm": arm} + for i in range(n_cases) + for lr in learning_rates + for arm in ("edit", "review") + ], + "reserved_original_case_indices": remaining, + "reserved_cases_are_independent_world_confirmation": False, + "optimizer": "Adam, no weight decay", + "parameter": PARAMETER, + "objective": "target answer/EOS CE + KL(parent || edited) on 32 replay answer/EOS logits", + "replay_kl_weight": 1.0, + "supervised_prefix_tokens": 0, + "trained_compositions": 0, + "Kdev_selection": "First 32 lexicographic atoms excluding E, R, necessary successors", + "Kdev_threshold": 0.95, + "U_selection": "All remaining atomic facts, including unused necessary successors", + "U_or_D_select_editor": False, + "all_grid_failures_retained": True, + "executions_affected_by_shared_edit": model.repeats, + "limits": [ + "Finite replay KL is not strict output preservation", + "A successful Kdev check does not establish unobserved U preservation", + "Cases share one development world and original checkpoints", + ], + } + write_json(out / "calibration-config.json", config) + return config, cases + + +def load_prepared_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): + """Validate an existing prepared configuration, without rewriting it.""" + out = Path(out) + config_file = out / "calibration-config.json" + config = json.loads(config_file.read_text()) + if any(path.name != config_file.name for path in out.iterdir()): + raise FileExistsError("Existing branch artifacts prevent a repeated execution") + if config["learning_rates"] != list(learning_rates) or config["n_cases"] != n_cases: + raise ValueError("Requested grid differs from prepared calibration") + expected_source = config["source_checkpoint"] + for key in ("checkpoint_sha256", "dataset_sha256", "step", "spec"): + if source[key] != expected_source[key]: + raise ValueError("Checkpoint or data differ from prepared calibration: " + key) + if model_digest(model) != config["parent_model_sha256"]: + raise ValueError("Parent parameter hash differs from prepared calibration") + expected_matrix = [ + {"case": i, "lr": lr, "arm": arm} + for i in range(n_cases) + for lr in learning_rates + for arm in ("edit", "review") + ] + if config["matrix"] != expected_matrix or config["nodes"] != list(NODES): + raise ValueError("Prepared update matrix or nodes changed") + if ( + config["parameter"] != PARAMETER + or config["replay_kl_weight"] != 1.0 + or config["Kdev_threshold"] != 0.95 + or config["U_or_D_select_editor"] + ): + raise ValueError("Prepared operation contract changed") + cases, remaining = calibration_cases(world, n_cases=n_cases) + if remaining != config["reserved_original_case_indices"]: + raise ValueError("Reserved cases changed") + for case, frozen in zip(cases, config["cases"], strict=True): + for key in ( + "atomic_index", + "old_fact", + "new_fact", + "replay_indices", + "keep_dev_indices", + "unused_atomic_indices", + "propagation_scope", + ): + if case[key] != frozen[key]: + raise ValueError("Case selection changed: " + key) + if set(case["tasks"]) != set(frozen["task_rows"]): + raise ValueError("Prepared task set changed") + for name, rows in case["tasks"].items(): + if ( + rows.tolist() != frozen["task_rows"][name] + or _array_hash(rows) != frozen["task_sha256"][name] + ): + raise ValueError("Prepared task rows changed: " + name) + for name, rows in case["original_d_rows"].items(): + if rows.tolist() != frozen["original_d_rows"][name]: + raise ValueError("Prepared original D labels changed") + for path, expected in config["source"].items(): + if file_hash(path) != expected: + raise ValueError("Source changed after calibration freeze: " + path) + return config, cases + + +def execute_calibration(model, world, config, cases, out, device): + out = Path(out) + if model_digest(model) != config["parent_model_sha256"]: + raise ValueError("Parent parameter hash differs from frozen configuration") + for path, expected in config["source"].items(): + if file_hash(path) != expected: + raise ValueError("Source changed after calibration freeze: " + path) + for case, expected in zip(cases, config["cases"], strict=True): + for name, rows in case["tasks"].items(): + if _array_hash(rows) != expected["task_sha256"][name]: + raise ValueError("Task rows changed after freeze: " + name) + started = time.perf_counter() + records = [] + for item in config["matrix"]: + number, lr, arm = item["case"], item["lr"], item["arm"] + record, raw = calibrated_edit_one( + model, cases[number], world, device, arm, lr, nodes=tuple(config["nodes"]) + ) + label = f"case{number:02d}-lr{lr:.4f}-{arm}" + np.savez_compressed(out / (label + "-raw.npz"), **raw) + write_json(out / (label + ".json"), record) + records.append(record) + print(f"Calibration branch completed: {label}", flush=True) + report = { + "phase": "development_calibration", + "records": records, + "config_sha256": file_hash(out / "calibration-config.json"), + "completed_branches": len(records), + "wall_seconds": time.perf_counter() - started, + "model_selection_by_U_or_D": False, + } + write_json(out / "calibration-summary.json", report) + return report diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/depth_step_mechanism.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/depth_step_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb78cafec65ea5b0a4031d27502f7d0c4b00e16 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/depth_step_mechanism.py @@ -0,0 +1,589 @@ +"""Descriptive entity readouts, pure-first-hop interventions and MLP edits. + +No fitted probe or performance predictor is used. Residual readouts and raw MLP +cosines are descriptions; only interventions test a causal contribution. The +truth graph chooses queries, donors and edits before any model is evaluated. +""" + +from __future__ import annotations + +import copy +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import ENTITY_OFFSET, EOS, construct, pack_rows, prompt_rows, truth_path_details +from .grok_depth import utc, write_json +from .storage_composition import file_hash + + +def traced_forward(model, tokens, patches=None): + """Use the real SDPA computation and record every executed block/position. + + Patches map (zero-based execution, 'mlp_delta' or 'postresidual', position) + to a batch of replacement vectors. Repeated executions of a shared block + remain separately indexed. Attention maps are descriptive manual softmax; + the forward uses the same SDPA primitive as LoopGPT. + """ + if model.training: + raise ValueError("Tracing requires evaluation mode") + patches = patches or {} + length = tokens.shape[1] + x = model.token(tokens) + model.position(torch.arange(length, device=tokens.device)) + cache = {key: [] for key in ("attention_map", "attention_delta", "mlp_delta", "postresidual")} + consumed = set() + for index, block in enumerate(model.iter_blocks()): + z = block.ln1(x) + batch, _, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + q, k, v = (part.transpose(1, 2) for part in (q, k, v)) + scores = (q @ k.transpose(-1, -2)) / math.sqrt(width // a.heads) + causal = torch.ones(length, length, device=tokens.device, dtype=torch.bool).tril() + attention_map = scores.masked_fill(~causal, -torch.inf).softmax(-1) + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0.0) + attention_delta = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + attention_delta + mlp_delta = block.mlp(block.ln2(x)) + for key, replacement in patches.items(): + layer, component, position = key + if layer == index and component == "mlp_delta": + if replacement.shape != mlp_delta[:, position].shape: + raise ValueError("Patch shape differs from selected MLP position") + mlp_delta = mlp_delta.clone() + mlp_delta[:, position] = replacement + consumed.add(key) + x = x + mlp_delta + for key, replacement in patches.items(): + layer, component, position = key + if layer == index and component == "postresidual": + if replacement.shape != x[:, position].shape: + raise ValueError("Patch shape differs from selected residual position") + x = x.clone() + x[:, position] = replacement + consumed.add(key) + for key, value in ( + ("attention_map", attention_map), + ("attention_delta", attention_delta), + ("mlp_delta", mlp_delta), + ("postresidual", x), + ): + cache[key].append(value.detach()) + if consumed != set(patches): + raise ValueError("Unknown execution/component in patch") + logits = F.linear(model.ln_final(x), model.token.weight) + return logits, {key: torch.stack(values) for key, values in cache.items()} + + +def _separator(world): + return int(world["metadata"]["separator_token"]) + + +def _mean(values): + return float(np.mean(values)) if len(values) else None + + +@torch.no_grad() +def generate(model, rows, world, device, batch_size=256): + """Free answer then free EOS, retaining full-vocabulary probabilities.""" + rows = np.asarray(rows, dtype=np.int64) + predictions, probabilities, gold_probabilities = [], [], [] + for begin in range(0, len(rows), batch_size): + selected = rows[begin : begin + batch_size] + tokens = torch.as_tensor(prompt_rows(selected, _separator(world)), device=device) + probability = model(tokens)[:, -1].softmax(-1) + answer = probability.argmax(-1) + eos = model(torch.cat((tokens, answer[:, None]), dim=1))[:, -1].argmax(-1) + predictions.append(torch.stack((answer, eos), 1).cpu().numpy()) + probabilities.append(probability.cpu().numpy()) + gold_probabilities.append( + probability[ + torch.arange(len(selected), device=device), + torch.as_tensor(selected[:, -1], device=device), + ] + .cpu() + .numpy() + ) + vocab = model.config.vocab_size + predicted = np.concatenate(predictions) if predictions else np.empty((0, 2), dtype=np.int64) + prob = ( + np.concatenate(probabilities) if probabilities else np.empty((0, vocab), dtype=np.float32) + ) + gold_prob = np.concatenate(gold_probabilities) if gold_probabilities else np.empty(0) + correct = predicted[:, 0] == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": _mean(correct), + "accuracy": _mean(correct & (predicted[:, 1] == EOS)), + "gold_probability": _mean(gold_prob), + }, {"rows": rows, "predictions": predicted, "answer_probabilities": prob} + + +def select_donors(world, rows): + """Lexicographic donors know exactly one fact and no target second relation.""" + atoms = world["atomic"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + nodes, _ = truth_path_details(world, rows) + same, changed, changed_tail = [], [], [] + for row, path in zip(rows, nodes, strict=True): + h, r1, r2, old_tail = map(int, row) + bridge = int(path[1]) + identical = next( + (i for i in order if int(atoms[i, 2]) == bridge and tuple(atoms[i, :2]) != (h, r1)), -1 + ) + different = next( + ( + i + for i in order + if int(atoms[i, 2]) != bridge + and (int(atoms[i, 2]), r2) in lookup + and lookup[(int(atoms[i, 2]), r2)] != old_tail + ), + -1, + ) + same.append(identical) + changed.append(different) + changed_tail.append(lookup[(int(atoms[different, 2]), r2)] if different >= 0 else -1) + return { + "same_bridge_atomic_indices": np.asarray(same, dtype=np.int64), + "different_bridge_atomic_indices": np.asarray(changed, dtype=np.int64), + "different_bridge_tail": np.asarray(changed_tail, dtype=np.int64), + } + + +@torch.no_grad() +def entity_readouts(model, cache, targets, entities): + """Apply the unmodified final norm/tied readout; raw MLP cosine is separate.""" + residual = cache["postresidual"] + logits = F.linear(model.ln_final(residual), model.token.weight) + entity_logits = logits[..., ENTITY_OFFSET : ENTITY_OFFSET + entities] + probabilities = logits.softmax(-1) + entity_probabilities = entity_logits.softmax(-1) + embedding = F.normalize(model.token.weight[ENTITY_OFFSET : ENTITY_OFFSET + entities], dim=-1) + cosine = F.normalize(cache["mlp_delta"], dim=-1) @ embedding.T + arrays = {} + for name, token_ids in targets.items(): + ids = torch.as_tensor(token_ids, device=residual.device) + full_ids = ids[None, :, None, None].expand(*residual.shape[:-1], 1) + entity_ids = full_ids - ENTITY_OFFSET + gold_logit = entity_logits.gather(-1, entity_ids).squeeze(-1) + gold_cosine = cosine.gather(-1, entity_ids).squeeze(-1) + arrays[name + "_residual_entity_rank"] = 1 + (entity_logits > gold_logit[..., None]).sum(-1) + arrays[name + "_residual_vocab_probability"] = probabilities.gather(-1, full_ids).squeeze( + -1 + ) + arrays[name + "_residual_entity_probability"] = entity_probabilities.gather( + -1, entity_ids + ).squeeze(-1) + arrays[name + "_mlp_embedding_cosine"] = gold_cosine + arrays[name + "_mlp_embedding_cosine_rank"] = 1 + (cosine > gold_cosine[..., None]).sum(-1) + return {name: value.cpu().numpy() for name, value in arrays.items()} + + +@torch.no_grad() +def _patched_generation(model, tokens, patch): + logits, _ = traced_forward(model, tokens, patch) + probability = logits[:, -1].softmax(-1) + answer = probability.argmax(-1) + # Reapply the same intervention while freely generating the EOS token. + extended = torch.cat((tokens, answer[:, None]), dim=1) + eos_logits, _ = traced_forward(model, extended, patch) + eos = eos_logits[:, -1].argmax(-1) + return torch.stack((answer, eos), 1).cpu().numpy(), probability.cpu().numpy() + + +def trace_analysis(model, world, out, device, max_queries=128): + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + model.eval() + started = time.perf_counter() + raw, baseline = {}, {} + for split in ("atomic", "familiar_2", "strict_2"): + metrics, prediction = generate(model, world[split], world, device) + baseline[split] = metrics + raw.update({f"baseline_{split}_{key}": value for key, value in prediction.items()}) + indices = np.arange(min(max_queries, len(world["familiar_2"]))) + rows = world["familiar_2"][indices] + nodes, edges = truth_path_details(world, rows) + tokens = torch.as_tensor(prompt_rows(rows, _separator(world)), device=device) + with torch.no_grad(): + reference = model(tokens) + actual, cache = traced_forward(model, tokens) + difference = float((actual - reference).abs().max()) + torch.testing.assert_close(actual, reference, rtol=1e-5, atol=2e-6) + if not torch.equal(actual.argmax(-1), reference.argmax(-1)): + raise ValueError("Traced forward changes full-vocabulary argmax") + raw.update( + { + "query_indices": indices, + "query_rows": rows, + "truth_nodes": nodes, + "truth_atomic_indices": edges, + } + ) + raw.update({"cache_" + key: value.cpu().numpy() for key, value in cache.items()}) + raw.update( + entity_readouts( + model, + cache, + {"bridge": nodes[:, 1], "tail": nodes[:, -1]}, + world["metadata"]["entities"], + ) + ) + donors = select_donors(world, rows) + raw.update(donors) + atom_predictions = raw["baseline_atomic_predictions"] + atoms = world["atomic"] + atom_correct = (atom_predictions[:, 0] == atoms[:, -1]) & (atom_predictions[:, 1] == EOS) + atomic_key_indices = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)} + raw["original_constituent_atoms_correct"] = atom_correct[edges].all(1) + records = [] + for style in ("self", "same_bridge", "different_bridge"): + donor_ids = edges[:, 0] if style == "self" else donors[style + "_atomic_indices"] + valid = donor_ids >= 0 + selected = np.flatnonzero(valid) + if not len(selected): + continue + donor_rows = world["atomic"][donor_ids[valid]] + donor_tokens = torch.as_tensor(prompt_rows(donor_rows, _separator(world)), device=device) + with torch.no_grad(): + _, donor_cache = traced_forward(model, donor_tokens) + expected = ( + donors["different_bridge_tail"][valid] + if style == "different_bridge" + else rows[valid, -1] + ) + new_second_indices = np.asarray( + [ + atomic_key_indices[(int(donor[2]), int(query[2]))] + for donor, query in zip(donor_rows, rows[valid], strict=True) + ] + ) + premises = ( + atom_correct[edges[valid]].all(1) + & atom_correct[donor_ids[valid]] + & atom_correct[new_second_indices] + ) + raw[style + "_premises_correct"] = premises + for layer in range(model.effective_depth): + for component in ("mlp_delta", "postresidual"): + for position in (2, 1): + key = f"{style}_layer{layer}_{component}_pos{position}" + patch = { + (layer, component, position): donor_cache[component][layer, :, position] + } + prediction, probability = _patched_generation(model, tokens[valid], patch) + raw[key + "_selected_query_indices"] = selected + raw[key + "_predictions"] = prediction + raw[key + "_answer_probabilities"] = probability + following = prediction[:, 0] == expected + correct = prediction[:, 0] == rows[valid, -1] + base_pred = raw["baseline_familiar_2_predictions"][indices[valid]] + base_correct = (base_pred[:, 0] == rows[valid, -1]) & (base_pred[:, 1] == EOS) + if style == "self" and not np.array_equal(prediction, base_pred): + raise ValueError("Pure-first-hop self patch changes generation") + record = { + "donor": style, + "execution": layer, + "component": component, + "position": position, + "n": len(selected), + "selected_query_coverage": len(selected) / len(rows), + "full_pool_coverage": len(selected) / len(world["familiar_2"]), + "new_route_answer_accuracy": _mean(following), + "new_route_accuracy": _mean(following & (prediction[:, 1] == EOS)), + "original_accuracy": _mean(correct & (prediction[:, 1] == EOS)), + "baseline_correct_coverage": _mean(base_correct), + "all_required_atomic_correct_coverage": _mean(premises), + "new_route_conditional_on_required_atomics": _mean( + (following & (prediction[:, 1] == EOS))[premises] + ), + "new_route_conditional_on_baseline_correct": _mean( + (following & (prediction[:, 1] == EOS))[base_correct] + ), + } + records.append(record) + with torch.no_grad(): + entity_embedding = model.token.weight[ + ENTITY_OFFSET : ENTITY_OFFSET + world["metadata"]["entities"] + ] + normalized = F.normalize(entity_embedding, dim=-1) + raw["entity_embedding_cosine_matrix"] = (normalized @ normalized.T).cpu().numpy() + raw["entity_embedding_singular_values"] = ( + torch.linalg.svdvals(entity_embedding).cpu().numpy() + ) + np.savez_compressed(out / "trace-raw.npz", **raw) + report = { + "phase": "development", + "created_utc": utc(), + "baseline": baseline, + "query_selection": ( + "First 128 familiar_2 rows in frozen data order, independent of predictions" + ), + "selected_queries": len(rows), + "full_pool_queries": len(world["familiar_2"]), + "selection_coverage": len(rows) / len(world["familiar_2"]), + "forward_max_absolute_difference": difference, + "forward_all_argmax_identical": True, + "donor_information": ( + "Only BOS, head, first relation, SEP; no second relation or final answer" + ), + "patch_position_roles": {"1": "head control", "2": "first relation"}, + "interventions": records, + "wall_seconds": time.perf_counter() - started, + "limits": [ + "Unfitted final-norm tied readout and raw cosine are descriptive", + "Attention maps are descriptive; patch tests entire state or MLP contribution", + "Layers, positions and queries are dependent measurements in one world", + ], + } + write_json(out / "trace-summary.json", report) + return report + + +def edit_cases(world, n_facts=8, replay_n=32): + """Choose graph-based first-hop edits before observing any model behavior.""" + atoms = world["atomic"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + candidate_first = {(int(row[0]), int(row[1])) for row in world["familiar_2"]} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + cases = [] + for index in order: + h, relation, old_bridge = map(int, atoms[index]) + if (h, relation) not in candidate_first: + continue + first_rows = world["familiar_2"][ + (world["familiar_2"][:, 0] == h) & (world["familiar_2"][:, 1] == relation) + ] + bridges = sorted({int(t) for _, _, t in atoms}) + new_bridge = next( + ( + b + for b in bridges + if b != old_bridge + and all( + (b, int(row[2])) in lookup and lookup[(b, int(row[2]))] != int(row[-1]) + for row in first_rows + ) + ), + None, + ) + if new_bridge is None: + continue + replay_indices = np.asarray([i for i in order if i != index][:replay_n]) + if len(replay_indices) != replay_n: + raise ValueError("Insufficient nonedited replay atoms") + new_fact = np.asarray([[h, relation, new_bridge]], dtype=np.int64) + old_fact = atoms[index : index + 1].copy() + edited_lookup = {**lookup, (h, relation): new_bridge} + tasks = {"E_new": new_fact, "E_old": old_fact, "R_atomic": atoms[replay_indices].copy()} + original_d_rows = {} + unreplayed = [i for i in range(len(atoms)) if i != index and i not in replay_indices] + tasks["U_atomic"] = atoms[unreplayed].copy() + successor_keys = set() + for split in ("familiar_2", "strict_2"): + rows = world[split] + nodes, path_indices = truth_path_details(world, rows) + first = path_indices[:, 0] == index + second = (path_indices[:, 1] == index) & ~first + unaffected = ~(first | second) + for role, mask in (("first", first), ("second", second)): + changed = rows[mask].copy() + for i, row in enumerate(changed): + bridge = edited_lookup[(int(row[0]), int(row[1]))] + changed[i, -1] = edited_lookup[(bridge, int(row[2]))] + if role == "first" and (bridge, int(row[2])) != (h, relation): + successor_keys.add((bridge, int(row[2]))) + tasks[f"D_{role}_{split}"] = changed + original_d_rows[f"D_{role}_{split}"] = rows[mask].copy() + tasks["U_" + split] = rows[unaffected].copy() + # All facts occurring as either hop in U retain their graph labels. + if index in path_indices[unaffected]: + raise ValueError("Edited fact leaked into the unaffected holdout") + del nodes + successor_indices = [i for i, row in enumerate(atoms) if tuple(row[:2]) in successor_keys] + tasks["necessary_successor_atomic"] = atoms[successor_indices].copy() + cases.append( + { + "atomic_index": index, + "old_fact": old_fact[0].tolist(), + "new_fact": new_fact[0].tolist(), + "replay_indices": replay_indices.tolist(), + "tasks": tasks, + "original_d_rows": original_d_rows, + "propagation_scope": { + name: { + "n": len(old_rows), + "changed_answer_n": int( + np.count_nonzero(tasks[name][:, -1] != old_rows[:, -1]) + ), + "source_pool_n": len(world[name.split("_", 2)[2]]), + } + for name, old_rows in original_d_rows.items() + }, + } + ) + if len(cases) == n_facts: + break + if len(cases) != n_facts: + raise ValueError("Fewer graph-valid fixed edit cases than requested") + return cases + + +def _atomic_loss(model, rows, world, device): + tokens, labels = pack_rows(rows, separator=_separator(world)) + tokens = torch.as_tensor(tokens, device=device) + labels = torch.as_tensor(labels, device=device) + logits = model(tokens) + return F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + + +def edit_one(model, case, world, device, arm, nodes=(0, 20, 100, 200), lr=0.01): + """Independently edit one checkpoint; only unique block-0 MLP down changes.""" + if arm not in {"edit", "review"}: + raise ValueError("Arm must be edit or review") + if tuple(nodes) != tuple(sorted(set(nodes))) or nodes[0] != 0: + raise ValueError("Nodes must be increasing with initial measurement") + edited = copy.deepcopy(model).eval() + target_name = "blocks.0.mlp.down.weight" + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == target_name) + parameter.grad = None + before = {name: value.detach().clone() for name, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[target_name] + optimizer = torch.optim.Adam([parameter], lr=lr) + objective_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) + history, raw = [], {} + for name, old_rows in case["original_d_rows"].items(): + raw[name + "_original_rows"] = old_rows + raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] + step = 0 + final_loss = None + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + loss = 0.5 * _atomic_loss(edited, objective_rows, world, device) + loss = loss + 0.5 * _atomic_loss(edited, case["tasks"]["R_atomic"], world, device) + loss.backward() + optimizer.step() + step += 1 + final_loss = float(loss.detach()) + measures = {} + for name, rows in case["tasks"].items(): + metrics, prediction = generate(edited, rows, world, device) + if name in case["original_d_rows"]: + old_rows = case["original_d_rows"][name] + changed_mask = rows[:, -1] != old_rows[:, -1] + predicted = prediction["predictions"] + correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) + old_correct = (predicted[:, 0] == old_rows[:, -1]) & (predicted[:, 1] == EOS) + metrics.update( + { + "changed_answer_n": int(changed_mask.sum()), + "changed_answer_coverage": _mean(changed_mask), + "changed_answer_accuracy": _mean(correct[changed_mask]), + "old_answer_accuracy": _mean(old_correct), + } + ) + measures[name] = metrics + raw.update({f"step{step}_{name}_{key}": value for key, value in prediction.items()}) + history.append({"step": step, "loss": final_loss, "metrics": measures}) + changed = [ + name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) + ] + if set(changed) - {target_name}: + raise ValueError("Parameters outside the frozen MLP projection changed") + delta = parameter.detach() - before[target_name] + raw["mlp_down_weight_delta"] = delta.cpu().numpy() + return { + "arm": arm, + "atomic_index": case["atomic_index"], + "old_fact": case["old_fact"], + "new_fact": case["new_fact"], + "replay_indices": case["replay_indices"], + "propagation_scope": case["propagation_scope"], + "updated_parameter": target_name, + "changed_state_tensors": changed, + "weight_delta_l2": float(delta.norm()), + "history": history, + }, raw + + +def edit_analysis(model, world, out, device, n_facts=8, nodes=(0, 20, 100, 200), lr=0.01): + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + started = time.perf_counter() + cases = edit_cases(world, n_facts=n_facts) + serializable_cases = [ + {key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"}} + | {"task_sizes": {key: len(rows) for key, rows in case["tasks"].items()}} + for case in cases + ] + # This is written before evaluating or updating any case. + write_json(out / "data-selected-edit-cases.json", serializable_cases) + records = [] + for number, case in enumerate(cases): + for arm in ("edit", "review"): + record, raw = edit_one(model, case, world, device, arm, nodes=nodes, lr=lr) + np.savez_compressed(out / f"case{number:02d}-{arm}-raw.npz", **raw) + write_json(out / f"case{number:02d}-{arm}.json", record) + records.append(record) + report = { + "phase": "development", + "created_utc": utc(), + "n_facts": n_facts, + "nodes": list(nodes), + "lr": lr, + "optimizer": "Adam, no weight decay", + "objective": "0.5 target atomic full-token CE + 0.5 fixed 32-atomic replay full-token CE", + "trained_compositions": 0, + "unique_block_edited": 0, + "executions_affected_by_shared_edit": model.repeats, + "independent_layers": len(model.blocks), + "execution_depth": model.effective_depth, + "scope_difference": ( + "Loop block-0 update applies at every repeat; ordinary block-0 applies once" + ), + "records": records, + "wall_seconds": time.perf_counter() - started, + "limits": [ + "Edits use the same fixed budget; failed target changes remain in results", + "MLP-only parameter fine-tuning is not a constrained-preservation theorem", + "Each case independently starts from the same checkpoint", + "A single development world is not independent confirmation", + ], + } + write_json(out / "edit-summary.json", report) + return report + + +def load_run(run_dir, checkpoint, device): + run_dir, checkpoint = Path(run_dir), Path(checkpoint) + saved = torch.load(checkpoint, map_location=device, weights_only=False) + model = construct(saved["spec"], device).eval() + model.load_state_dict(saved["model"], strict=True) + arrays = np.load(run_dir / "world.npz", allow_pickle=False) + world = {key: arrays[key] for key in arrays.files} + world["metadata"] = json.loads((run_dir / "world-metadata.json").read_text()) + from .depth_step import audit_world + + audit = audit_world(world) + if audit["dataset_sha256"] != saved["spec"].get("frozen_data_sha256", audit["dataset_sha256"]): + raise ValueError("Checkpoint and archived data digest disagree") + return ( + model, + world, + { + "checkpoint": str(checkpoint), + "checkpoint_sha256": file_hash(checkpoint), + "step": saved["step"], + "spec": saved["spec"], + "dataset_sha256": audit["dataset_sha256"], + }, + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/experiment_tracking.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/experiment_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..167c8e1a359008fa8b7c89642273e85c9699643e --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/experiment_tracking.py @@ -0,0 +1,298 @@ +"""W&B sidecar for future experiments; reads trainer artifacts without changing training.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import importlib +import json +import math +import os +import subprocess +import sys +import time +from pathlib import Path + +DEFAULTS = Path(__file__).resolve().parents[2] / "configs/experiment-tracking-defaults.json" +PRIVATE_KEYS = { + "api_key", + "wandb_api_key", + "access_token", + "auth_token", + "password", + "credentials", + "secret", +} + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temp.replace(path) + + +def public_config(value): + if isinstance(value, dict): + return {k: public_config(v) for k, v in value.items() if k.lower() not in PRIVATE_KEYS} + if isinstance(value, list): + return [public_config(v) for v in value] + return value + + +def numeric_fields(value, prefix): + result = {} + for key, item in value.items(): + name = f"{prefix}/{key}" + if isinstance(item, dict): + result.update(numeric_fields(item, name)) + elif isinstance(item, int | float) and not isinstance(item, bool) and math.isfinite(item): + result[name] = item + return result + + +def learning_metrics(record, previous=None): + """Keep the actual optimizer step and task denominators; derive interval throughput.""" + result = {"training/step": int(record["step"])} + result.update(numeric_fields(record.get("metrics", {}), "eval")) + groups = { + "training_seconds": "perf/training_seconds", + "wall_seconds": "perf/wall_seconds", + "examples": "exposure/examples", + "supervised_tokens": "exposure/supervised_tokens", + "executed_input_tokens": "compute/executed_input_tokens", + "estimated_matmul_training_flops": "compute/estimated_matmul_training_flops", + "atomic_epochs": "exposure/atomic_epochs", + "composition_epochs": "exposure/composition_epochs", + } + for key, value in record.items(): + if key in {"step", "metrics"}: + continue + if isinstance(value, int | float) and not isinstance(value, bool) and math.isfinite(value): + result[groups.get(key, f"training/{key}")] = value + if previous is not None and record["step"] > previous["step"]: + steps = record["step"] - previous["step"] + if "training_seconds" in record and "training_seconds" in previous: + seconds = record["training_seconds"] - previous["training_seconds"] + if seconds > 0: + result["perf/training_ms_per_update"] = 1000 * seconds / steps + result["perf/updates_per_second"] = steps / seconds + if "examples" in record and "examples" in previous: + result["perf/examples_per_second"] = ( + record["examples"] - previous["examples"] + ) / seconds + return result + + +class ArtifactRunTracker: + def __init__(self, sdk, batch, path, settings): + self.path = Path(path) + self.state_path = Path(batch) / "tracking-wandb" / self.path.name / "state.json" + self.metadata = read_json(self.path / "run.json") + self.settings = settings + identity = { + "batch": Path(batch).name, + "name": self.path.name, + "spec": public_config(self.metadata.get("spec", {})), + "world_sha256": self.metadata.get("world_sha256"), + "initial_model_sha256": self.metadata.get("initial_model_sha256"), + } + fingerprint = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest() + saved = read_json(self.state_path) if self.state_path.exists() else {} + if saved: + assert saved["fingerprint"] == fingerprint, "Source trajectory identity changed" + assert saved["entity"] == settings["entity"] and saved["project"] == settings["project"] + self.state = { + "run_id": fingerprint[:16], + "fingerprint": fingerprint, + "entity": settings["entity"], + "project": settings["project"], + "last_logged_step": -1, + **saved, + } + options = {"disable_git": True} + if not settings["system_metrics"]: + options["x_disable_stats"] = True + else: + if "gpu" in self.metadata: + options["x_stats_gpu_device_ids"] = (self.metadata["gpu"],) + if "pid" in self.metadata: + options["x_stats_pid"] = self.metadata["pid"] + mode = settings["mode"] + run_id = self.state["run_id"] + if mode == "offline" and saved: + segment = saved.get("offline_segment", 0) + 1 + self.state["offline_segment"] = segment + run_id = f"{run_id[:12]}{segment:04x}" + self.state_path.parent.mkdir(parents=True, exist_ok=True) + config = { + **identity, + "scientific_run_id": self.state["run_id"], + **{ + k: self.metadata[k] + for k in [ + "model", + "phase", + "evaluation_nodes", + "execution_lock_sha256", + "parameters", + "vocab_size", + "atomic_examples", + "composition_examples", + "dtype", + "gpu_name", + ] + if k in self.metadata + }, + } + self.run = sdk.init( + entity=settings["entity"], + project=settings["project"], + group=self.metadata.get("tracking_group", Path(batch).name), + name=self.path.name, + id=run_id, + config=config, + mode=mode, + resume="allow" if mode == "online" else None, + job_type=self.metadata.get("job_type", "training"), + tags=self.metadata.get("tags", []), + dir=str(self.state_path.parent), + save_code=False, + reinit="create_new", + settings=sdk.Settings(**options), + ) + self.run.define_metric("training/step") + self.run.define_metric("*", step_metric="training/step") + if mode == "online": + # The public history is authoritative: an SDK restart can briefly report step 0, + # and a local cursor can include points queued before a network interruption. + remote = sdk.Api(timeout=30).run(f"{settings['entity']}/{settings['project']}/{run_id}") + self.cursor = remote.lastHistoryStep + else: + self.cursor = self.state["last_logged_step"] + self.state.update(url=self.run.url, mode=mode, wandb_run_id=run_id) + write_json(self.state_path, self.state) + + def poll(self): + history = read_json(self.path / "learning.json") + previous = None + for record in history: + step = int(record["step"]) + if step > self.cursor: + self.run.log(learning_metrics(record, previous), step=step) + self.cursor = step + self.state["last_logged_step"] = step + write_json(self.state_path, self.state) + previous = record + status_path = self.path / "status.json" + if status_path.exists(): + status = read_json(status_path) + self.run.summary["training_state"] = status.get("state", "unknown") + complete = (self.path / "complete.json").exists() + failure_record = (self.path / "failure.json").exists() or ( + self.path / "failure-detail.json" + ).exists() + failed = failure_record and not complete + self.run.summary["has_failure_record"] = failure_record + self.run.summary["independently_reloaded"] = (self.path / "audit.json").exists() + if complete or failed: + self.run.summary["scientific_final_step"] = self.cursor + self.run.finish(exit_code=1 if failed else 0) + return True + return False + + def close(self): + self.run.finish() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--runs-dir", type=Path) + parser.add_argument("--defaults", type=Path, default=DEFAULTS) + parser.add_argument("--entity") + parser.add_argument("--project") + parser.add_argument("--mode", choices=["online", "offline"]) + parser.add_argument("--once", action="store_true") + parser.add_argument("--detach", action="store_true") + args = parser.parse_args() + settings = read_json(args.defaults) + for name in ["entity", "project", "mode"]: + settings[name] = ( + getattr(args, name) or os.environ.get(f"WANDB_{name.upper()}") or settings[name] + ) + if not settings["enabled"]: + raise SystemExit("Experiment tracking is disabled in the selected defaults") + local = args.root / "tracking-wandb" + local.mkdir(parents=True, exist_ok=True) + if args.detach: + metadata_path = local / "process.json" + if metadata_path.exists(): + pid = read_json(metadata_path)["pid"] + try: + os.kill(pid, 0) + except ProcessLookupError: + pass + else: + raise SystemExit(f"Tracking process already running: {pid}") + arguments = [a for a in sys.argv[1:] if a != "--detach"] + command = [ + sys.executable, + "-u", + "-m", + "llm_memory_editability.experiment_tracking", + *arguments, + ] + with (local / "tracker.log").open("a") as log: + process = subprocess.Popen( + command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True + ) + write_json(metadata_path, {"pid": process.pid, "command": command}) + print(json.dumps({"tracker_pid": process.pid, "log": str(local / "tracker.log")})) + return + try: + sdk = importlib.import_module("wandb") + except ImportError as error: + raise SystemExit("Install the tracking extra, or use .venv-wandb/bin/python") from error + with (local / "tracker.lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + active, finished = {}, set() + runs_dir = args.runs_dir or args.root / "development" + try: + while True: + for path in sorted(runs_dir.glob("*")): + if path in active or path in finished: + continue + if not (path / "run.json").exists() or not (path / "learning.json").exists(): + continue + active[path] = ArtifactRunTracker(sdk, args.root, path, settings) + print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True) + for path, tracker in list(active.items()): + current = read_json(path / "run.json") + if current.get("pid") != tracker.metadata.get("pid"): + tracker.close() + tracker = ArtifactRunTracker(sdk, args.root, path, settings) + active[path] = tracker + if tracker.poll(): + finished.add(path) + del active[path] + if args.once: + break + manifest = args.root / "controller-state.json" + if manifest.exists() and not active: + if read_json(manifest).get("state") in {"complete", "finished_with_failures"}: + break + time.sleep(settings["poll_seconds"]) + finally: + for tracker in active.values(): + tracker.close() + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/experiments.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/experiments.py new file mode 100644 index 0000000000000000000000000000000000000000..21513c79efc2f2e137213ca20f5444209e6d313d --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/experiments.py @@ -0,0 +1,39 @@ +"""Deterministic analytical illustration from the supplied research memo.""" + +import platform +from typing import Any + +import numpy as np + +from .low_rank import evaluate_update + + +def run_minimal_example(rank: int = 1, atol: float = 1e-10) -> dict[str, Any]: + """Compare a shared-rule update with a one-entry exception. + + At rank budget one, both changes have rank-one deltas but only the rule's + target is representable. At budget two, both targets are representable. + This is a classical matrix fact, not evidence of LLM editing difficulty. + """ + original = np.ones((2, 2), dtype=float) + cases = { + "original": evaluate_update(original, original, rank, atol), + "rule": evaluate_update(original, 2 * original, rank, atol), + "exception": evaluate_update(original, [[2, 1], [1, 1]], rank, atol), + } + return { + "experiment": "minimal_low_rank", + "scope": ( + "Analytical SVD illustration for fully observed real matrices with a " + "fixed total rank budget and unweighted Frobenius error. No training, " + "optimization path, or Transformer editing is evaluated. Numerical " + "rank counts singular values greater than an absolute tolerance; " + "this example does not validate the broader research hypothesis." + ), + "parameters": { + "rank_budget": cases["original"]["rank_budget"], + "atol": cases["original"]["atol"], + }, + "versions": {"python": platform.python_version(), "numpy": np.__version__}, + "cases": cases, + } diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_depth.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb93ea353cb12f972942a3cf658bc6593f81bb7 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_depth.py @@ -0,0 +1,431 @@ +"""Small GPT-2 composition learning, adapted from Wang et al. (NeurIPS 2024). + +Data/target conventions follow GrokkedTransformer commit 734ca654ec7a71dd6737d640407fac14491d538c. +The compact vocabulary, widths and data sizes are explicit experimental adaptations. +CUDA Graph capture is an execution optimization, not a change to the training objective. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import math +import time +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import CausalLM, ModelConfig, matmul_flops + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + tmp.replace(path) + + +class SmallGPT(CausalLM): + """GPT-2 pre-LN, tied output, learned positions, GELU, standard dropout.""" + + def __init__(self, config, dropout=0.1): + super().__init__(config) + self.dropout = dropout + + def forward(self, tokens, positions=None): + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + for block in self.blocks: + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + +def pack_rows(rows): + """Right-pad; supervise tail and EOS only. No BOS or answer delimiter.""" + rows = np.asarray(rows, dtype=np.int64) + x = np.zeros((len(rows), 4), dtype=np.int64) + x[:, : rows.shape[1]] = rows + positions = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) + labels = np.c_[rows[:, -1], np.ones(len(rows), dtype=np.int64)] + return x, positions, labels + + +def make_optimizer(model, lr, weight_decay): + decay = [p for p in model.parameters() if p.ndim >= 2] + no_decay = [p for p in model.parameters() if p.ndim < 2] + return torch.optim.AdamW( + [ + {"params": decay, "weight_decay": weight_decay}, + {"params": no_decay, "weight_decay": 0.0}, + ], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + fused=True, + capturable=True, + ) + + +class GraphStep: + """Capture complete AdamW step and undo warmup without rebinding state tensors.""" + + def __init__(self, model, optimizer, table, batch_size, clip=1.0): + self.index = torch.zeros(batch_size, dtype=torch.long, device=table[0].device) + self.model, self.optimizer, self.table, self.clip = model, optimizer, table, clip + weights = {k: v.detach().clone() for k, v in model.state_dict().items()} + state = { + p: { + k: v.detach().clone() if torch.is_tensor(v) else copy.deepcopy(v) + for k, v in s.items() + } + for p, s in optimizer.state.items() + } + cpu_rng = torch.get_rng_state() + cuda_rng = torch.cuda.get_rng_state(table[0].device) + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(3): + self.eager() + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + self.graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(self.graph): + self.loss, self.grad_norm = self.eager() + torch.cuda.synchronize() + with torch.no_grad(): + for k, v in model.state_dict().items(): + v.copy_(weights[k]) + for param, values in optimizer.state.items(): + before = state.get(param, {}) + for k, v in values.items(): + if torch.is_tensor(v): + if k in before: + v.copy_(before[k]) + else: + v.zero_() + for p in model.parameters(): + if p.grad is not None: + p.grad.zero_() + torch.set_rng_state(cpu_rng) + torch.cuda.set_rng_state(cuda_rng, table[0].device) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, pos, labels = (t[self.index] for t in self.table) + logits = self.model(x, positions=pos) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten()) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + def __call__(self, indices): + self.index.copy_(indices) + self.graph.replay() + return self.loss + + +class EpochStream: + """Uniform shuffled epochs of the combined atomic/composite training set.""" + + def __init__(self, size, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def take(self, n): + parts = [] + while n: + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(n, len(self.remaining)) + parts.append(self.remaining[:count]) + self.remaining = self.remaining[count:] + n -= count + return np.concatenate(parts) + + def state_dict(self): + return { + "size": self.size, + "rng": self.rng.bit_generator.state, + "remaining": self.remaining.copy(), + } + + def load_state_dict(self, state): + assert state["size"] == self.size + self.rng.bit_generator.state = state["rng"] + self.remaining = state["remaining"].copy() + + +@torch.no_grad() +def evaluate_rows(model, rows, device, batch_size=1024): + model.eval() + packed = pack_rows(rows) + answers, stops, losses = [], [], [] + for start in range(0, len(rows), batch_size): + x, pos, labels = ( + torch.as_tensor(t[start : start + batch_size], device=device) for t in packed + ) + logits = model(x, pos) + losses.append( + F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + .view(-1, 2) + .cpu() + .numpy() + ) + answer = logits[:, 0].argmax(-1) + # Actual generated answer is fed back when producing EOS. + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + stop = model(x, pos)[:, 1].argmax(-1) + answers.append(answer.cpu().numpy()) + stops.append(stop.cpu().numpy()) + model.train() + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}, {} + answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) + correct = answer == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": float(correct.mean()), + "accuracy": float((correct & (stop == 1)).mean()), + "nll": float(nll.mean()), + }, {"answer": answer, "stop": stop, "nll": nll, "target": rows[:, -1]} + + +@torch.no_grad() +def two_calls(model, rows, device): + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None} + first = np.c_[rows[:, :2], np.zeros(len(rows), dtype=np.int64)] + _, first_pred = evaluate_rows(model, first, device) + second = np.c_[first_pred["answer"], rows[:, 2], rows[:, 3]] + result, second_pred = evaluate_rows(model, second, device) + result["accuracy"] = float( + ( + (second_pred["answer"] == rows[:, -1]) + & (second_pred["stop"] == 1) + & (first_pred["stop"] == 1) + ).mean() + ) + return result + + +def source_hash(paths): + return {str(p): hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths} + + +def run(spec, world, out, device="cuda:0", resume=False): + """Run a fixed scientific budget. Intermediate evaluations never change training.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + device = torch.device(device) + torch.cuda.set_device(device) + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = SmallGPT(cfg, spec["dropout"]).to(device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + atoms, comps = pack_rows(world["atomic"]), pack_rows(world["train_composite"]) + table = tuple( + torch.as_tensor(np.concatenate([a, c]), device=device) + for a, c in zip(atoms, comps, strict=True) + ) + stream = EpochStream(len(table[0]), spec["stream_seed"]) + counts = {"atomic": 0, "composite": 0} + elapsed_training, elapsed_eval = 0.0, 0.0 + start_step = 0 + checkpoint = out / "latest.pt" + if resume: + state = torch.load(checkpoint, map_location=device, weights_only=False) + assert state["spec"] == spec + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + # load_state_dict replaces the LR tensor; retain the optimizer's live tensor. + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + counts = state["counts"] + elapsed_training = state["elapsed_training"] + elapsed_eval = state["elapsed_eval"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + started = time.perf_counter() + graph = GraphStep(model, opt, table, spec["batch_size"]) + capture_seconds = time.perf_counter() - started + names = ("atomic", "train_composite", "test_composite", "ood_composite") + nparams = sum(p.numel() for p in model.parameters()) + flop_step = matmul_flops(cfg, spec["batch_size"], sequence=4, output_positions=2) + rows_log = [] + if (out / "learning.json").exists(): + rows_log = json.loads((out / "learning.json").read_text()) + if resume: + # A crash can leave a log newer than the atomically replaced checkpoint. + rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) + rows_log.sort(key=lambda r: r["step"]) + if start_step == spec["steps"]: + endpoint = rows_log[-1] + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": endpoint, + "completion_recovered_from_final_checkpoint": True, + }, + ) + write_json( + out / "status.json", + { + "state": "complete", + "step": start_step, + "budget": spec["steps"], + "updated_utc": utc(), + "atomic": endpoint["atomic"]["accuracy"], + "train": endpoint["train_composite"]["accuracy"], + "test": endpoint["test_composite"]["accuracy"], + }, + ) + return rows_log[-1] + + def measure(step, last_loss=None): + nonlocal elapsed_eval + torch.cuda.synchronize() + t0 = time.perf_counter() + row = { + "step": step, + "utc": utc(), + "parameters": nparams, + "training_seconds": elapsed_training, + "capture_seconds": capture_seconds, + "examples": step * spec["batch_size"], + "counts": counts.copy(), + "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * 4, + "supervised_tokens": step * spec["batch_size"] * 2, + "estimated_training_flops": step * flop_step, + "last_batch_loss": last_loss, + } + predictions = {} + for name in names: + row[name], pred = evaluate_rows(model, world[name], device) + predictions.update({name + "_" + k: v for k, v in pred.items()}) + row["two_calls"] = two_calls(model, world["test_composite"], device) + torch.cuda.synchronize() + elapsed_eval += time.perf_counter() - t0 + row["evaluation_seconds"] = elapsed_eval + rows_log.append(row) + write_json(out / "learning.json", rows_log) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + state = { + "step": step, + "spec": spec, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "elapsed_training": elapsed_training, + "elapsed_eval": elapsed_eval, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(checkpoint) + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "complete" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "updated_utc": utc(), + "atomic": row["atomic"]["accuracy"], + "train": row["train_composite"]["accuracy"], + "test": row["test_composite"]["accuracy"], + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + nodes = [s for s in spec["nodes"] if s > start_step] + for end in nodes: + last_loss = None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + ix = stream.take(n * spec["batch_size"]).reshape(n, spec["batch_size"]) + atom_count = int((ix < len(world["atomic"])).sum()) + counts["atomic"] += atom_count + counts["composite"] += ix.size - atom_count + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + last_loss = graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + elapsed_training += time.perf_counter() - t0 + loss_value = float(last_loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at step {end}") + row = measure(end, loss_value) + start_step = end + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": row, + }, + ) + return row diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_depth_bridge.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_depth_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..ca05be9fcd170cee34075ae1aa2fa0c2bcca1e2c --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_depth_bridge.py @@ -0,0 +1,631 @@ +"""Prefix-only causal interventions on frozen grok-depth-v1 checkpoints. + +Donors are selected from world facts before any model is loaded. The only donor +input is its two-token atomic query; second relations and answers never enter the +forward pass that supplies the post-first-block residual state. +""" + +from __future__ import annotations + +import hashlib +import importlib +import json +import platform +import sys +import time +import types +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +CONDITIONS = ( + "baseline", + "identity_r1", + "different_bridge_r1", + "same_bridge_r1", + "different_bridge_h", + "different_bridge_h_r1", + "counterfactual_input", +) +DATA_FIELDS = ("entities", "relations", "degree", "phi", "id_fraction", "id_test_fraction") + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temporary.replace(path) + + +def require(condition, message): + if not condition: + raise AssertionError(message) + + +def _frozen_modules(source_dir, metadata): + """Verify all historical copies, then import exclusively from that snapshot.""" + snapshot = source_dir / "source" + copied = {p.relative_to(snapshot).as_posix(): p for p in snapshot.rglob("*") if p.is_file()} + verified = {} + for original, expected in metadata["files"].items(): + matches = [ + p for rel, p in copied.items() if original == rel or original.endswith("/" + rel) + ] + require(len(matches) == 1, f"missing or ambiguous historical copy: {original}") + path = matches[0] + actual = digest(path) + require(actual == expected, f"historical source hash mismatch: {path}") + verified[path.relative_to(snapshot).as_posix()] = actual + configs = [snapshot / p for p in verified if p.startswith("configs/")] + require(len(configs) == 1, "expected exactly one frozen configuration") + frozen = read_json(configs[0]) + require( + {**frozen["base"], **frozen["runs"][source_dir.name]} == metadata["spec"], + "historical metadata differs from its frozen configuration", + ) + package = "_grok_bridge_source_" + hashlib.sha256(str(source_dir).encode()).hexdigest()[:16] + namespace = types.ModuleType(package) + namespace.__path__ = [str(snapshot / "src/llm_memory_editability")] + sys.modules[package] = namespace + training = importlib.import_module(package + ".grok_depth") + data = importlib.import_module(package + ".grok_depth_data") + return training, data, verified + + +def load_source_run(source_dir, step, device="cuda:0"): + """Return a frozen model/world after source, world and checkpoint consistency checks.""" + source_dir = Path(source_dir).resolve() + metadata = read_json(source_dir / "metadata.json") + spec = metadata["spec"] + require(spec["phase"] == source_dir.parent.name, "historical phase/path mismatch") + training, data, verified = _frozen_modules(source_dir, metadata) + require(step in spec["weight_nodes"], f"unregistered historical weight node {step}") + checkpoint_path = source_dir / f"weights-{step:07d}.pt" + checkpoint_hash = digest(checkpoint_path) + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + require( + checkpoint["spec"] == spec and checkpoint["step"] == step, "checkpoint identity mismatch" + ) + require(digest(checkpoint_path) == checkpoint_hash, "checkpoint changed while loading") + if step == spec["steps"]: + latest = torch.load(source_dir / "latest.pt", map_location="cpu", weights_only=False) + require( + latest["step"] == step and latest["spec"] == spec, "latest checkpoint identity mismatch" + ) + require( + checkpoint["model"].keys() == latest["model"].keys() + and all(torch.equal(v, latest["model"][k]) for k, v in checkpoint["model"].items()), + "endpoint weights differ from latest checkpoint", + ) + del latest + world_path = source_dir / "world.npz" + world_hash = digest(world_path) + with np.load(world_path, allow_pickle=False) as stored: + world = {key: stored[key].copy() for key in stored.files} + world["metadata"] = read_json(source_dir / "world-metadata.json") + require(digest(world_path) == world_hash, "world changed while loading") + audit = data.audit_world(world) + require(audit == read_json(source_dir / "data-audit.json"), "historical world audit mismatch") + require( + audit["dataset_sha256"] == world["metadata"]["dataset_sha256"], + "world content hash mismatch", + ) + rebuilt = data.build_world(spec["world_seed"], **{key: spec[key] for key in DATA_FIELDS}) + require(rebuilt["metadata"] == world["metadata"], "regenerated world metadata mismatch") + for key, array in world.items(): + if key != "metadata": + require(np.array_equal(array, rebuilt[key]), f"regenerated world mismatch: {key}") + cfg = training.ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = training.SmallGPT(cfg, spec["dropout"]).to(device) + model.load_state_dict(checkpoint["model"], strict=True) + model.eval() + for parameter in model.parameters(): + parameter.requires_grad_(False) + provenance = { + "source_dir": str(source_dir), + "source_hashes": verified, + "checkpoint_sha256": checkpoint_hash, + "world_file_sha256": world_hash, + "dataset_sha256": audit["dataset_sha256"], + "world_audit": audit, + "source_metadata_sha256": digest(source_dir / "metadata.json"), + "source_predictions_sha256": digest(source_dir / f"predictions-{step:07d}.npz"), + "world_regenerated_identically": True, + } + return model, world, spec, provenance + + +def _choose(candidates, world_hash, seed, row, kind): + """Content-based uniform deterministic selection; no model input is accepted.""" + if not candidates: + return None + material = json.dumps([world_hash, int(seed), list(map(int, row)), kind], separators=(",", ":")) + rng = np.random.default_rng( + int.from_bytes(hashlib.sha256(material.encode()).digest()[:16], "big") + ) + return sorted(candidates)[int(rng.integers(len(candidates)))] + + +def select_donors(world, seed): + """Select once per test row; preserve all rows, masks and rejection counts. + + Different-bridge candidates share r1, change h/b/t, have ID second facts, + and yield a reserved-test or unused counterfactual. Same-bridge candidates + may change r1; only their bridge, query distinctness and h != original t + matter. No candidate is selected using model behavior. + """ + rows = world["test_composite"] + n = len(rows) + atoms = {tuple(map(int, row)) for row in world["id_atomic"]} + lookup = {(h, r): t for h, r, t in atoms} + held_out = { + tuple(map(int, row)) + for name in ("test_composite", "unused_composite") + for row in world[name] + } + training = {tuple(map(int, row)) for row in world["train_composite"]} + world_hash = world["metadata"]["dataset_sha256"] + out = { + "original_rows": rows.copy(), + "original_bridge": np.full(n, -1, dtype=np.int64), + "different_donor": np.full((n, 3), -1, dtype=np.int64), + "same_donor": np.full((n, 3), -1, dtype=np.int64), + "counterfactual_rows": np.full((n, 4), -1, dtype=np.int64), + "different_valid": np.zeros(n, dtype=bool), + "same_valid": np.zeros(n, dtype=bool), + "different_reason": np.full(n, "", dtype="U64"), + "same_reason": np.full(n, "", dtype="U64"), + "different_candidate_count": np.zeros(n, dtype=np.int64), + "same_candidate_count": np.zeros(n, dtype=np.int64), + "same_relation_control": np.full(n, "missing", dtype="U24"), + "different_nondegenerate": np.zeros(n, dtype=bool), + } + rejection_names = ( + "same_head", + "same_bridge", + "missing_id_second_fact", + "same_tail", + "head_is_answer", + "counterfactual_in_train", + "counterfactual_not_held_out", + ) + for reason in rejection_names: + out["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) + for index, row in enumerate(rows): + h, r1, r2, tail = map(int, row) + bridge = lookup[h, r1] + require(lookup.get((bridge, r2)) == tail, "recipient is not an ID-ID chain") + out["original_bridge"][index] = bridge + candidates = [] + for dh, dr, db in sorted(atoms): + if dr != r1: + continue + dt = lookup.get((db, r2)) + cf = (dh, r1, r2, dt) + reason = ( + "same_head" + if dh == h + else "same_bridge" + if db == bridge + else "missing_id_second_fact" + if dt is None + else "same_tail" + if dt == tail + else "head_is_answer" + if dh in (tail, dt) + else "counterfactual_in_train" + if cf in training + else "counterfactual_not_held_out" + if cf not in held_out + else None + ) + if reason: + out["different_rejected_" + reason][index] += 1 + else: + candidates.append((dh, dr, db, dt)) + donor = _choose(candidates, world_hash, seed, row, "different") + out["different_candidate_count"][index] = len(candidates) + if donor is None: + out["different_reason"][index] = "no_candidate_after_registered_exclusions" + else: + dh, dr, db, dt = donor + out["different_donor"][index] = dh, dr, db + out["counterfactual_rows"][index] = dh, r1, r2, dt + out["different_valid"][index] = True + out["different_reason"][index] = "eligible" + out["different_nondegenerate"][index] = db != dt and db != tail + candidates = [ + (dh, dr, db) + for dh, dr, db in atoms + if db == bridge and (dh, dr) != (h, r1) and dh != tail + ] + same_relation = [candidate for candidate in candidates if candidate[1] == r1] + donor = _choose(same_relation or candidates, world_hash, seed, row[:2], "same") + out["same_candidate_count"][index] = len(candidates) + if donor is None: + out["same_reason"][index] = "no_distinct_id_prefix_with_same_bridge_and_head_not_answer" + else: + out["same_donor"][index] = donor + out["same_valid"][index] = True + out["same_reason"][index] = "eligible" + out["same_relation_control"][index] = "same_r1" if donor[1] == r1 else "different_r1" + return out + + +@torch.no_grad() +def traced_forward( + model, + tokens, + positions=None, + donor_state=None, + patch_positions=(), + identity=False, + return_state=False, +): + """Frozen SmallGPT eval forward, replacing residuals after complete block 0. + + Both attention and MLP in the first block run before replacement. There is + no patch in another block, and final LN/output projection remain untouched. + """ + require(not model.training, "interventions require model.eval()") + require( + donor_state is None or not identity, "identity and donor patches are mutually exclusive" + ) + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + first_state = None + for index, block in enumerate(model.blocks): + z = block.ln1(x) + batch, length, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, length, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=0.0 + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + y + x = x + block.mlp(block.ln2(x)) + if index == 0: + if return_state: + first_state = x.clone() + if donor_state is not None or identity: + x = x.clone() + replacement = x.clone() if identity else donor_state + for position in patch_positions: + x[:, position, :] = replacement[:, position, :] + x = model.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, model.token.weight) + return (logits, first_state) if return_state else logits + + +@torch.no_grad() +def prefix_state(model, prefixes): + """Two informative tokens, padded to the historical four-position shape. + + Both suffix tokens are the fixed PAD token, never a relation or answer. + Causality makes the retained two states independent of these suffixes. + Matching the matrix shapes avoids TF32 kernel-dependent rounding changes. + """ + require(prefixes.ndim == 2 and prefixes.shape[1] == 2, "expected h/r1 prefixes") + padded = F.pad(prefixes, (0, 2), value=0) + _, state = traced_forward(model, padded, return_state=True) + return state[:, :2] + + +@torch.no_grad() +def evaluate_condition( + model, + rows, + device, + batch_size=1024, + donor_prefixes=None, + patch_positions=(), + identity=False, + verify_trace=False, +): + """Answer generation followed by EOS with the generated answer fed back. + + The exact same prefix state is reapplied on the second forward pass. Arrays + are local to the supplied rows; the caller scatters them to the full test set. + """ + n = len(rows) + answers, stops, original_logits = [], [], [] + trace_max_delta, trace_disagreements = 0.0, 0 + prefix_max_delta = 0.0 + for start in range(0, n, batch_size): + selected = rows[start : start + batch_size] + arity = rows.shape[1] + require(arity in (3, 4), "expected atomic or composite rows") + packed = np.zeros((len(selected), 4), dtype=np.int64) + packed[:, :arity] = selected + x = torch.as_tensor(packed, device=device) + pos = torch.as_tensor(np.tile([arity - 2, arity - 1], (len(x), 1)), device=device) + donor_state = None + if donor_prefixes is not None: + prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) + require(prefixes.shape == (len(x), 2), "donor model may receive only h and r1") + donor_state = prefix_state(model, prefixes) + logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) + if verify_trace: + reference = model(x, pos) + trace_max_delta = max(trace_max_delta, float((reference - logits).abs().max())) + trace_disagreements += int((reference.argmax(-1) != logits.argmax(-1)).sum()) + prefix = prefix_state(model, x[:, :2]) + _, whole = traced_forward(model, x, return_state=True) + prefix_max_delta = max(prefix_max_delta, float((prefix - whole[:, :2]).abs().max())) + require( + torch.allclose(prefix, whole[:, :2], atol=1e-4, rtol=1e-4), + "pure-prefix state does not match causal full-input prefix", + ) + answer = logits[:, 0].argmax(-1) + original_logits.append(logits[:, 0].cpu().numpy()) + x[:, arity - 1] = answer + generated_logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) + if verify_trace: + reference = model(x, pos) + trace_max_delta = max( + trace_max_delta, float((reference - generated_logits).abs().max()) + ) + trace_disagreements += int((reference.argmax(-1) != generated_logits.argmax(-1)).sum()) + answers.append(answer.cpu().numpy()) + stops.append(generated_logits[:, 1].argmax(-1).cpu().numpy()) + require(trace_disagreements == 0, "traced forward changes standard-forward discrete outputs") + require(trace_max_delta <= 1e-5, f"traced forward mismatch: {trace_max_delta}") + return { + "answer": np.concatenate(answers) if n else np.empty(0, dtype=np.int64), + "stop": np.concatenate(stops) if n else np.empty(0, dtype=np.int64), + "answer_logits": np.concatenate(original_logits) + if n + else np.empty((0, model.token.num_embeddings), dtype=np.float32), + }, { + "standard_forward_max_logit_delta": trace_max_delta, + "standard_forward_argmax_disagreements": trace_disagreements, + "prefix_vs_full_first_block_max_delta": prefix_max_delta, + "trace_comparison_performed": verify_trace, + } + + +def _metrics(answer, stop, original, cf, selected, cf_valid, total, baseline_answer): + count = int(selected.sum()) + counterfactual = selected & cf_valid + ncf = int(counterfactual.sum()) + correct = answer == original + cf_correct = answer == cf + return { + "n": count, + "total_test_n": total, + "coverage": count / total if total else None, + "original_answer_accuracy": float(correct[selected].mean()) if count else None, + "original_complete_accuracy": float((correct & (stop == 1))[selected].mean()) + if count + else None, + "eos_accuracy": float((stop[selected] == 1).mean()) if count else None, + "answer_change_rate": float((answer[selected] != baseline_answer[selected]).mean()) + if count + else None, + "cf_target_n": ncf, + "cf_answer_accuracy": float(cf_correct[counterfactual].mean()) if ncf else None, + "cf_complete_accuracy": float((cf_correct & (stop == 1))[counterfactual].mean()) + if ncf + else None, + } + + +def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): + """Evaluate all fixed conditions, then expose full and prerequisite subgroups.""" + started = time.perf_counter() + rows = world["test_composite"] + n = len(rows) + different, same = donors["different_valid"], donors["same_valid"] + arrays = {key: value.copy() for key, value in donors.items()} + audits = {} + for condition in CONDITIONS: + mask = ( + same + if condition == "same_bridge_r1" + else different + if condition.startswith("different_") or condition == "counterfactual_input" + else np.ones(n, dtype=bool) + ) + eval_rows = ( + donors["counterfactual_rows"][mask] + if condition == "counterfactual_input" + else rows[mask] + ) + donor_key = "same_donor" if condition == "same_bridge_r1" else "different_donor" + donor_prefix = donors[donor_key][mask, :2] if "bridge_" in condition else None + positions = ( + (0, 1) + if condition == "different_bridge_h_r1" + else (0,) + if condition == "different_bridge_h" + else (1,) + ) + result, audit = evaluate_condition( + model, + eval_rows, + device, + batch_size, + donor_prefix, + positions, + condition == "identity_r1", + condition == "baseline", + ) + audits[condition] = audit + answer = np.full(n, -1, dtype=np.int64) + stop = np.full(n, -1, dtype=np.int64) + answer[mask], stop[mask] = result["answer"], result["stop"] + arrays[condition + "_answer"], arrays[condition + "_stop"] = answer, stop + arrays[condition + "_valid"] = mask + original_logit = result["answer_logits"][np.arange(mask.sum()), rows[mask, -1]] + cf_logit = np.full(n, np.nan, dtype=np.float32) + cf_local = different[mask] + cf_logit[mask.nonzero()[0][cf_local]] = ( + result["answer_logits"][ + np.flatnonzero(cf_local), donors["counterfactual_rows"][mask][cf_local, -1] + ] + - original_logit[cf_local] + ) + arrays[condition + "_cf_minus_original_logit"] = cf_logit + for column in ("answer", "stop"): + require( + np.array_equal(arrays["baseline_" + column], arrays["identity_r1_" + column]), + f"identity patch changed {column}", + ) + if len(model.blocks) == 1: + for condition in ( + "different_bridge_r1", + "same_bridge_r1", + "different_bridge_h", + "different_bridge_h_r1", + ): + valid = arrays[condition + "_valid"] + require( + np.array_equal( + arrays["baseline_" + column][valid], arrays[condition + "_" + column][valid] + ), + f"one-layer structural negative control changed {condition}.{column}", + ) + baseline_correct = (arrays["baseline_answer"] == rows[:, -1]) & (arrays["baseline_stop"] == 1) + cf_correct = ( + different + & (arrays["counterfactual_input_answer"] == donors["counterfactual_rows"][:, -1]) + & (arrays["counterfactual_input_stop"] == 1) + ) + atomic_rows = { + "different_first": (donors["different_donor"], different), + "counterfactual_second": ( + np.c_[ + donors["different_donor"][:, 2], rows[:, 2], donors["counterfactual_rows"][:, -1] + ], + different, + ), + "same_first": (donors["same_donor"], same), + } + atomic_scores = {} + atomic_correct = {} + for name, (facts, mask) in atomic_rows.items(): + prediction, _ = evaluate_condition(model, facts[mask], device, batch_size) + answer = np.full(n, -1, dtype=np.int64) + stop = np.full(n, -1, dtype=np.int64) + answer[mask], stop[mask] = prediction["answer"], prediction["stop"] + arrays["atomic_" + name + "_rows"] = facts.copy() + arrays["atomic_" + name + "_answer"] = answer + arrays["atomic_" + name + "_stop"] = stop + arrays["atomic_" + name + "_valid"] = mask.copy() + correct = mask & (answer == facts[:, -1]) + atomic_correct[name] = correct & (stop == 1) + count = int(mask.sum()) + atomic_scores[name] = { + "n": count, + "total_test_n": n, + "coverage": count / n if n else None, + "answer_accuracy": float(correct[mask].mean()) if count else None, + "complete_accuracy": float(atomic_correct[name][mask].mean()) if count else None, + "eos_accuracy": float((stop[mask] == 1).mean()) if count else None, + } + groups = { + "all_test": np.ones(n, dtype=bool), + "different_donor_available": different, + "same_donor_available": same, + "baseline_and_counterfactual_complete_correct": baseline_correct & cf_correct, + "different_bridge_nondegenerate": donors["different_nondegenerate"], + "same_bridge_same_r1": same & (donors["same_relation_control"] == "same_r1"), + "same_bridge_different_r1": same & (donors["same_relation_control"] == "different_r1"), + "both_counterfactual_atomic_facts_complete_correct": atomic_correct["different_first"] + & atomic_correct["counterfactual_second"], + } + for group, mask in groups.items(): + arrays["subset_" + group] = mask + scores = { + group: { + "subset_n": int(mask.sum()), + "total_test_n": n, + "coverage": float(mask.mean()) if n else None, + "conditions": { + condition: _metrics( + arrays[condition + "_answer"], + arrays[condition + "_stop"], + rows[:, -1], + donors["counterfactual_rows"][:, -1], + mask & arrays[condition + "_valid"], + different, + n, + arrays["baseline_answer"], + ) + for condition in CONDITIONS + }, + } + for group, mask in groups.items() + } + summary = { + "conditions": list(CONDITIONS), + "scores": scores, + "atomic_preconditions": atomic_scores, + "donor_coverage": { + "total_test_n": n, + "different_n": int(different.sum()), + "same_n": int(same.sum()), + "different_reasons": dict(Counter(donors["different_reason"].tolist())), + "same_reasons": dict(Counter(donors["same_reason"].tolist())), + "same_relation_control": dict(Counter(donors["same_relation_control"].tolist())), + }, + "engineering_checks": { + "identity_predictions_equal": True, + "one_layer_all_early_position_patch_predictions_equal": True + if len(model.blocks) == 1 + else None, + "trace": audits["baseline"], + "eos_uses_generated_answer_and_reapplies_patch": True, + "donor_nonpadding_input_tokens": 2, + "donor_forward_sequence_length": 4, + "donor_pad_token": 0, + }, + "evaluation_seconds": time.perf_counter() - started, + } + return summary, arrays + + +def environment(device): + return { + "python": platform.python_version(), + "platform": platform.platform(), + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "device": str(device), + "gpu": torch.cuda.get_device_name(torch.device(device)) + if str(device).startswith("cuda") + else None, + "cuda_matmul_tf32": torch.backends.cuda.matmul.allow_tf32, + "cudnn_tf32": torch.backends.cudnn.allow_tf32, + "precision": "FP32 parameters and evaluation; TF32 flags recorded explicitly", + } diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_depth_data.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_depth_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8696c3ffe204466f57619157a3f47739f899c6c4 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_depth_data.py @@ -0,0 +1,281 @@ +"""Symbolic composition worlds adapted from GrokkedTransformer/composition.ipynb. + +Source: https://github.com/OSU-NLP-Group/GrokkedTransformer +Revision: 734ca654ec7a71dd6737d640407fac14491d538c (MIT). + +The graph, atomic ID/OOD split, reserved ID test chains, and phi downsampling +follow the authors' construction. Differences: integer tokens replace text; +randomness is local and seeded; atomic ordering is stable; graph size and the +reserved ID-test fraction are configurable. Unselected ID chains are returned +for audit only. No graph is regenerated to improve OOD counts or model results. + +Adapted source license: +MIT License +Copyright (c) 2024 OSU Natural Language Processing + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +PAD_TOKEN = 0 +EOS_TOKEN = 1 +ENTITY_OFFSET = 2 +SOURCE_URL = "https://github.com/OSU-NLP-Group/GrokkedTransformer" +SOURCE_COMMIT = "734ca654ec7a71dd6737d640407fac14491d538c" +ATOMIC_SPLITS = ("atomic", "id_atomic", "ood_atomic") +COMPOSITE_SPLITS = ( + "train_composite", + "test_composite", + "ood_composite", + "unused_composite", +) + + +def _array(rows: list, columns: int) -> np.ndarray: + return np.asarray(rows, dtype=np.int64).reshape(-1, columns) + + +def build_world( + seed: int, + entities: int = 128, + relations: int = 16, + degree: int = 8, + phi: float = 8.0, + id_fraction: float = 0.95, + id_test_fraction: float = 0.005, +) -> dict: + """Return atomic ``[h,r,t]`` and composite ``[h,r1,r2,t]`` int64 arrays. + + All atomics belong in training, including those labelled OOD. OOD refers + to *composition experience*: neither constituent of an OOD composite is + allowed in composite training. Mixed ID/OOD chains are excluded. The + test set is reserved before phi downsampling; unused ID chains are never + automatically reassigned to test. ``phi`` is relative to ID atomics, as in + the source. Requests larger than the available training pool are capped + and explicitly recorded. Empty test sets are retained and reported. + + Query tokens are every column except the last; the last is the entity + answer. EOS supervision, padding, and loss masks belong to the trainer. + """ + for name, value in (("entities", entities), ("relations", relations), ("degree", degree)): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 1: + raise ValueError(f"{name} must be a positive integer") + if degree > relations: + raise ValueError("degree cannot exceed relations") + if not math.isfinite(phi) or phi < 0: + raise ValueError("phi must be finite and nonnegative") + if not math.isfinite(id_fraction) or not 0 <= id_fraction <= 1: + raise ValueError("id_fraction must be in [0, 1]") + if not math.isfinite(id_test_fraction) or not 0 <= id_test_fraction <= 1: + raise ValueError("id_test_fraction must be in [0, 1]") + + # RandomState keeps the source's NumPy draw family, without global RNG use. + rng = np.random.RandomState(seed) + relation_offset = ENTITY_OFFSET + entities + rows = [] + outgoing = [[] for _ in range(entities)] + for head_index in range(entities): + selected = rng.choice(relations, size=degree, replace=False) + for relation_index in selected: + tail_index = int(rng.randint(entities)) + edge = ( + head_index + ENTITY_OFFSET, + int(relation_index) + relation_offset, + tail_index + ENTITY_OFFSET, + ) + outgoing[head_index].append(len(rows)) + rows.append(edge) + atomic = _array(rows, 3) + ood_count = round(len(atomic) * (1 - id_fraction)) + ood_mask = np.zeros(len(atomic), dtype=bool) + ood_mask[rng.choice(len(atomic), size=ood_count, replace=False)] = True + + eligible, test, ood = [], [], [] + mixed_count = 0 + for first_index, (head, relation1, bridge) in enumerate(atomic): + for second_index in outgoing[int(bridge) - ENTITY_OFFSET]: + _, relation2, tail = atomic[second_index] + row = (head, relation1, relation2, tail) + first_ood, second_ood = ood_mask[first_index], ood_mask[second_index] + if first_ood and second_ood: + ood.append(row) + elif first_ood or second_ood: + mixed_count += 1 + elif rng.uniform() > id_test_fraction: + eligible.append(row) + else: + test.append(row) + + requested_count = round(phi * int((~ood_mask).sum())) + train_count = min(requested_count, len(eligible)) + # Source choose() returns the full pool unchanged when it is saturated. + indices = ( + np.arange(len(eligible)) + if train_count == len(eligible) + else rng.choice(len(eligible), size=train_count, replace=False) + ) + eligible_array = _array(eligible, 4) + selected_mask = np.zeros(len(eligible), dtype=bool) + selected_mask[indices] = True + world = { + "atomic": atomic, + "id_atomic": atomic[~ood_mask], + "ood_atomic": atomic[ood_mask], + "train_composite": eligible_array[indices], + "test_composite": _array(test, 4), + "ood_composite": _array(ood, 4), + "unused_composite": eligible_array[~selected_mask], + "metadata": { + "seed": int(seed), + "entities": int(entities), + "relations": int(relations), + "degree": int(degree), + "phi_requested": float(phi), + "id_fraction": float(id_fraction), + "id_test_fraction": float(id_test_fraction), + "pad_token": PAD_TOKEN, + "eos_token": EOS_TOKEN, + "entity_offset": ENTITY_OFFSET, + "relation_offset": int(relation_offset), + "vocab_size": int(relation_offset + relations), + "train_composite_requested": int(requested_count), + "train_composite_capped": requested_count > len(eligible), + "phi_actual": train_count / max(int((~ood_mask).sum()), 1), + "mixed_composite_excluded": mixed_count, + "source_url": SOURCE_URL, + "source_commit": SOURCE_COMMIT, + "source_file": "composition.ipynb", + "source_license": "MIT", + "construction_differences": [ + "integer tokens and local seeded RNG", + "stable atomic ordering instead of Python set iteration", + "configurable graph size and ID-test reserve fraction", + "all evaluation rows retained instead of sampling at most 3000", + ], + }, + } + audit = audit_world(world) + world["metadata"]["counts"] = audit["counts"] + world["metadata"]["dataset_sha256"] = audit["dataset_sha256"] + world["metadata"]["warnings"] = audit["warnings"] + return world + + +def audit_world(world: dict) -> dict: + """Validate token ranges, graph truth, exhaustive partitions and no leakage. + + Raises ValueError on a broken contract; zero-sized test sets and capped + training pools are valid and surfaced as warnings, never resampled. + """ + metadata = world["metadata"] + entities, relations, degree = (int(metadata[x]) for x in ("entities", "relations", "degree")) + relation_offset = entities + ENTITY_OFFSET + digest = hashlib.sha256() + counts = {} + tuples = {} + for name in ATOMIC_SPLITS + COMPOSITE_SPLITS: + array = world[name] + columns = 3 if name in ATOMIC_SPLITS else 4 + if not isinstance(array, np.ndarray) or array.dtype != np.int64: + raise ValueError(f"{name} must be an int64 numpy array") + if array.ndim != 2 or array.shape[1] != columns: + raise ValueError(f"{name} must have {columns} columns") + for column in (0, columns - 1): + if np.any(array[:, column] < ENTITY_OFFSET) or np.any( + array[:, column] >= relation_offset + ): + raise ValueError(f"{name} has an invalid entity token") + if np.any(array[:, 1:-1] < relation_offset) or np.any( + array[:, 1:-1] >= relation_offset + relations + ): + raise ValueError(f"{name} has an invalid relation token") + rows = {tuple(map(int, row)) for row in array} + if len(rows) != len(array) or len({row[:-1] for row in rows}) != len(rows): + raise ValueError(f"{name} has duplicate or conflicting queries") + tuples[name] = rows + counts[name] = len(array) + digest.update(name.encode()) + digest.update(np.asarray(array.shape, dtype="= threshold for row in triple): + row = triple[0] + result.update( + reached=True, + step=row["step"], + confirmed_at_step=triple[-1]["step"], + previous_evaluation_step=rows[i - 1]["step"] if i else None, + examples=row["examples"], + atomic_exposures=row["counts"]["atomic"] / counts["atomic"], + composite_exposures=row["counts"]["composite"] / counts["train_composite"], + dataset_passes=row["examples"] / (counts["atomic"] + counts["train_composite"]), + estimated_training_flops=row["estimated_training_flops"], + effective_input_tokens=row["effective_input_tokens"], + supervised_tokens=row["supervised_tokens"], + ) + break + return result + + +def verify_files(root, expected): + for relative, sha in expected.items(): + assert digest(root / relative) == sha, f"Frozen input changed: {relative}" diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_data.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..18cae2dbd6dfdd997883935619a80811eede27d0 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_data.py @@ -0,0 +1,346 @@ +"""Audited data and fixed atomic/composite exposure for loop-depth comparisons. + +The graph, truth, complete-query holdout and phi sampling are inherited from +``grok_multihop_data``. Changing the atomic ID fraction is an explicit design +choice; no graph is regenerated in response to diagnostics or model scores. +""" + +from __future__ import annotations + +import copy +from collections.abc import Mapping + +import numpy as np + +from . import grok_multihop_data as multihop + +SPLITS = multihop.SPLITS +DATA_DEFAULTS = { + "hops": 2, + "entities": 128, + "relations": 16, + "degree": 8, + "phi": 6.0, + "id_fraction": 0.95, + "id_test_fraction": 0.1, + "evaluation_size": 1024, +} + + +def build_world(spec: Mapping) -> dict: + """Adapt a flat run specification while retaining the historical world API. + + ``world_seed`` (or ``seed``) is required. Unrelated model/training keys are + ignored. The default atomic ID/OOD fraction remains 95/5; use an explicit + ``id_fraction=0.75`` for the new composition-experience comparison. + + ``relevant_atomic_indices[split][i, j]`` identifies query i's true hop-j + fact in ``world['atomic']``. These truth indices are evaluation artifacts; + training must only use the original atomic and train-composite rows. + """ + if "world_seed" not in spec and "seed" not in spec: + raise ValueError("spec must contain world_seed or seed") + seed = spec.get("world_seed", spec.get("seed")) + fields = {key: spec.get(key, default) for key, default in DATA_DEFAULTS.items()} + world = multihop.build_world(seed, **fields) + world["relevant_atomic_indices"] = { + name: query_atomic_indices(world, world[name]) for name in SPLITS + } + world["metadata"]["loop_data_diagnostics"] = data_diagnostics(world) + world["metadata"]["loop_data_contract"] = { + "constructor": "grok_multihop_data.build_world", + "world_selection": "fixed supplied seed; no diagnostic or model-based selection", + "all_atomic_rows_are_training_facts": True, + "ood_definition": "all constituent facts absent from composite training by split", + "query_fact_indices": "evaluation truth only; no intermediate-entity supervision", + "suffix_statistics": "within-split descriptive counts; not fitted or held-out predictors", + } + audit_world(world) + return world + + +def query_atomic_indices(world: dict, rows: np.ndarray) -> np.ndarray: + """Return true constituent fact indices, including [N, 1] for atomics.""" + meta = world["metadata"] + _, edges = multihop.path_details( + rows, world["atomic"], int(meta["entities"]), int(meta["relations"]) + ) + return edges + + +def audit_world(world: dict) -> dict: + """Independently verify truth, ID/OOD partitions and recorded fact indices. + + The reused auditor checks truth by graph traversal and counts all-ID and + all-OOD paths by dynamic programming, independently of path construction. + Neither correct-looking diagnostics nor a saved metadata hash substitutes + for those checks. + """ + result = multihop.audit_world(world) + recorded = world.get("relevant_atomic_indices") + if recorded is not None: + if set(recorded) != set(SPLITS): + raise ValueError("Relevant atomic indices must cover every data split") + for name in SPLITS: + expected = query_atomic_indices(world, world[name]) + if ( + not isinstance(recorded[name], np.ndarray) + or recorded[name].dtype != np.int64 + or not np.array_equal(recorded[name], expected) + ): + raise ValueError(f"Incorrect relevant atomic indices: {name}") + if result["dataset_sha256"] != world["metadata"].get("dataset_sha256"): + raise ValueError("Recorded dataset hash disagrees with actual data") + return {**result, "relevant_atomic_indices_checked": recorded is not None} + + +def suffix_target_diagnostics(rows: np.ndarray) -> list[dict]: + """Describe target concentration after omitting the head and prefix relations. + + The empirical modal fraction sums each suffix group's largest target count + and divides by query count. It uses the same rows to count and summarize; + singleton suffixes score one automatically. It is not a model-independent + generalization bound, a learned baseline, or proof that heads are unnecessary. + """ + results = [] + n = len(rows) + for length in range(1, rows.shape[1] - 1): + suffix = rows[:, -(length + 1) : -1] + if not n: + results.append( + { + "suffix_relation_count": length, + "groups": 0, + "empirical_modal_target_fraction": None, + "single_target_group_query_fraction": None, + "singleton_group_query_fraction": None, + "multi_query_groups": 0, + "multi_query_coverage_fraction": None, + "multi_query_empirical_modal_target_fraction": None, + "multi_target_groups": 0, + "same_suffix_different_target_example": None, + } + ) + continue + _, groups, totals = np.unique(suffix, axis=0, return_inverse=True, return_counts=True) + pairs, pair_counts = np.unique(np.c_[groups, rows[:, -1]], axis=0, return_counts=True) + maxima = np.zeros(len(totals), dtype=np.int64) + np.maximum.at(maxima, pairs[:, 0], pair_counts) + multi = totals > 1 + multi_n = int(totals[multi].sum()) + multi_target = maxima != totals + example = None + if multi_target.any(): + # Deterministic first lexicographic suffix with incompatible targets. + group = int(np.flatnonzero(multi_target)[0]) + members = np.flatnonzero(groups == group) + first = members[0] + second = members[np.flatnonzero(rows[members, -1] != rows[first, -1])[0]] + example = [rows[first].tolist(), rows[second].tolist()] + results.append( + { + "suffix_relation_count": length, + "groups": len(totals), + "empirical_modal_target_fraction": float(maxima.sum() / n), + "single_target_group_query_fraction": float(totals[maxima == totals].sum() / n), + "singleton_group_query_fraction": float((totals == 1).sum() / n), + "multi_query_groups": int(multi.sum()), + "multi_query_coverage_fraction": float(multi_n / n), + "multi_query_empirical_modal_target_fraction": ( + float(maxima[multi].sum() / multi_n) if multi_n else None + ), + "multi_target_groups": int(multi_target.sum()), + "same_suffix_different_target_example": example, + } + ) + return results + + +def majority_tail_diagnostics(rows: np.ndarray) -> dict: + """Report the empirical within-split majority target, without fitting a model.""" + if not len(rows): + return {"target_token": None, "count": 0, "fraction": None, "distinct_targets": 0} + targets, counts = np.unique(rows[:, -1], return_counts=True) + index = int(counts.argmax()) + return { + "target_token": int(targets[index]), + "count": int(counts[index]), + "fraction": float(counts[index] / len(rows)), + "distinct_targets": len(targets), + } + + +def data_diagnostics(world: dict) -> dict: + """Pure data coverage and target distributions; never evaluate a predictor.""" + atomic_n = len(world["atomic"]) + indices = world.get("relevant_atomic_indices") + if indices is None: + indices = {name: query_atomic_indices(world, world[name]) for name in SPLITS} + training_counts = np.bincount(indices["train_composite"].ravel(), minlength=atomic_n) + id_facts = np.zeros(atomic_n, dtype=bool) + id_facts[indices["id_atomic"].ravel()] = True + training_majority = majority_tail_diagnostics(world["train_composite"]) + per_split = {} + for name in SPLITS: + rows, edges = world[name], indices[name] + distinct = np.unique(edges) + trained = training_counts[edges] > 0 + all_id, all_ood = id_facts[edges].all(axis=1), (~id_facts[edges]).all(axis=1) + per_split[name] = { + "n": len(rows), + "unique_relevant_atomic_facts": len(distinct), + "relevant_atomic_fact_coverage_of_graph": len(distinct) / atomic_n, + "all_relevant_facts_in_atomic_training_fraction": 1.0 if len(rows) else None, + "all_relevant_facts_in_composite_training_n": int(trained.all(axis=1).sum()), + "any_relevant_fact_in_composite_training_n": int(trained.any(axis=1).sum()), + "relevant_fact_occurrences_seen_in_composite_training_fraction": ( + float(trained.mean()) if edges.size else None + ), + "all_id_queries": int(all_id.sum()), + "all_ood_queries": int(all_ood.sum()), + "mixed_queries": int((~all_id & ~all_ood).sum()), + "unique_relevant_facts_by_hop": [ + len(np.unique(edges[:, j])) for j in range(edges.shape[1]) + ], + "within_split_majority_tail": majority_tail_diagnostics(rows), + "train_composite_majority_tail_fraction": ( + float((rows[:, -1] == training_majority["target_token"]).mean()) + if len(rows) and training_majority["target_token"] is not None + else None + ), + "suffix_without_head": suffix_target_diagnostics(rows), + } + return { + "interpretation": { + "atomic_coverage": "data availability only; does not establish model mastery", + "ood": "all facts are atomic training facts; none has composite-training experience", + "suffix": ( + "empirical within-split target concentration; singleton suffixes score 1; " + "not a predictor, generalization bound, or evidence that the model ignores head" + ), + "majority": "within-split descriptive ceiling plus fixed training-majority fraction", + }, + "atomic_facts": atomic_n, + "id_facts": int(id_facts.sum()), + "ood_facts": int((~id_facts).sum()), + "id_facts_seen_in_composite_training": int((training_counts[id_facts] > 0).sum()), + "ood_facts_seen_in_composite_training": int((training_counts[~id_facts] > 0).sum()), + "train_composite_fact_occurrence_counts": training_counts.tolist(), + "splits": per_split, + } + + +class _EpochStream: + """NumPy-only shuffled epochs, with the existing EpochStream draw convention.""" + + def __init__(self, size: int, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def take(self, n: int) -> np.ndarray: + if not n: + return np.empty(0, dtype=np.int64) + parts = [] + while n: + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(n, len(self.remaining)) + parts.append(self.remaining[:count]) + self.remaining = self.remaining[count:] + n -= count + return np.concatenate(parts) + + def state_dict(self) -> dict: + return { + "size": self.size, + "rng": copy.deepcopy(self.rng.bit_generator.state), + "remaining": self.remaining.copy(), + } + + def load_state_dict(self, state: dict): + if state["size"] != self.size: + raise ValueError("Epoch size mismatch") + remaining = np.asarray(state["remaining"]) + if ( + remaining.ndim != 1 + or remaining.dtype != np.int64 + or np.any((remaining < 0) | (remaining >= self.size)) + or len(np.unique(remaining)) != len(remaining) + ): + raise ValueError("Invalid remaining epoch indices") + self.rng.bit_generator.state = copy.deepcopy(state["rng"]) + self.remaining = remaining.copy() + + +class StratifiedStream: + """Fixed composition per batch over the table [atomics; train_composites]. + + Atomic, composite and interleaving draws use independent RNGs. Thus changing + phi or the composite pool cannot change the atomic sequence or its batch + positions. Individual strata use shuffled epochs and may cross an epoch + boundary within one batch. No evaluation data enters either stream. + """ + + def __init__( + self, atomic_size: int, composite_size: int, batch_size: int, n_atomic: int, seed: int + ): + fields = { + "atomic_size": atomic_size, + "composite_size": composite_size, + "batch_size": batch_size, + "n_atomic": n_atomic, + } + for name, value in fields.items(): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 0: + raise ValueError(f"{name} must be a nonnegative integer") + if batch_size < 1 or n_atomic > batch_size: + raise ValueError("Require batch_size > 0 and 0 <= n_atomic <= batch_size") + if (n_atomic and not atomic_size) or (batch_size > n_atomic and not composite_size): + raise ValueError("A sampled stratum cannot be empty") + self.atomic_size, self.composite_size = int(atomic_size), int(composite_size) + self.batch_size, self.n_atomic = int(batch_size), int(n_atomic) + self.atomic = _EpochStream(atomic_size, np.random.SeedSequence([int(seed), 145101])) + self.composite = _EpochStream(composite_size, np.random.SeedSequence([int(seed), 145102])) + self.interleave = np.random.default_rng(np.random.SeedSequence([int(seed), 145103])) + self.batches = 0 + + def take(self, n: int | None = None) -> np.ndarray: + if n is not None and n != self.batch_size: + raise ValueError("StratifiedStream only emits its configured batch_size") + indices = np.r_[ + self.atomic.take(self.n_atomic), + self.composite.take(self.batch_size - self.n_atomic) + self.atomic_size, + ] + self.batches += 1 + return indices[self.interleave.permutation(self.batch_size)] + + def state_dict(self) -> dict: + return { + "version": 1, + "atomic_size": self.atomic_size, + "composite_size": self.composite_size, + "batch_size": self.batch_size, + "n_atomic": self.n_atomic, + "atomic": self.atomic.state_dict(), + "composite": self.composite.state_dict(), + "interleave_rng": copy.deepcopy(self.interleave.bit_generator.state), + "batches": self.batches, + } + + def load_state_dict(self, state: dict): + if state.get("version") != 1: + raise ValueError("Unsupported StratifiedStream state version") + for name in ("atomic_size", "composite_size", "batch_size", "n_atomic"): + if state[name] != getattr(self, name): + raise ValueError(f"StratifiedStream {name} mismatch") + atomic, composite = copy.deepcopy(self.atomic), copy.deepcopy(self.composite) + interleave = copy.deepcopy(self.interleave) + atomic.load_state_dict(state["atomic"]) + composite.load_state_dict(state["composite"]) + interleave.bit_generator.state = copy.deepcopy(state["interleave_rng"]) + batches = state["batches"] + if not isinstance(batches, int) or batches < 0: + raise ValueError("Invalid completed batch count") + self.atomic, self.composite, self.interleave = atomic, composite, interleave + self.batches = batches diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_mechanism.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd1ad614952efa432b820d8f26f1e282657a947 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_mechanism.py @@ -0,0 +1,549 @@ +"""Prefix-only component interventions at every executed Transformer block. + +The recipient block runs normally before mixing cached attention and MLP +increments at r1. The current block's MLP is never recomputed after mixing. +Only later blocks consume the intervention. Donors are graph-selected before +evaluating the model and receive only [head, r1] followed by fixed PAD tokens. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections import Counter, defaultdict +from numbers import Integral + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_multihop import pack_rows + +COMPONENTS = ("attention", "mlp", "both", "full") +SPLITS = ("test_composite", "test_full_composite", "ood_composite") +TRACE_FIELDS = ("input", "attention", "mlp", "residual") + + +def _choose(candidates, world_hash, seed, row, family): + if not candidates: + return None + material = json.dumps([world_hash, int(seed), list(map(int, row)), family]) + index = int.from_bytes(hashlib.sha256(material.encode()).digest(), "big") % len(candidates) + return sorted(candidates)[index] + + +def _path(head, relations, graph): + edges = [] + for relation in relations: + fact = graph.get((int(head), int(relation))) + if fact is None: + return None + head, index = fact + edges.append(index) + return int(head), tuple(edges) + + +def select_donors(world, seed, split="test_composite"): + """Select same-r1 donors using only truth and split membership. + + ID recipients and every donor-path fact are restricted to ID facts. OOD + recipients and donor paths analogously use only OOD facts. Different-bridge + paths must change the target and their complete queries must be untrained. + Same-bridge paths may be trained; their split is saved for separate scoring. + Rows without donors remain present with explicit masks and reasons. + """ + if split not in SPLITS: + raise ValueError(f"split must be one of {SPLITS}") + rows = world[split] + n, hops = len(rows), rows.shape[1] - 2 + if not 2 <= hops <= 4: + raise ValueError("Interventions require two-, three- or four-hop rows") + atom_index = {tuple(map(int, row)): i for i, row in enumerate(world["atomic"])} + atomic_split = "ood_atomic" if split == "ood_composite" else "id_atomic" + graph = { + (int(h), int(r)): (int(t), atom_index[int(h), int(r), int(t)]) + for h, r, t in world[atomic_split] + } + by_relation = defaultdict(list) + for (head, relation), (tail, _) in graph.items(): + by_relation[relation].append((head, relation, tail)) + training = {tuple(map(int, row[:-1])) for row in world["train_composite"]} + reserved = {tuple(map(int, row[:-1])) for row in world["test_full_composite"]} + result = { + "split": np.asarray(split), + "atomic_split": np.asarray(atomic_split), + "original_rows": rows.copy(), + "original_bridge": np.full(n, -1, dtype=np.int64), + "original_atomic_indices": np.full((n, hops), -1, dtype=np.int64), + } + for family in ("different", "same"): + result.update( + { + family + "_donor": np.full((n, 3), -1, dtype=np.int64), + family + "_counterfactual_rows": np.full_like(rows, -1), + family + "_atomic_indices": np.full((n, hops), -1, dtype=np.int64), + family + "_valid": np.zeros(n, dtype=bool), + family + "_candidate_count": np.zeros(n, dtype=np.int64), + family + "_reason": np.full(n, "no_eligible_same_relation_path", dtype="U64"), + family + "_counterfactual_split": np.full(n, "missing", dtype="U16"), + } + ) + reasons = ( + "same_head", + "same_bridge", + "missing_successor", + "same_target", + "head_is_answer", + "trained_counterfactual", + ) + for reason in reasons: + result["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) + for i, row in enumerate(rows): + head, r1, target = int(row[0]), int(row[1]), int(row[-1]) + original = _path(head, row[1:-1], graph) + if original is None or original[0] != target: + raise ValueError(f"Recipient is not a true all-{atomic_split} path") + bridge = graph[head, r1][0] + result["original_bridge"][i] = bridge + result["original_atomic_indices"][i] = original[1] + candidates = {"different": [], "same": []} + for dh, dr, db in by_relation[r1]: + continuation = _path(dh, row[1:-1], graph) + if continuation is None: + reason = "missing_successor" + else: + dt, edges = continuation + query = (dh, *map(int, row[1:-1])) + if dh != head and db == bridge and dh != target: + candidates["same"].append((dh, dr, db, dt, edges)) + reason = ( + "same_head" + if dh == head + else "same_bridge" + if db == bridge + else "same_target" + if dt == target + else "head_is_answer" + if dh in (target, dt) + else "trained_counterfactual" + if query in training + else None + ) + if reason is None: + candidates["different"].append((dh, dr, db, dt, edges)) + if reason: + result["different_rejected_" + reason][i] += 1 + for family in ("different", "same"): + choices = candidates[family] + result[family + "_candidate_count"][i] = len(choices) + donor = _choose(choices, world["metadata"]["dataset_sha256"], seed, row, family) + if donor is None: + continue + dh, dr, db, dt, edges = donor + cf = (dh, *map(int, row[1:-1]), dt) + result[family + "_donor"][i] = dh, dr, db + result[family + "_counterfactual_rows"][i] = cf + result[family + "_atomic_indices"][i] = edges + result[family + "_valid"][i] = True + result[family + "_reason"][i] = "eligible" + result[family + "_counterfactual_split"][i] = ( + "ood" + if split == "ood_composite" + else "train" + if cf[:-1] in training + else "reserved_test" + if cf[:-1] in reserved + else "unused" + ) + return result + + +def executed_blocks(model): + return list(model.iter_blocks()) if hasattr(model, "iter_blocks") else list(model.blocks) + + +@torch.no_grad() +def traced_forward( + model, + tokens, + positions=None, + *, + patch_layer=None, + component="both", + donor_trace=None, + identity=False, + return_trace=False, +): + """Run eval forward, optionally mixing one executed layer's r1 state. + + Trace fields contain only position r1, with shape [batch, width]. For a + component patch the output is (recipient input + mixed A) + mixed M. Full + replacement also changes the incoming residual, so it equals replacing A + and M only at execution layer zero for same-r1 donors, not at later layers. + """ + if model.training: + raise ValueError("Interventions require model.eval()") + blocks = executed_blocks(model) + if component not in COMPONENTS: + raise ValueError(f"component must be one of {COMPONENTS}") + if patch_layer is not None and ( + isinstance(patch_layer, bool) + or not isinstance(patch_layer, Integral) + or not 0 <= patch_layer < len(blocks) + ): + raise ValueError("patch_layer must index an executed block") + if identity and donor_trace is not None: + raise ValueError("Identity and donor patches are mutually exclusive") + if (donor_trace is not None or identity) != (patch_layer is not None): + raise ValueError("A patch layer requires exactly one donor or identity patch") + if donor_trace is not None and len(donor_trace) != len(blocks): + raise ValueError("Donor trace must cover every executed layer") + if tokens.shape[1] < 2: + raise ValueError("The r1 position requires at least two tokens") + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + trace = [] + for layer, block in enumerate(blocks): + z = block.ln1(x) + batch, length, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, length, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + a = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=0.0, + ) + a = attention.proj(a.transpose(1, 2).reshape(batch, length, width)) + m = block.mlp(block.ln2(x + a)) + residual = (x + a) + m + current = { + "input": x[:, 1].clone(), + "attention": a[:, 1].clone(), + "mlp": m[:, 1].clone(), + "residual": residual[:, 1].clone(), + } + if return_trace: + trace.append(current) + if layer == patch_layer: + donor = current if identity else donor_trace[layer] + if any(donor[key].shape != current[key].shape for key in TRACE_FIELDS): + raise ValueError("Donor trace has incompatible batch or width") + if component == "full": + replacement = donor["residual"] + else: + mixed_a = donor["attention"] if component in ("attention", "both") else a[:, 1] + mixed_m = donor["mlp"] if component in ("mlp", "both") else m[:, 1] + replacement = (x[:, 1] + mixed_a) + mixed_m + residual = residual.clone() + residual[:, 1] = replacement + x = residual + x = model.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, model.token.weight) + return (logits, trace) if return_trace else logits + + +@torch.no_grad() +def prefix_trace(model, prefixes, padded_length): + """Evaluate only two supplied tokens and a fixed zero suffix; never a target.""" + if prefixes.ndim != 2 or prefixes.shape[1] != 2 or padded_length < 4: + raise ValueError("Need two-token prefixes and the fixed hops+2 sequence length") + tokens = torch.zeros((len(prefixes), padded_length), dtype=torch.long, device=prefixes.device) + tokens[:, :2] = prefixes + positions = torch.ones((len(prefixes), 1), dtype=torch.long, device=prefixes.device) + return traced_forward(model, tokens, positions, return_trace=True)[1] + + +@torch.no_grad() +def evaluate_condition( + model, + rows, + device, + padded_length, + *, + donor_prefixes=None, + patch_layer=None, + component="both", + identity=False, + batch_size=1024, + verify_trace=False, +): + """Generate answer then EOS, reapplying exactly the same donor intervention.""" + if donor_prefixes is not None and donor_prefixes.shape != (len(rows), 2): + raise ValueError("Donor prefixes must align one-to-one with recipient rows") + answers, stops, logits_saved = [], [], [] + max_delta = prefix_delta = 0.0 + packed = pack_rows(rows, padded_length) + for start in range(0, len(rows), batch_size): + x, pos, _ = (torch.as_tensor(a[start : start + batch_size], device=device) for a in packed) + x = x.clone() + donor = None + if donor_prefixes is not None: + prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) + donor = prefix_trace(model, prefixes, padded_length) + arguments = dict( + patch_layer=patch_layer, + component=component, + donor_trace=donor, + identity=identity, + ) + logits, trace = traced_forward(model, x, pos, return_trace=True, **arguments) + if verify_trace: + if patch_layer is not None: + raise ValueError("Native-forward verification applies to baseline only") + reference = model(x, pos) + max_delta = max(max_delta, float((reference - logits).abs().max())) + if not torch.equal(reference.argmax(-1), logits.argmax(-1)): + raise AssertionError("Traced forward changes native argmax") + prefix = prefix_trace(model, x[:, :2], padded_length) + for full, truncated in zip(trace, prefix, strict=True): + for field in TRACE_FIELDS: + prefix_delta = max( + prefix_delta, float((full[field] - truncated[field]).abs().max()) + ) + answer = logits[:, 0].argmax(-1) + logits_saved.append(logits[:, 0].cpu().numpy()) + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + continuation = traced_forward(model, x, pos, **arguments) + if verify_trace: + reference = model(x, pos) + max_delta = max(max_delta, float((reference - continuation).abs().max())) + if not torch.equal(reference.argmax(-1), continuation.argmax(-1)): + raise AssertionError("Generated-answer trace changes native argmax") + answers.append(answer.cpu().numpy()) + stops.append(continuation[:, 1].argmax(-1).cpu().numpy()) + if max_delta > 1e-5 or prefix_delta > 1e-5: + raise AssertionError(f"Native/prefix trace disagreement: {max_delta}, {prefix_delta}") + return { + "answer": np.concatenate(answers) if answers else np.empty(0, dtype=np.int64), + "stop": np.concatenate(stops) if stops else np.empty(0, dtype=np.int64), + "answer_logits": np.concatenate(logits_saved) + if logits_saved + else np.empty((0, model.token.num_embeddings), dtype=np.float32), + }, { + "native_comparison_performed": verify_trace, + "native_max_logit_delta": max_delta, + "prefix_only_vs_full_all_layers_max_delta": prefix_delta, + } + + +def _metrics(arrays, condition, selected, original, target, baseline): + mask = selected & arrays[condition + "_valid"] + n, total = int(mask.sum()), len(mask) + answer, stop = arrays[condition + "_answer"], arrays[condition + "_stop"] + + def mean(value): + return float(value[mask].mean()) if n else None + + return { + "n": n, + "total_n": total, + "coverage": n / total if total else None, + "target_answer_accuracy": mean(answer == target), + "target_complete_accuracy": mean((answer == target) & (stop == 1)), + "original_answer_accuracy": mean(answer == original), + "original_complete_accuracy": mean((answer == original) & (stop == 1)), + "other_answer_rate": mean((answer != target) & (answer != original)), + "eos_accuracy": mean(stop == 1), + "answer_change_rate": mean(answer != baseline), + } + + +def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): + """Evaluate every executed layer, preserving all rows and prerequisite masks.""" + started = time.perf_counter() + model.eval() + split = str(donors["split"].item()) + rows = world[split] + if not np.array_equal(rows, donors["original_rows"]): + raise ValueError("Donor rows differ from the registered evaluation split") + n, padded_length = len(rows), int(world["metadata"]["hops"]) + 2 + arrays = {key: value.copy() for key, value in donors.items()} + all_rows = np.ones(n, dtype=bool) + conditions, audits = {}, {} + + def evaluate(name, mask, inputs, *, family=None, **kwargs): + result, audit = evaluate_condition( + model, inputs[mask], device, padded_length, batch_size=batch_size, **kwargs + ) + for key in ("answer", "stop"): + values = np.full(n, -1, dtype=np.int64) + values[mask] = result[key] + arrays[name + "_" + key] = values + arrays[name + "_valid"] = mask.copy() + targets = rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] + for suffix, labels in (("original_logit", rows[:, -1]), ("target_logit", targets)): + values = np.full(n, np.nan, dtype=np.float32) + values[mask] = result["answer_logits"][np.arange(mask.sum()), labels[mask]] + arrays[name + "_" + suffix] = values + conditions[name] = { + "family": family, + **{k: v for k, v in kwargs.items() if k in ("patch_layer", "component", "identity")}, + } + audits[name] = audit + + evaluate("baseline", all_rows, rows, verify_trace=True) + for family in ("different", "same"): + valid = donors[family + "_valid"] + # Match batch shape as well as sequence shape for floating-point controls. + evaluate(family + "_matched_baseline", valid, rows, family=family) + evaluate( + family + "_counterfactual_input", + valid, + donors[family + "_counterfactual_rows"], + family=family, + ) + blocks = executed_blocks(model) + for layer in range(len(blocks)): + for component in COMPONENTS: + identity_name = f"e{layer:03d}_identity_{component}" + evaluate( + identity_name, all_rows, rows, patch_layer=layer, component=component, identity=True + ) + for key in ("answer", "stop", "original_logit", "target_logit"): + if not np.array_equal(arrays[identity_name + "_" + key], arrays["baseline_" + key]): + raise AssertionError(f"Identity patch changes {identity_name}.{key}") + for family in ("different", "same"): + valid = donors[family + "_valid"] + name = f"e{layer:03d}_{family}_{component}" + evaluate( + name, + valid, + rows, + family=family, + patch_layer=layer, + component=component, + donor_prefixes=donors[family + "_donor"][valid, :2], + ) + if layer == len(blocks) - 1: + for key in ("answer", "stop", "original_logit"): + if not np.array_equal( + arrays[name + "_" + key][valid], + arrays[family + "_matched_baseline_" + key][valid], + ): + raise AssertionError("Last-block r1 patch changes later answer/EOS") + if layer == 0: + for family in ("different", "same"): + valid = donors[family + "_valid"] + for key in ("answer", "stop", "original_logit", "target_logit"): + left = arrays[f"e000_{family}_both_{key}"][valid] + right = arrays[f"e000_{family}_full_{key}"][valid] + if not np.array_equal(left, right): + raise AssertionError("First-layer same-r1 both/full differ") + atomics, _ = evaluate_condition( + model, world["atomic"], device, padded_length, batch_size=batch_size + ) + atom_correct = (atomics["answer"] == world["atomic"][:, -1]) & (atomics["stop"] == 1) + arrays["atomic_rows"] = world["atomic"].copy() + arrays["atomic_answer"], arrays["atomic_stop"] = atomics["answer"], atomics["stop"] + groups = {"all_rows": all_rows} + prerequisites = {} + for family in ("original", "different", "same"): + valid = all_rows if family == "original" else donors[family + "_valid"] + indices = donors[family + "_atomic_indices"] + correct = np.zeros_like(indices, dtype=bool) + correct[valid] = atom_correct[indices[valid]] + arrays[family + "_atomic_complete_correct"] = correct + complete = valid & correct.all(axis=1) + groups[family + "_all_atomic_correct"] = complete + prerequisites[family] = { + "n": int(valid.sum()), + "total_n": n, + "coverage": float(valid.mean()) if n else None, + "all_hops_complete_accuracy": float(complete[valid].mean()) if valid.any() else None, + "per_hop_complete_accuracy": correct[valid].mean(axis=0).tolist() + if valid.any() + else None, + } + for family in ("different", "same"): + valid = donors[family + "_valid"] + baseline_correct = (arrays[family + "_matched_baseline_answer"] == rows[:, -1]) & ( + arrays[family + "_matched_baseline_stop"] == 1 + ) + groups[family + "_donor_available"] = valid + groups[family + "_donor_missing"] = ~valid + cf = family + "_counterfactual_input" + cf_correct = valid & ( + arrays[cf + "_answer"] == donors[family + "_counterfactual_rows"][:, -1] + ) + cf_correct &= arrays[cf + "_stop"] == 1 + groups[family + "_native_original_and_counterfactual_correct"] = ( + baseline_correct & cf_correct + ) + for category in ("train", "reserved_test", "unused", "ood"): + groups[family + "_counterfactual_" + category] = valid & ( + donors[family + "_counterfactual_split"] == category + ) + scores = {} + for group, mask in groups.items(): + arrays["subset_" + group] = mask.copy() + scored = {} + for condition, description in conditions.items(): + family = description["family"] + target = ( + rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] + ) + scored[condition] = _metrics( + arrays, + condition, + mask, + rows[:, -1], + target, + arrays[(family + "_matched_baseline" if family else "baseline") + "_answer"], + ) + scores[group] = { + "n": int(mask.sum()), + "total_n": n, + "coverage": float(mask.mean()) if n else None, + "conditions": scored, + } + return { + "split": split, + "atomic_split": str(donors["atomic_split"].item()), + "sample_rule": "training-independent fixed probe" + if split == "test_composite" + else "full split", + "hops": padded_length - 2, + "executed_depth": len(blocks), + "unique_layers": len(model.blocks), + "repeats": getattr(model, "repeats", 1), + "patch_position": 1, + "conditions": conditions, + "scores": scores, + "atomic_preconditions": prerequisites, + "donor_coverage": { + family: { + "n": int(donors[family + "_valid"].sum()), + "total_n": n, + "reasons": dict(Counter(donors[family + "_reason"].tolist())), + "counterfactual_split": dict( + Counter(donors[family + "_counterfactual_split"].tolist()) + ), + } + for family in ("different", "same") + }, + "engineering_checks": { + "native_trace": audits["baseline"], + "identity_all_layers_components": True, + "first_layer_same_r1_both_equals_full": True, + "last_layer_r1_patch_cannot_change_later_answer_or_eos": True, + "donor_nonpadding_tokens": 2, + "donor_padded_length": padded_length, + "mlp_recomputed_after_mixing": False, + "eos_uses_generated_answer_and_reapplies_same_patch": True, + }, + "interpretation": ( + "End-to-end prefix-state interventions, not proof that facts reside only in MLP. " + "Component mixtures retain recipient incoming residual. Both/full are equivalent " + "only at first execution layer with same r1; later differences are expected. " + "Facts and queries within one world are not independent experimental worlds." + ), + "evaluation_seconds": time.perf_counter() - started, + }, arrays diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_model.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed46483cb7277c172f8848cefb9e2d085d67c0b --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_model.py @@ -0,0 +1,108 @@ +"""Depth-shared GPT blocks for controlled composition-learning comparisons. + +This keeps the existing SmallGPT tokenization, causal attention, dropout and tied +readout. ``config.layers`` counts independently parameterized blocks; each loop +executes this whole block group. Positions and token embeddings are added once. +""" + +from __future__ import annotations + +import math +from dataclasses import replace +from numbers import Integral + +import torch +from torch.nn import functional as F + +from .bios_model import matmul_flops +from .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, + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f3cac329831b303c1dc9ca05c270837de0614eec --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py @@ -0,0 +1,342 @@ +"""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 fed +to the model. ID donors must have actually occurred at the first position of +composite training. OOD donors have zero composite exposure at either position. +All eligible donors and ID x OOD pairs are retained. A pair is a repeated +measurement of its recipient, not an independent query or world. +""" + +from __future__ import annotations + +import hashlib +import json +from collections import defaultdict +from collections.abc import Mapping +from 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 result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..48fa45f53e08b7da9c17a92df8eb5ba4efd8a229 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py @@ -0,0 +1,353 @@ +"""Same-bridge prefix interventions, with query-balanced donor summaries. + +The donor selector never sees model scores. This evaluator reuses the audited +first-block component mixer; it does not retrain models or recompute the current +MLP after mixing. All candidate donors are evaluated, then averaged within the +recipient query before any world-level aggregation. +""" + +from __future__ import annotations + +import hashlib +import time + +import numpy as np +import 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", + } diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_supervision.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_supervision.py new file mode 100644 index 0000000000000000000000000000000000000000..104364e93299229e1a8216acabb046e5fae1dde4 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_supervision.py @@ -0,0 +1,349 @@ +"""Paired continuation: terminal versus distributed answer supervision. + +Historical model/trainer files remain unchanged. All heads branch off the same +trajectory; their LayerNorm outputs never replace the recurrent residual state. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_data import StratifiedStream +from .grok_loop_model import LoopGPT, flops +from .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, + }, + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_train.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_train.py new file mode 100644 index 0000000000000000000000000000000000000000..ffee809fcc7335c7b68e3321427ffcc0342c3086 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_loop_train.py @@ -0,0 +1,214 @@ +"""Frozen loop comparison trainer with stratified exposure and executed-depth FLOPs.""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_data import StratifiedStream +from .grok_loop_model import LoopGPT, flops +from .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] diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_multihop.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_multihop.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0824b5e038658e91c3cbc5e521a316861f20a4 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_multihop.py @@ -0,0 +1,278 @@ +"""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 json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_json +from .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] diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_multihop_data.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_multihop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d857233765485dc4bf1a210fda171628a20d9817 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_multihop_data.py @@ -0,0 +1,245 @@ +"""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 and +one 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 hashlib +import math + +import numpy as np + +from .grok_depth_data import ENTITY_OFFSET +from .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="= 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, + } diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_usage_data.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_usage_data.py new file mode 100644 index 0000000000000000000000000000000000000000..04e5650b0bdea1e25cfde235045efc9b14e0c769 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_usage_data.py @@ -0,0 +1,397 @@ +"""Paired fact-use assignments and constituent-occurrence repetition controls. + +The same random graph and held-out queries are used in every arm. A/B change +which random fact cohort may occur in composition training. repA/repB replace +each 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 copy +import hashlib +from collections.abc import Mapping + +import numpy as np + +from .grok_depth_data import build_world as build_graph_world +from .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=" 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"] diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_usage_train.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_usage_train.py new file mode 100644 index 0000000000000000000000000000000000000000..8460dcf149ad8f229cc4c16783e8e7429acd0610 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grok_usage_train.py @@ -0,0 +1,261 @@ +"""Paired training of composition experience versus constituent-fact repetition.""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .grok_multihop import autonomous_calls, evaluate_rows, pack_rows +from .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(), + }, + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..9530969731263b69c576f12989a3610ead6036f5 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py @@ -0,0 +1,421 @@ +"""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 copy +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step_mechanism import traced_forward +from .grok_depth import write_json +from .latent_scaling import model_digest +from .storage_composition import generate_rows, pack_sentences +from .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 result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grokking_reproduction.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grokking_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f7ba958ea469d5edea6e98c9941dcc49427a6f --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/grokking_reproduction.py @@ -0,0 +1,563 @@ +"""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 initialization +are retained. SDPA, selecting supervised logits, CUDA graphs and bf16 AMP are +explicit execution/numerical adaptations, checked against Hugging Face GPT-2. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F +from transformers import GPT2Config, GPT2LMHeadModel, GPT2TokenizerFast + +from .bios_model import ModelConfig, matmul_flops +from .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"" for i in range(2000)] + [f"" for i in range(200)] + vocab += ["", "", "", "", "", ""] + 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(""), + "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 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) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_data.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_data.py new file mode 100644 index 0000000000000000000000000000000000000000..b67eee718fd00d44c1de51a2821e24aa7251196b --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_data.py @@ -0,0 +1,396 @@ +"""CounterFact true-label data, explicit audit decisions and indivisible subject pools.""" + +from __future__ import annotations + +import hashlib +import re +import unicodedata +from 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"(? 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 coverage diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_followup.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..89afed17153ba18880997b4089ddadb1b997f80b --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_followup.py @@ -0,0 +1,103 @@ +"""Fixed-content worlds and conservative full-entity answer parsing.""" + +from __future__ import annotations + +import hashlib +import re +import unicodedata +from 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}")) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_future.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_future.py new file mode 100644 index 0000000000000000000000000000000000000000..24171d0e5bc0c31f7cc4ac32af06d86dd8ec15f4 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_future.py @@ -0,0 +1,148 @@ +"""Exploratory kernel prediction and balanced multi-hop worlds, September 2026.""" + +from __future__ import annotations + +import hashlib +import json +from 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])] diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_interface.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..0135ee958b76df5e2df2aa4ea0c2c57c40f2b24a --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_interface.py @@ -0,0 +1,566 @@ +"""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 hashlib +import importlib.metadata +import json +import platform +import sys +import time +from dataclasses import asdict +from pathlib import Path + +import numpy as np +import torch +import 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 summary diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_learning.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..78155602739f614f369304edc920dbb75b590bea --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_learning.py @@ -0,0 +1,187 @@ +"""Prospective Hebbian study: numerical calibration and auditable common primitives.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import math +import os +from datetime import datetime, timezone +from 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()) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_model.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_model.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8e5da864f18f673c829d8b68db641d728ca437 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_model.py @@ -0,0 +1,339 @@ +"""FP32 Qwen adapter. All CE/KL reductions preserve per-sequence weighting.""" + +from __future__ import annotations + +import copy +import hashlib +import os +import time + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import AutoModelForCausalLM, AutoTokenizer, StoppingCriteria, StoppingCriteriaList + +from .hebbian_data import TEMPLATE, score_answer +from .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}, + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_statistics.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..52bcc965886f86bf20041ec40ce6aa95b96a725f --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_statistics.py @@ -0,0 +1,168 @@ +"""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 None diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_train.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_train.py new file mode 100644 index 0000000000000000000000000000000000000000..f70905fa1648aeba1d7bad8aca55a77bbcadd72f --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/hebbian_train.py @@ -0,0 +1,811 @@ +"""Paired formation/adaptation, prospective diagnostics and exact state resumption.""" + +from __future__ import annotations + +import itertools +import json +import random +import time + +import numpy as np +import torch +import 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", + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/independent_alignment.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/independent_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..88bc143ff025e794e6a5f1ec62e514b99563d88b --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/independent_alignment.py @@ -0,0 +1,124 @@ +"""Replicate the existing state objective in two ordinary, independent GPT layers.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import representation_alignment as original +from .grok_depth import write_json +from .latent_scaling import build_world, model_digest +from .storage_composition import data_digest, evaluate, file_hash + + +def validate_model(spec, model): + if spec["layers"] != 2 or spec["repeats"] != 1: + raise ValueError("This replication requires two independent layers, executed once") + blocks = list(model.iter_blocks()) + assert len(blocks) == 2 and blocks[0] is not blocks[1] + assert not {p.data_ptr() for p in blocks[0].parameters()} & { + p.data_ptr() for p in blocks[1].parameters() + } + assert all(p.requires_grad for p in model.parameters()) + + +@torch.no_grad() +def diagnose(model, world, device): + """Original readout of a pure first-hop prefix; no fitted probe or final answer.""" + model.eval() + metrics, predictions = {}, {} + for task in ("common_atomic", "familiar_test", "strict_test"): + rows = world[task] + prefixes = np.column_stack( + (np.full(len(rows), 2), rows[:, 0], np.full(len(rows), 3), rows[:, 1]) + ) + labels = rows[:, 2] + guesses, cosines = [], [] + for start in range(0, len(rows), 256): + tokens = torch.as_tensor(prefixes[start : start + 256], device=device) + targets = torch.as_tensor(labels[start : start + 256], device=device) + _, state = model(tokens, return_bridge=True) + logits = F.linear(model.ln_final(state), model.token.weight) + guesses.append(logits.argmax(-1).cpu().numpy()) + cosines.append(F.cosine_similarity(state, model.token(targets)).cpu().numpy()) + guess, cosine = np.concatenate(guesses), np.concatenate(cosines) + correct = guess == labels + metrics[task] = dict( + n=len(rows), + first_hop_original_readout_accuracy=float(correct.mean()), + mean_cosine_to_input_embedding=float(cosine.mean()), + pure_prefix=True, + ) + predictions.update( + {task + "_guess": guess, task + "_correct": correct, task + "_cosine": cosine} + ) + return metrics, predictions + + +def train(spec, out, source, device): + model = original.new_model(spec, "cpu") + validate_model(spec, model) + assert model_digest(model) == spec["initial_model_sha256"] + assert data_digest(build_world(spec)) == spec["data_sha256"] + del model + # Keep the historical trainer, objective, sampling, optimizer and arithmetic intact. + original.train(spec, out, source, device) + out = Path(out) + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + model = original.new_model(spec, device) + model.load_state_dict(payload["model"]) + metrics, predictions = diagnose(model, build_world(spec), device) + write_json(out / "state-diagnostics.json", metrics) + np.savez_compressed(out / "state-predictions.npz", **predictions) + + +def audit(out, device): + """Independent process reload of full generation and original intermediate readout.""" + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + spec = payload["spec"] + model = original.new_model(spec, device) + validate_model(spec, model) + model.load_state_dict(payload["model"]) + world = build_world(spec) + stored_world = np.load(out / "world.npz") + for key, value in world.items(): + np.testing.assert_array_equal(value, stored_world[key]) + assert data_digest(world) == spec["data_sha256"] + complete = json.loads((out / "complete.json").read_text()) + assert file_hash(out / "model.pt") == complete["model_sha256"] + metrics, predictions = evaluate(model, world, "low", device) + saved = np.load(out / f"predictions-{spec['steps']:06d}.npz") + maximum = 0.0 + for key, value in predictions.items(): + if key.endswith("nll"): + maximum = max(maximum, float(np.max(np.abs(value - saved[key])))) + np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(value, saved[key]) + state_metrics, state_predictions = diagnose(model, world, device) + saved_state = np.load(out / "state-predictions.npz") + for key, value in state_predictions.items(): + if key.endswith("cosine"): + np.testing.assert_allclose(value, saved_state[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(value, saved_state[key]) + write_json( + out / "audit.json", + dict( + passed=True, + metrics=metrics, + state_metrics=state_metrics, + max_nll_error=maximum, + allow_tf32=True, + independent_parameters=True, + ), + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/interface_editing.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/interface_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..7065e910e82f4aa54e312af63f4f99925c4e1269 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/interface_editing.py @@ -0,0 +1,759 @@ +"""Local factual updates and downstream composition in existing aligned GPTs. + +Cases are selected from the graph alone, before loading any model predictions. +Every edit has a same-budget old-fact sham, fresh optimizer, and frozen parent +replay reference. No composition labels or intermediate-state targets enter +optimization. Finite replay KL is a regularizer, not exact preservation. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import build_world, model_digest +from .representation_alignment import new_model +from .storage_composition import data_digest, file_hash, generate_rows, pack_sentences + +ROLES = ("first", "second") +STRATA = ("familiar", "strict") +DEFAULT_NODES = (0, 32, 128, 512) + + +def _rows(values, width): + return np.asarray(values, dtype=np.int64).reshape(-1, width) + + +def _unique(values, width): + return _rows(sorted(set(map(tuple, _rows(values, width)))), width) + + +def _hash_json(value): + return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() + + +def _batch_hash(batch): + digest = hashlib.sha256() + for tensor in batch: + array = tensor.detach().cpu().numpy() + digest.update(str(array.dtype).encode()) + digest.update(str(array.shape).encode()) + digest.update(array.tobytes()) + return digest.hexdigest() + + +def learned_atoms(world): + """Only atomics actually supervised in the representation parent.""" + return _unique(np.concatenate([world["common_atomic"], world["anchor_atomic"]]), 3) + + +def composition_pools(world): + """All legal untrained queries, plus the original holdout and training sets.""" + trained = set(map(tuple, world["train_composite"])) + full = _unique(np.concatenate([world["available_composite"], world["familiar_test"]]), 5) + familiar = _rows([r for r in full if tuple(r) not in trained], 5) + return { + "familiar": familiar, + "strict": world["strict_test"].copy(), + "registered_familiar": world["familiar_test"].copy(), + "train": world["train_composite"].copy(), + } + + +def affected(rows, fact, role): + """Whether a query uses this factual address, independently of its answer.""" + columns = (0, 1) if role == "first" else (2, 3) + return (rows[:, columns[0]] == fact[0]) & (rows[:, columns[1]] == fact[1]) + + +def rewrite(rows, old_fact, new_fact, role, lookup): + result = rows.copy() + mask = affected(rows, old_fact, role) + if role == "first": + result[mask, 2] = new_fact[2] + for index in np.flatnonzero(mask): + result[index, 4] = lookup[int(new_fact[2]), int(rows[index, 3])] + else: + result[mask, 4] = new_fact[2] + return result + + +def graph_cases(parent_spec, *, seed=780011, per_cell=2, replay_n=32): + """Return JSON-compatible selected cases and graph-only eligibility counts. + + Each distinct atomic address receives at most one counterfactual per role. + First-hop replacements stay in the original familiar/strict bridge group and + change at least one affected untrained composition answer. Strict cases never + borrow a bridge with composition experience from the familiar group. + """ + if per_cell < 1 or replay_n < 1: + raise ValueError("Positive case and replay counts are required") + world = build_world(parent_spec) + atoms = learned_atoms(world) + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + pools = composition_pools(world) + rng = np.random.default_rng(seed + int(parent_spec["world"])) + candidates, qualification = [], {} + for role in ROLES: + for stratum in STRATA: + rows = pools[stratum] + addresses = _unique(rows[:, [0, 1, 2] if role == "first" else [2, 3, 4]], 3) + bridges = np.unique(rows[:, 2]) + # Include all trained bridges in that group, even if the holdout + # happens not to visit them (strict rows enumerate all chains). + group = world["background_atomic"] if stratum == "familiar" else world["common_atomic"] + group_bridges = np.unique(group[group[:, 1] >= 17, 0]) + if stratum == "strict": + familiar_bridges = world["background_atomic"] + familiar_bridges = familiar_bridges[familiar_bridges[:, 1] >= 17, 0] + group_bridges = np.setdiff1d(group_bridges, familiar_bridges) + bridges = np.union1d(bridges, group_bridges) + tails = np.unique(atoms[atoms[:, 1] >= 17, 2]) + eligible, replacement_count = [], 0 + for old in addresses: + impacted = rows[affected(rows, old, role)] + choices = [] + for value in bridges if role == "first" else tails: + if value == old[2]: + continue + new = [int(old[0]), int(old[1]), int(value)] + updated = rewrite(impacted, old, new, role, lookup) + if np.any(updated[:, -1] != impacted[:, -1]): + choices.append(new) + replacement_count += len(choices) + if choices: + eligible.append((old.tolist(), choices)) + key = f"{role}_{stratum}" + qualification[key] = { + "candidate_addresses": len(addresses), + "eligible_addresses": len(eligible), + "eligible_replacements": replacement_count, + "untrained_queries": len(rows), + } + if len(eligible) < per_cell: + raise ValueError(f"Insufficient graph-qualified {key} cases: {qualification[key]}") + order = rng.permutation(len(eligible))[:per_cell] + for serial, index in enumerate(order): + old, choices = eligible[index] + new = choices[int(rng.integers(len(choices)))] + candidates.append( + { + "case_id": f"{key}-{serial:02d}", + "role": role, + "stratum": stratum, + "old_fact": old, + "new_fact": new, + } + ) + for case in candidates: + tasks, originals = case_tasks(world, case, replay_indices=None) + necessary = set(map(tuple, tasks["necessary_atomic"])) + allowed = [ + i + for i, row in enumerate(atoms) + if tuple(row) != tuple(case["old_fact"]) and tuple(row) not in necessary + ] + if len(allowed) < replay_n: + raise ValueError("Insufficient independent replay atomics") + case["replay_indices"] = sorted(map(int, rng.choice(allowed, replay_n, replace=False))) + case["affected_untrained_n"] = {name: len(rows) for name, rows in originals.items()} + return candidates, qualification + + +def case_tasks(world, case, replay_indices=None): + """Construct E/R/U/D with address-based exclusions and recomputed truth.""" + atoms = learned_atoms(world) + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + old, new, role = case["old_fact"], case["new_fact"], case["role"] + if lookup[tuple(old[:2])] != old[2] or old[:2] != new[:2] or old[2] == new[2]: + raise ValueError("An edit must replace one existing factual value") + tasks = {"E_old": _rows([old], 3), "E_new": _rows([new], 3)} + originals, necessary = {}, [] + for stratum, rows in composition_pools(world).items(): + mask = affected(rows, old, role) + tasks[f"U_{stratum}"] = rows[~mask].copy() + old_rows = rows[mask].copy() + new_rows = rewrite(old_rows, old, new, role, lookup) + changed = old_rows[:, -1] != new_rows[:, -1] + if stratum == "train": + # Training-query transfer is reported separately from held-out D. + name = f"T_{role}_train" + originals[name] = old_rows + tasks[name] = new_rows + else: + name = f"D_{role}_{stratum}" + originals[name] = old_rows[changed] + tasks[name] = new_rows[changed] + same = f"S_same_answer_{role}_{stratum}" + originals[same] = old_rows[~changed] + tasks[same] = new_rows[~changed] + if stratum in STRATA: + for h, r1, b, r2, t in tasks[name]: + prerequisite = (b, r2, t) if role == "first" else (h, r1, b) + necessary.append(prerequisite) + tasks["necessary_atomic"] = _unique(necessary, 3) + replay = case.get("replay_indices", []) if replay_indices is None else replay_indices + if len(set(replay)) != len(replay): + raise ValueError("Replay indices must be unique") + target = np.flatnonzero(np.all(atoms == np.asarray(old), axis=1)) + if len(target) != 1 or int(target[0]) in replay: + raise ValueError("Replay cannot contain the edited address") + tasks["R_atomic"] = atoms[replay].copy() + tasks["U_atomic"] = np.delete(atoms, [int(target[0]), *replay], axis=0) + return tasks, originals + + +def answer_batch(rows, device): + """Only answer, punctuation and EOS labels; no prefix or bridge labels.""" + tokens, labels = pack_sentences(_rows(rows, 3)) + positions = np.tile([4, 5, 6], (len(rows), 1)) + targets = labels[np.arange(len(rows))[:, None], positions] + expected = np.column_stack([np.asarray(rows)[:, 2], np.full(len(rows), 5), np.ones(len(rows))]) + np.testing.assert_array_equal(targets, expected) + return tuple(torch.as_tensor(x, device=device) for x in (tokens, positions, targets)) + + +def edit_objective(model, target_batch, replay_batch, parent_log, replay_weight=1.0): + target = model(target_batch[0], positions=target_batch[1]) + ce = F.cross_entropy(target.flatten(0, 1), target_batch[2].flatten()) + replay = model(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + if parent_log.requires_grad: + raise ValueError("Replay reference must be detached") + kl = F.kl_div(replay, parent_log, log_target=True, reduction="none").sum(-1).mean() + return ce + replay_weight * kl, ce, kl + + +def _generate(model, rows, device, batch_size): + if len(rows): + return generate_rows(model, rows, device, batch_size=batch_size) + return ( + {"n": 0, "accuracy": None, "answer_accuracy": None, "answer_nll": None}, + { + "generated": np.empty((0, 3), dtype=np.int64), + "correct": np.empty(0, dtype=bool), + "answer_nll": np.empty(0), + }, + ) + + +def evaluate_case(model, tasks, originals, parent_correct, role, device, batch_size=512): + """Full-pool scores and separately labelled prerequisite/parent subsets.""" + metrics, raw = {}, {} + for name, rows in tasks.items(): + values, predictions = _generate(model, rows, device, batch_size) + raw.update({f"{name}__{k}": v for k, v in predictions.items()}) + if name in originals: + old = originals[name] + generated = predictions["generated"] + changed = old[:, -1] != rows[:, -1] + old_correct = (generated[:, 0] == old[:, -1]) & np.all( + generated[:, 1:] == [5, 1], axis=1 + ) + prerequisite = rows[:, [2, 3, 4] if role == "first" else [0, 1, 2]] + _m, needed = _generate(model, prerequisite, device, batch_size) + edited_ok = metrics["E_new"]["accuracy"] == 1.0 + covered = needed["correct"] & edited_ok + baseline = parent_correct[name] + valid_parent = baseline & changed + correct = predictions["correct"] + values.update( + { + "changed_answer_n": int(changed.sum()), + "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None, + "parent_correct_n": int(baseline.sum()), + "parent_correct_coverage": float(baseline.mean()) if len(rows) else None, + "new_following_parent_correct": float(correct[valid_parent].mean()) + if valid_parent.any() + else None, + "old_retained_parent_correct": float(old_correct[valid_parent].mean()) + if valid_parent.any() + else None, + "direct_edit_success": edited_ok, + "necessary_atomic_correct_n": int(needed["correct"].sum()), + "operation_correct_n": int(covered.sum()), + "operation_correct_coverage": float(covered.mean()) if len(rows) else None, + "new_following_operation_correct": float(correct[covered].mean()) + if covered.any() + else None, + } + ) + raw[f"{name}__parent_correct"] = baseline + raw[f"{name}__operation_correct"] = covered + raw[f"{name}__old_correct"] = old_correct + raw[f"{name}__necessary_generated"] = needed["generated"] + raw[f"{name}__new_rows"] = rows + raw[f"{name}__old_rows"] = old + metrics[name] = values + return metrics, raw + + +def editable_parameters(model, scope="mlp", block_index=0): + prefix = f"blocks.{block_index}.mlp." + selected = [ + name + for name, _ in model.named_parameters() + if name.startswith(prefix) and (scope == "mlp" or name == prefix + "down.weight") + ] + if scope not in {"mlp", "down"} or not selected: + raise ValueError("Unknown or empty local parameter scope") + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name in selected) + parameter.grad = None + return selected + + +def _configure(device): + device = torch.device(device) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + return device + + +def _load_parent(parent_dir, device): + path = Path(parent_dir) / "model.pt" + payload = torch.load(path, map_location="cpu", weights_only=False) + model = new_model(payload["spec"], device).eval() + model.load_state_dict(payload["model"]) + world = build_world(payload["spec"]) + if (Path(parent_dir) / "world.npz").exists(): + with np.load(Path(parent_dir) / "world.npz") as saved: + for name, rows in world.items(): + np.testing.assert_array_equal(rows, saved[name]) + return model, world, payload["spec"] + + +def _parent_masks(parent, originals, device, batch_size): + return { + name: _generate(parent, rows, device, batch_size)[1]["correct"] + for name, rows in originals.items() + } + + +def run(spec, out, device="cuda:0"): + """Execute one parent, a graph-selected case set and optional development lr grid. + + The caller owns source freezing, resource allocation and W&B startup. Each + branch has run/learning/complete artifacts. Root ``step`` is a strictly + increasing evaluation index, including every branch's unchanged node zero; + ``optimizer_updates`` separately records cumulative optimization work. + Target labels and replay KL positions have separate exposure counters. + ``status.json`` retains completed-branch progress, explicitly labelled in + the manifest; it does not define the tracking series' step axis. + """ + device = _configure(device) + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite an existing attempt: {out}") + nodes = spec.get("nodes", list(DEFAULT_NODES)) + if not nodes or nodes[0] != 0 or nodes != sorted(set(nodes)) or nodes[-1] <= 0: + raise ValueError("Nodes must increase from zero to a positive fixed endpoint") + rates = spec.get("learning_rates", [spec.get("lr", 1e-4)]) + if not rates or any(lr <= 0 for lr in rates) or len(set(rates)) != len(rates): + raise ValueError("Learning rates must be positive and unique") + if spec.get("phase") not in {"development", "engineering"} and len(rates) > 1: + raise ValueError("Learning-rate grids are development-only") + arms = spec.get("arms", ["edit", "sham"]) + if sorted(arms) != ["edit", "sham"]: + raise ValueError("Every case requires paired edit and sham branches") + parent, world, parent_spec = _load_parent(spec["parent_dir"], device) + parent_hash = model_digest(parent) + cases, qualification = graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + if "case_ids" in spec: + requested = set(spec["case_ids"]) + if not requested or not requested <= {c["case_id"] for c in cases}: + raise ValueError("Unknown/empty fixed graph-selected case subset") + cases = [c for c in cases if c["case_id"] in requested] + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "cases": cases, + "qualification": qualification, + "case_sha256": _hash_json(cases), + "parent_file_sha256": file_hash(Path(spec["parent_dir"]) / "model.pt"), + "parent_model_sha256": parent_hash, + "world_sha256": data_digest(world), + "created_utc": utc(), + "dtype": "float32", + "allow_tf32": True, + "pid": os.getpid(), + "gpu": device.index if device.type == "cuda" else None, + "branches": len(cases) * len(rates) * len(arms), + "planned_updates": len(cases) * len(rates) * len(arms) * nodes[-1], + "planned_evaluations": len(cases) * len(rates) * len(arms) * len(nodes), + "learning_step_unit": "evaluation_index", + "status_step_unit": "completed_branches", + "scope_warning": "The selected MLP is shared across all repeated executions", + } + write_json(out / "run.json", manifest) + write_json(out / "cases.json", cases) + np.savez_compressed(out / "world.npz", **world) + root_learning, branch_summaries, completed_steps = [], [], 0 + started = time.perf_counter() + training_seconds = 0.0 + batch_size = spec.get("eval_batch_size", 512) + for case in cases: + tasks, originals = case_tasks(world, case) + parent_correct = _parent_masks(parent, originals, device, batch_size) + parent_metrics, parent_predictions = evaluate_case( + parent, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + case_out = out / case["case_id"] + case_out.mkdir() + np.savez_compressed(case_out / "parent-predictions.npz", **parent_predictions) + write_json(case_out / "parent-metrics.json", parent_metrics) + np.savez_compressed(case_out / "tasks.npz", **tasks) + replay_batch = answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + parent_log = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1).detach() + for lr in rates: + for arm in arms: + branch_name = f"lr{lr:.8g}-{arm}" + branch_out = case_out / branch_name + branch_out.mkdir() + model = copy.deepcopy(parent).eval() + selected = editable_parameters( + model, + spec.get("parameter_scope", "mlp"), + spec.get("block_index", 0), + ) + parameters = dict(model.named_parameters()) + optimizer = torch.optim.Adam([parameters[n] for n in selected], lr=lr) + target = tasks["E_new" if arm == "edit" else "E_old"] + target_batch = answer_batch(target, device) + write_json( + branch_out / "run.json", + { + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + "parent_model_sha256": parent_hash, + "editable_parameters": selected, + "optimizer": "Adam, fresh state, zero weight decay", + "sampling": "same fixed full replay batch on every update; no dropout", + "old_fact_sha256": _hash_json(case["old_fact"]), + "new_fact_sha256": _hash_json(case["new_fact"]), + "target_batch_sha256": _batch_hash(target_batch), + "replay_batch_sha256": _batch_hash(replay_batch), + "parent_reference_sha256": _batch_hash((parent_log,)), + "nodes": nodes, + }, + ) + np.savez_compressed( + branch_out / "replay-reference.npz", log_probabilities=parent_log.cpu().numpy() + ) + step, losses, history = 0, [], [] + for node in nodes: + if device.type == "cuda": + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, ce, kl = edit_objective( + model, + target_batch, + replay_batch, + parent_log, + spec.get("replay_weight", 1.0), + ) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite edit loss at {step}") + loss.backward() + gradient_norm = torch.nn.utils.clip_grad_norm_( + [parameters[n] for n in selected], + spec.get("clip_norm", 1.0), + ) + optimizer.step() + step += 1 + losses.append( + { + "step": step, + "loss": float(loss.detach()), + "target_ce": float(ce.detach()), + "replay_kl": float(kl.detach()), + "gradient_norm": float(gradient_norm), + } + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + metrics, predictions = evaluate_case( + model, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + current_hash = model_digest(model) + record = { + "step": step, + "metrics": metrics, + "model_sha256": current_hash, + "target_success": metrics["E_new" if arm == "edit" else "E_old"]["accuracy"] + == 1, + "U_atomic_at_least_95": metrics["U_atomic"]["accuracy"] >= 0.95, + "loss": losses[-1] if losses else None, + } + history.append(record) + write_json(branch_out / "learning.json", history) + write_json(branch_out / "losses.json", losses) + np.savez_compressed(branch_out / f"predictions-{step:06d}.npz", **predictions) + torch.save( + { + "edited_tensors": { + n: parameters[n].detach().cpu().clone() for n in selected + }, + "model_sha256": current_hash, + "step": step, + }, + branch_out / f"tensors-{step:06d}.pt", + ) + root_learning.append( + { + "step": len(root_learning), + "branch_step": step, + "completed_branches": len(branch_summaries) + int(step == nodes[-1]), + "optimizer_updates": completed_steps + step, + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + "metrics": metrics, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": (completed_steps + step) * (1 + len(tasks["R_atomic"])), + "target_supervised_tokens": (completed_steps + step) * 3, + "replay_distillation_positions": (completed_steps + step) + * len(tasks["R_atomic"]) + * 3, + } + ) + write_json(out / "learning.json", root_learning) + write_json( + out / "status.json", + { + "state": "running", + "step": len(branch_summaries), + "optimizer_updates": completed_steps + step, + "budget": manifest["branches"], + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + }, + ) + changed = [ + n + for n, t in model.state_dict().items() + if not torch.equal(t, parent.state_dict()[n]) + ] + if set(changed) - set(selected) or model_digest(parent) != parent_hash: + raise AssertionError("A frozen parameter or the parent changed") + complete = { + "case_id": case["case_id"], + "role": case["role"], + "stratum": case["stratum"], + "lr": lr, + "arm": arm, + "path": str(branch_out.relative_to(out)), + "metrics": metrics, + "steps": step, + "changed_tensors": changed, + "parent_model_sha256": parent_hash, + "final_model_sha256": current_hash, + "delta_l2": float( + torch.sqrt( + sum( + (parameters[n] - dict(parent.named_parameters())[n]).square().sum() + for n in selected + ) + ).detach() + ), + "tensor_file_sha256": file_hash(branch_out / f"tensors-{step:06d}.pt"), + } + write_json(branch_out / "complete.json", complete) + branch_summaries.append(complete) + completed_steps += step + result = { + "status": "complete", + "branches": branch_summaries, + "updates": completed_steps, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "finished_utc": utc(), + "case_sha256": manifest["case_sha256"], + } + write_json(out / "complete.json", result) + write_json( + out / "status.json", + { + "state": "complete", + "step": len(branch_summaries), + "optimizer_updates": completed_steps, + "budget": manifest["branches"], + }, + ) + return result + + +def audit(out, device="cuda:0"): + """Reload every saved node from parent plus exact tensors and re-score it.""" + device, out = _configure(device), Path(out) + manifest = json.loads((out / "run.json").read_text()) + spec = manifest["spec"] + if file_hash(Path(spec["parent_dir"]) / "model.pt") != manifest["parent_file_sha256"]: + raise AssertionError("Parent checkpoint hash changed") + parent, world, parent_spec = _load_parent(spec["parent_dir"], device) + if model_digest(parent) != manifest["parent_model_sha256"]: + raise AssertionError("Parent model digest changed") + cases, qualification = graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + if "case_ids" in spec: + cases = [c for c in cases if c["case_id"] in spec["case_ids"]] + if cases != manifest["cases"] or _hash_json(cases) != manifest["case_sha256"]: + raise AssertionError("Graph-selected cases changed") + if qualification != manifest["qualification"] or data_digest(world) != manifest["world_sha256"]: + raise AssertionError("World qualification changed") + summary = json.loads((out / "complete.json").read_text()) + rates = spec.get("learning_rates", [spec.get("lr", 1e-4)]) + expected_branches = { + (c["case_id"], lr, arm) for c in cases for lr in rates for arm in ("edit", "sham") + } + actual_branches = [(b["case_id"], b["lr"], b["arm"]) for b in summary["branches"]] + if len(actual_branches) != len(expected_branches) or set(actual_branches) != expected_branches: + raise AssertionError("The fixed paired branch matrix is incomplete") + root_learning = json.loads((out / "learning.json").read_text()) + nodes = spec.get("nodes", list(DEFAULT_NODES)) + expected_evaluations = len(actual_branches) * len(nodes) + if len(root_learning) != expected_evaluations or [row["step"] for row in root_learning] != list( + range(expected_evaluations) + ): + raise AssertionError("Root learning evaluation indices are incomplete or repeated") + for index, row in enumerate(root_learning): + branch_index, node_index = divmod(index, len(nodes)) + updates = branch_index * nodes[-1] + nodes[node_index] + if ( + (row["case_id"], row["lr"], row["arm"]) != actual_branches[branch_index] + or row["branch_step"] != nodes[node_index] + or row["optimizer_updates"] != updates + or row["target_supervised_tokens"] != updates * 3 + or row["replay_distillation_positions"] != updates * spec.get("replay_n", 32) * 3 + or "supervised_tokens" in row + ): + raise AssertionError("Root learning optimizer or exposure accounting changed") + batch_size = spec.get("eval_batch_size", 512) + checked_nodes, checked_predictions, max_error = 0, 0, 0.0 + for case in cases: + tasks, originals = case_tasks(world, case) + parent_correct = _parent_masks(parent, originals, device, batch_size) + for branch in summary["branches"]: + if branch["case_id"] != case["case_id"]: + continue + directory = out / branch["path"] + branch_spec = json.loads((directory / "run.json").read_text()) + target = tasks["E_new" if branch["arm"] == "edit" else "E_old"] + target_batch = answer_batch(target, device) + replay_batch = answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + reference = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + expected_hashes = { + "old_fact_sha256": _hash_json(case["old_fact"]), + "new_fact_sha256": _hash_json(case["new_fact"]), + "target_batch_sha256": _batch_hash(target_batch), + "replay_batch_sha256": _batch_hash(replay_batch), + "parent_reference_sha256": _batch_hash((reference,)), + } + if any(branch_spec[key] != value for key, value in expected_hashes.items()): + raise AssertionError("Target or paired replay provenance changed") + history = json.loads((directory / "learning.json").read_text()) + if [record["step"] for record in history] != spec.get("nodes", list(DEFAULT_NODES)): + raise AssertionError("Saved edit node matrix is incomplete") + if ( + file_hash(directory / f"tensors-{history[-1]['step']:06d}.pt") + != branch["tensor_file_sha256"] + ): + raise AssertionError("Final exact tensor file hash changed") + for record in history: + state = torch.load( + directory / f"tensors-{record['step']:06d}.pt", + map_location="cpu", + weights_only=True, + ) + model = copy.deepcopy(parent).eval() + selected = editable_parameters( + model, spec.get("parameter_scope", "mlp"), spec.get("block_index", 0) + ) + if set(state["edited_tensors"]) != set(selected): + raise AssertionError("Unexpected edited tensor scope") + merged = model.state_dict() + merged.update(state["edited_tensors"]) + model.load_state_dict(merged) + if model_digest(model) != record["model_sha256"]: + raise AssertionError("Exact saved tensors did not reconstruct the model") + metrics, predictions = evaluate_case( + model, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + with np.load(directory / f"predictions-{record['step']:06d}.npz") as saved: + if set(saved.files) != set(predictions): + raise AssertionError("Prediction keys changed") + for name, actual in predictions.items(): + if name.endswith("answer_nll"): + np.testing.assert_allclose(actual, saved[name], rtol=1e-5, atol=1e-5) + if len(actual): + max_error = max( + max_error, float(np.max(np.abs(actual - saved[name]))) + ) + else: + np.testing.assert_array_equal(actual, saved[name]) + checked_predictions += actual.size + for name, values in metrics.items(): + for key, value in values.items(): + expected = record["metrics"][name][key] + if key == "answer_nll" and value is not None: + np.testing.assert_allclose(value, expected, rtol=1e-5, atol=1e-5) + elif value != expected: + raise AssertionError(f"Re-scoring mismatch: {name}/{key}") + checked_nodes += 1 + result = { + "passed": True, + "nodes": checked_nodes, + "array_elements": checked_predictions, + "max_nll_error": max_error, + "case_sha256": manifest["case_sha256"], + "finished_utc": utc(), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/interface_tracking.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/interface_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d7812ba16f84199f575a2c6eb88ba64a6bf26d --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/interface_tracking.py @@ -0,0 +1,203 @@ +"""Use the existing W&B sidecar, finishing only after the independent audit.""" + +import argparse +import fcntl +import importlib +import json +import os +import time +from pathlib import Path + +from . import experiment_tracking as tracking + + +class ContainerSDK: + def __init__(self, sdk, runtime): + self.sdk, self.runtime = sdk, runtime + + def __getattr__(self, name): + return getattr(self.sdk, name) + + def Settings(self, **options): + options.pop("x_stats_pid", None) + if self.runtime: + options["x_stats_pid"] = self.runtime["host_pid"] + options["x_stats_gpu_device_ids"] = (self.runtime["physical_gpu"],) + return self.sdk.Settings(**options) + + +class AuditedRunTracker(tracking.ArtifactRunTracker): + def __init__(self, sdk, batch, path, settings): + runtime_path = path / "container-runtime.json" + runtime = tracking.read_json(runtime_path) + super().__init__(ContainerSDK(sdk, runtime), batch, path, settings) + self.run.config.update( + { + key: self.metadata[key] + for key in ( + "parent_spec", + "cases", + "learning_step_unit", + "status_step_unit", + ) + if key in self.metadata + } + ) + if runtime: + self.run.config.update({"container_runtime": runtime}) + + def poll(self): + history = tracking.read_json(self.path / "learning.json") + previous = None + for record in history: + step = int(record["step"]) + if step > self.cursor: + metrics = tracking.learning_metrics(record, previous) + for key in ("case", "case_id", "condition", "variant", "arm"): + if key in record: + metrics["condition/" + key] = record[key] + if "optimizer_updates" in record: + metrics["evaluation/index"] = step + metrics["condition/step_unit"] = "evaluation_index" + metrics.pop("perf/updates_per_second", None) + metrics.pop("perf/training_ms_per_update", None) + if previous is not None: + seconds = record.get("wall_seconds", 0) - previous.get("wall_seconds", 0) + updates = record["optimizer_updates"] - previous.get("optimizer_updates", 0) + if seconds > 0: + metrics["perf/updates_per_second"] = updates / seconds + self.run.log(metrics, step=step) + self.cursor = step + self.state["last_logged_step"] = step + tracking.write_json(self.state_path, self.state) + previous = record + status_path = self.path / "status.json" + if status_path.exists(): + self.run.summary["training_state"] = tracking.read_json(status_path).get("state") + failed = (self.path / "failure.json").exists() + audit_path = self.path / "audit.json" + audit = tracking.read_json(audit_path) if audit_path.exists() else {} + audited = audit.get("passed") is True + complete = (self.path / "complete.json").exists() and audited + self.run.summary["has_failure_record"] = failed + self.run.summary["independently_reloaded"] = audited + if complete or failed: + self.run.summary["scientific_final_step"] = self.cursor + self.run.finish(exit_code=1 if failed else 0) + # Preserve the authoritative resume cursor even when every point + # was already on the server and this process logged no new points. + self.state["last_logged_step"] = self.cursor + tracking.write_json(self.state_path, self.state) + return True + return False + + +def discover_runs(runs_dir): + return { + path + for path in Path(runs_dir).glob("*") + if (path / "run.json").exists() and (path / "learning.json").exists() + } + + +def final_step(path): + history = tracking.read_json(path / "learning.json") + return max((int(record["step"]) for record in history), default=-1) + + +def drain_runs(sdk, root, runs_dir, settings, *, once=False, tracker_factory=None): + """Drain late-created runs and late final nodes before terminal exit. + + SDK initialization and uploads may take longer than an entire scientific + run. Consequently, a scan made before those calls is never an exit proof. + Finished runs stay in this process's cursor map and are reopened only if + their saved learning trajectory acquired an unlogged final node. + """ + root, runs_dir = Path(root), Path(runs_dir) + tracker_factory = tracker_factory or AuditedRunTracker + active, finished = {}, {} + try: + while True: + for path in sorted(discover_runs(runs_dir)): + if path in active or path in finished: + continue + active[path] = tracker_factory(sdk, root, path, settings) + print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True) + for path, tracker in list(active.items()): + current = tracking.read_json(path / "run.json") + if current.get("pid") != tracker.metadata.get("pid"): + tracker.close() + tracker = tracker_factory(sdk, root, path, settings) + active[path] = tracker + if tracker.poll(): + finished[path] = tracker.cursor + del active[path] + if once: + return {str(path): cursor for path, cursor in finished.items()} + manifest = root / "controller-state.json" + state = tracking.read_json(manifest) if manifest.exists() else {} + terminal = state.get("state") in { + "complete", + "finished_with_failures", + "development_prerequisite_not_met", + } + # Rescan AFTER all SDK calls and after reading the controller's + # terminal state, so runs born during initialization cannot vanish. + fresh = discover_runs(runs_dir) + stale = {path for path, cursor in finished.items() if final_step(path) > cursor} + for path in stale: + del finished[path] + if terminal and not active: + expected = {runs_dir / name for name in state.get("completed", [])} + if missing := expected - fresh: + raise RuntimeError(f"Completed runs lack logging artifacts: {sorted(missing)}") + if fresh <= finished.keys(): + result = { + "passed": True, + "registered_runs": len(finished), + "runs": { + path.name: { + "last_logged_step": finished[path], + "final_step": final_step(path), + } + for path in sorted(fresh) + }, + } + tracking.write_json(root / "tracking-completion.json", result) + return result + if fresh - (active.keys() | finished.keys()): + continue + time.sleep(settings["poll_seconds"]) + finally: + for tracker in active.values(): + tracker.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--runs-dir", type=Path) + parser.add_argument("--defaults", type=Path, default=tracking.DEFAULTS) + parser.add_argument("--entity") + parser.add_argument("--project") + parser.add_argument("--mode", choices=("online", "offline")) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + settings = tracking.read_json(args.defaults) + for key in ("entity", "project", "mode"): + settings[key] = ( + getattr(args, key) or os.environ.get(f"WANDB_{key.upper()}") or settings[key] + ) + if not settings["enabled"]: + raise SystemExit("Experiment tracking is disabled in the selected defaults") + local = args.root / "tracking-wandb" + local.mkdir(parents=True, exist_ok=True) + sdk = importlib.import_module("wandb") + with (local / "tracker.lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + tracking.write_json(args.root / "tracking-ready.json", {"sdk_version": sdk.__version__}) + drain_runs(sdk, args.root, args.runs_dir or args.root / "runs", settings, once=args.once) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/knowledge_change.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/knowledge_change.py new file mode 100644 index 0000000000000000000000000000000000000000..1481d60ac7e43d3617f38f6ca360b241dca20b70 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/knowledge_change.py @@ -0,0 +1,381 @@ +"""Learn to use temporarily changed factual parameters, without test edit labels. + +Every episode uses an atomic-only MLP update, followed by language-model training +of the remaining parameters. The edited MLP is then restored exactly. This is +episodic reader adaptation, not differentiable meta-learning or an assertion +that all facts reside in that MLP. All three arms use the same restricted scope. +""" + +from __future__ import annotations + +import copy +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from . import interface_editing as editing +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .latent_scaling import build_world, compare_metrics, compare_predictions, model_digest +from .shared_cache import construct, executed_flops +from .storage_composition import FullTokenStep, evaluate, file_hash, generate_rows, pack_sentences + +TRAINING_ARMS = ("fixed", "changed_atomic", "changed_use") +CASE_SEED = 107270041 +CASE_POOL = 16 +TEST_PER_CELL = 4 + + +def panel(spec): + """Split update addresses from graph only; reserve all test addresses first.""" + cases, qualification = editing.graph_cases( + spec, seed=CASE_SEED, per_cell=CASE_POOL, replay_n=32 + ) + test = [c for c in cases if int(c["case_id"].rsplit("-", 1)[1]) < TEST_PER_CELL] + reserved = {tuple(c["old_fact"][:2]) for c in test} + world = build_world(spec) + train = [] + for role in editing.ROLES: + selected = [ + c + for c in cases + if c["role"] == role + and c["stratum"] == "familiar" + and tuple(c["old_fact"][:2]) not in reserved + and editing.affected(world["train_composite"], c["old_fact"], role).any() + ] + if len(selected) < 4: + raise ValueError(f"Need four train update addresses per role, got {len(selected)}") + train.extend(selected[:4]) + train_addresses = {tuple(c["old_fact"][:2]) for c in train} + if train_addresses & reserved or len(train_addresses) != len(train): + raise AssertionError("Training/test update addresses overlap") + return dict(train=train, test=test, qualification=qualification) + + +def episode_rows(world, case, arm): + """No heldout query or bridge labels enter any episode's LM objective.""" + if arm not in TRAINING_ARMS: + raise ValueError(arm) + atoms = editing.learned_atoms(world) + original_atoms = atoms.copy() + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + target = case["old_fact"] if arm == "fixed" else case["new_fact"] + mask = np.all(atoms[:, :2] == np.asarray(target[:2]), axis=1) + assert mask.sum() == 1 + atoms[mask, 2] = target[2] + queries = world["train_composite"].copy() + affected = editing.affected(queries, case["old_fact"], case["role"]) + if not affected.any(): + raise ValueError("Training edit must affect taught composition queries") + if arm == "changed_use": + queries = editing.rewrite(queries, case["old_fact"], case["new_fact"], case["role"], lookup) + if arm == "changed_atomic": + # Remove affected queries: old answers would contradict the current fact. + emphasized = queries[~affected] + else: + emphasized = queries[affected] + unaffected = queries[~affected] + # Four matched streams: target atomic, other atomics, emphasized composition, + # unaffected composition. The atomic-only control differs in query exposure; + # this limitation is recorded rather than claiming exact information matching. + strata = [np.asarray([target]), atoms[~mask], emphasized, unaffected] + return strata, dict( + affected_training_n=int(affected.sum()), + changed_training_answers=int(np.sum(queries[:, -1] != world["train_composite"][:, -1])), + direct_atomic_changed=bool(np.any(atoms != original_atoms)), + stream_sizes=[len(x) for x in strata], + ) + + +class AtomicStep: + """Captured atomic edit with exact warmup rollback and fresh Adam state.""" + + def __init__(self, model, target, replay, reference, lr): + self.model, self.target, self.replay, self.reference = model, target, replay, reference + self.parameters = [p for p in model.parameters() if p.requires_grad] + self.optimizer = torch.optim.Adam(self.parameters, lr=lr, capturable=True, foreach=False) + before = [p.detach().clone() for p in model.parameters()] + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(3): + self.eager() + torch.cuda.current_stream().wait_stream(stream) + self.graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(self.graph): + self.loss = self.eager() + torch.cuda.synchronize() + with torch.no_grad(): + for parameter, old in zip(model.parameters(), before, strict=True): + parameter.copy_(old) + if parameter.grad is not None: + parameter.grad.zero_() + for state in self.optimizer.state.values(): + for value in state.values(): + if torch.is_tensor(value): + value.zero_() + + def eager(self): + self.optimizer.zero_grad(set_to_none=True) + loss, _, _ = editing.edit_objective( + self.model, self.target, self.replay, self.reference, 1.0 + ) + loss.backward() + torch.nn.utils.clip_grad_norm_(self.parameters, 1.0, foreach=True) + self.optimizer.step() + return loss + + def run(self, steps): + for _ in range(steps): + self.graph.replay() + torch.cuda.synchronize() + result = float(self.loss.detach()) + if not np.isfinite(result): + raise FloatingPointError(result) + return result + + +def set_reader_scope(model): + for name, parameter in model.named_parameters(): + parameter.requires_grad_(not name.startswith("blocks.0.mlp.")) + parameter.grad = None + + +def train(spec, out, source, engineering=False): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists(): + raise FileExistsError(out) + editing._configure("cuda:0") + parent_path = Path(spec["parent_dir"]) / "model-128000.pt" + payload = torch.load(parent_path, map_location="cpu", weights_only=False) + parent_spec = payload["spec"] + model = construct(parent_spec, "cuda:0") + model.load_state_dict(payload["model"]) + model.eval() + world = build_world(parent_spec) + selected_panel = panel(parent_spec) + assert editing._hash_json(selected_panel) == spec["panel_sha256"] + writer = { + n: p.detach().clone() for n, p in model.named_parameters() if n.startswith("blocks.0.mlp.") + } + manifest = dict( + spec=spec, + parent_spec=parent_spec, + parent_sha256=file_hash(parent_path), + initial_model_sha256=model_digest(model), + writer_names=list(writer), + panel=selected_panel, + source=source, + pid=__import__("os").getpid(), + gpu=int(__import__("os").environ.get("PHYSICAL_GPU", 0)), + created_utc=utc(), + ) + write_json(out / "run.json", manifest) + np.savez_compressed(out / "world.npz", **world) + episodes = 2 if engineering else spec["episodes"] + inner_steps = 4 if engineering else spec["inner_steps"] + reader_steps = 4 if engineering else spec["reader_steps"] + history, records = [], [] + training_seconds = 0.0 + started = time.perf_counter() + + def measure(episode): + nonlocal model + metrics, predictions = evaluate(model, world, "low", "cuda:0") + node = episode * (inner_steps + reader_steps) + history.append( + dict( + step=node, + episode=episode, + metrics=metrics, + training_seconds=training_seconds, + wall_seconds=time.perf_counter() - started, + reader_updates=episode * reader_steps, + atomic_update_steps=episode * inner_steps, + examples=episode * (inner_steps * 33 + reader_steps * spec["batch_size"]), + target_supervised_tokens=episode * inner_steps * 3, + replay_distillation_positions=episode * inner_steps * 32 * 3, + reader_supervised_tokens=episode * reader_steps * spec["batch_size"] * 8, + # Execution-shape estimate; frozen MLP and KL are not exact backward FLOPs. + estimated_matmul_training_flops=episode + * ( + inner_steps + * executed_flops(model.config, model.repeats, 33, 9, model.memory_arm, 3) + + reader_steps + * executed_flops( + model.config, model.repeats, spec["batch_size"], 9, model.memory_arm + ) + ), + ) + ) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{episode:03d}.npz", **predictions) + torch.save( + dict(spec=parent_spec, model=model.state_dict(), episode=episode), + out / f"model-{episode:03d}.pt", + ) + write_json(out / "status.json", dict(state="running", step=node, episode=episode)) + print(json.dumps(dict(name=spec["name"], episode=episode, metrics=metrics)), flush=True) + + measure(0) + for episode in range(episodes): + case = selected_panel["train"][episode % len(selected_panel["train"])] + before_writer = {n: p.detach().clone() for n, p in model.named_parameters() if n in writer} + for n in writer: + torch.testing.assert_close(before_writer[n], writer[n], rtol=0, atol=0) + tasks, _ = editing.case_tasks(world, case) + replay = editing.answer_batch(tasks["R_atomic"], "cuda:0") + model.eval() + with torch.no_grad(): + reference = model(replay[0], positions=replay[1]).log_softmax(-1).detach() + selected = editing.editable_parameters(model) + assert set(selected) == set(writer) + target = case["old_fact"] if spec["training_arm"] == "fixed" else case["new_fact"] + target_batch = editing.answer_batch(np.asarray([target]), "cuda:0") + torch.cuda.synchronize() + began = time.perf_counter() + operation = AtomicStep(model, target_batch, replay, reference, spec["inner_lr"]) + if engineering: + eager_model = copy.deepcopy(model) + eager_parameters = [p for p in eager_model.parameters() if p.requires_grad] + eager_optimizer = torch.optim.Adam( + eager_parameters, lr=spec["inner_lr"], capturable=True, foreach=False + ) + for _ in range(inner_steps): + eager_optimizer.zero_grad(set_to_none=True) + eager_loss, _, _ = editing.edit_objective( + eager_model, target_batch, replay, reference, 1.0 + ) + eager_loss.backward() + torch.nn.utils.clip_grad_norm_(eager_parameters, 1.0, foreach=True) + eager_optimizer.step() + inner_loss = operation.run(inner_steps) + if engineering: + for actual, expected in zip(model.parameters(), eager_model.parameters(), strict=True): + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + del eager_model, eager_optimizer + training_seconds += time.perf_counter() - began + inner_metrics, _ = generate_rows(model, np.asarray([target]), "cuda:0") + del operation + strata, info = episode_rows(world, case, spec["training_arm"]) + set_reader_scope(model) + model.train() + table = tuple( + torch.as_tensor(np.concatenate(parts), device="cuda:0") + 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(n, spec["stream_seed"] + episode * 10 + i) for i, n in enumerate(sizes) + ] + batch = spec["batch_size"] + reader_lr = torch.tensor(spec["reader_lr"], device="cuda:0") + optimizer = make_optimizer(model, reader_lr, 0.0) + began = time.perf_counter() + graph = FullTokenStep(model, optimizer, table, batch) + for start in range(0, reader_steps, 128): + n = min(128, reader_steps - start) + indices = np.concatenate( + [ + s.take(n * batch // 4).reshape(n, batch // 4) + offset + for s, offset in zip(streams, offsets, strict=True) + ], + axis=1, + ) + indices = torch.as_tensor(indices, device="cuda:0") + for j in range(n): + loss = graph(indices[j]) + torch.cuda.synchronize() + training_seconds += time.perf_counter() - began + reader_loss = float(loss.detach()) + if not np.isfinite(reader_loss): + raise FloatingPointError(reader_loss) + after_metrics, _ = generate_rows(model, np.asarray([target]), "cuda:0") + del graph, optimizer + with torch.no_grad(): + for name, parameter in model.named_parameters(): + if name in writer: + parameter.copy_(writer[name]) + records.append( + dict( + episode=episode + 1, + case_id=case["case_id"], + role=case["role"], + target=target, + inner_success=inner_metrics["accuracy"], + after_use_atomic_success=after_metrics["accuracy"], + inner_loss=inner_loss, + reader_loss=reader_loss, + **info, + ) + ) + write_json(out / "episodes.json", records) + if episode + 1 in {1, 8, 16, 24, episodes}: + measure(episode + 1) + torch.save(dict(spec=parent_spec, model=model.state_dict()), out / "model.pt") + result = dict( + spec=spec, + endpoint=history[-1], + episodes=records, + writer_restored_exact=True, + final_model_sha256=model_digest(model), + checkpoint_sha256=file_hash(out / "model.pt"), + training_seconds=training_seconds, + process_seconds=time.perf_counter() - started, + finished_utc=utc(), + engineering=engineering, + ) + write_json(out / "complete.json", result) + return result + + +def audit(out): + editing._configure("cuda:0") + out = Path(out) + manifest = json.loads((out / "run.json").read_text()) + complete = json.loads((out / "complete.json").read_text()) + spec = manifest["parent_spec"] + world = build_world(spec) + if panel(spec) != manifest["panel"]: + raise AssertionError("Update partition changed") + parent = torch.load( + Path(manifest["spec"]["parent_dir"]) / "model-128000.pt", + map_location="cpu", + weights_only=False, + ) + maximum = 0.0 + history = json.loads((out / "learning.json").read_text()) + for row in history: + payload = torch.load( + out / f"model-{row['episode']:03d}.pt", map_location="cpu", weights_only=False + ) + model = construct(spec, "cuda:0") + model.load_state_dict(payload["model"]) + for name in manifest["writer_names"]: + torch.testing.assert_close( + payload["model"][name], parent["model"][name], rtol=0, atol=0 + ) + metrics, predictions = evaluate(model, world, "low", "cuda:0") + compare_metrics(metrics, row["metrics"]) + with np.load(out / f"predictions-{row['episode']:03d}.npz") as saved: + maximum = max(maximum, compare_predictions(predictions, saved)) + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + model.load_state_dict(payload["model"]) + assert model_digest(model) == complete["final_model_sha256"] + assert file_hash(out / "model.pt") == complete["checkpoint_sha256"] + write_json( + out / "audit.json", + dict( + passed=True, + checked_nodes=len(history), + max_nll_error=maximum, + writer_exact=True, + utc=utc(), + ), + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/latent_scaling.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/latent_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..7abd21f4255e3f7de35ecee337ed09d32da707ff --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/latent_scaling.py @@ -0,0 +1,311 @@ +"""Scaling knowledge use in ordinary GPT blocks with fixed facts and tests. + +Independent composition examples and optimization time are separate axes. All +blocks retain learned embeddings, causal attention, residuals and 4x GELU MLPs. +Historical experiments and their frozen implementations are left untouched. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .storage_composition import FullTokenStep, data_digest, evaluate, file_hash, pack_sentences +from .storage_composition import build_world as historical_world +from .storage_frontier import SOURCE_FILES as STABILITY_SOURCES +from .storage_frontier import learning_rate +from .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 checked diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/latent_support.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/latent_support.py new file mode 100644 index 0000000000000000000000000000000000000000..4b307c09f7a1fe633c634ae39b3a83e964675355 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/latent_support.py @@ -0,0 +1,363 @@ +"""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 so +historical sources retain their frozen hashes. Architecture, optimizer, sentence +packing, evaluation and streams are reused; only build_world selects support. +""" + +from __future__ import annotations + +import json +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .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 checked diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/low_rank.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/low_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..3a58bee0d460cb3ae042e17d22b7132b2035bd4b --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/low_rank.py @@ -0,0 +1,138 @@ +"""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, Real +from 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 report diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/memory_reuse.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/memory_reuse.py new file mode 100644 index 0000000000000000000000000000000000000000..89520ed7649557ad7e4cfc2611ac85b8d9db8396 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/memory_reuse.py @@ -0,0 +1,469 @@ +"""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 used +by its optimizer, and all evaluation uses continuous intermediate states. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from 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 result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/multihop_scaling.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/multihop_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..64b5a3d67ef6bab20c60904e626e811876d72279 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/multihop_scaling.py @@ -0,0 +1,518 @@ +"""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 copy +import hashlib +import json +import time +from functools import lru_cache +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import depth_step +from .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_json +from .grok_loop_model import flops +from .latent_scaling import model_digest +from .storage_composition import FullTokenStep, file_hash +from .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=" 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 checked diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/natural_composition_confirmation.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/natural_composition_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9608e59339683c91de69b2f1f392b93b8f0171 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/natural_composition_confirmation.py @@ -0,0 +1,687 @@ +"""Full-Qwen, nested compositional support with matched atomic supervision.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import platform +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +import transformers +from 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) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e949ff27eac75a758644d6a7ffd81f2a9477ea --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py @@ -0,0 +1,687 @@ +"""Full-Qwen, nested compositional support with matched atomic supervision.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import platform +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +import transformers +from 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) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/neural.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/neural.py new file mode 100644 index 0000000000000000000000000000000000000000..ce1f02e8195f4e583817b3781b044f021a41fbfb --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/neural.py @@ -0,0 +1,328 @@ +"""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 argparse +import copy +import json +import math +import platform +import statistics +import subprocess +import time +from dataclasses import asdict, dataclass +from pathlib import Path + +import numpy as np + +try: + import torch + from torch import nn + from torch.nn import functional as F +except ModuleNotFoundError as exc: + raise SystemExit("Neural experiments require PyTorch: pip install '.[neural]'") from exc + +from .neural_data import make_world +from .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()) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/neural_data.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/neural_data.py new file mode 100644 index 0000000000000000000000000000000000000000..555b2a06a7db0805d441a3f8f89bc2100deaa72a --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/neural_data.py @@ -0,0 +1,147 @@ +"""Balanced fact-table interventions, defined independently of model training.""" + +from dataclasses import dataclass +from 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, + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/neural_models.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/neural_models.py new file mode 100644 index 0000000000000000000000000000000000000000..448b3499cdce6fac7d4bcac1e60883f4c383df82 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/neural_models.py @@ -0,0 +1,157 @@ +"""Trainable nonlinear fact models; importing this module requires PyTorch.""" + +import torch +from 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 selected diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/parametric_architecture.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/parametric_architecture.py new file mode 100644 index 0000000000000000000000000000000000000000..a254bf6f90931d21d80c57972a6770ad6665c13a --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/parametric_architecture.py @@ -0,0 +1,443 @@ +"""Paired GPT-2 architecture extensions for the closed-book memory experiment. + +Dense execution delegates to the historical ReproductionGPT without changing +its numerical path. New modules use an independent, checkpointed initialization +seed; the eight-block reference is always constructed before taking a prefix. +The mHC residual convention is ``output[n] = sum_m H_res[m,n] * input[m]``. +""" + +from __future__ import annotations + +import hashlib +import math +from collections.abc import Sequence + +import torch +from torch import nn +from torch.nn import functional as F +from transformers import GPT2Config +from transformers.models.gpt2.modeling_gpt2 import GPT2MLP + +from .grokking_reproduction import ReproductionGPT + +ARMS = { + "D4": (4, 1, "dense"), + "D8": (8, 1, "dense"), + "L4R2": (4, 2, "dense"), + "M8": (8, 1, "moe"), + "W8": (8, 1, "wide"), + "IHC8": (8, 1, "identity_mhc"), + "HC8": (8, 1, "mhc"), + "M4": (4, 1, "moe"), + "LM4R2": (4, 2, "moe"), +} + + +def sinkhorn(logits: torch.Tensor, iterations: int = 20, eps: float = 1e-6): + """Accepted mHC A.6: initial row softmax, then 20 column normalizations. + + There are 19 intervening row normalizations. This is a finite-iteration + approximation, not an exact doubly stochastic projection. + """ + if iterations < 1: + raise ValueError("Sinkhorn requires at least one iteration") + with torch.autocast(logits.device.type, enabled=False): + matrix = logits.float().softmax(dim=-1) + eps + matrix = matrix / (matrix.sum(dim=-2, keepdim=True) + eps) + for _ in range(iterations - 1): + matrix = matrix / (matrix.sum(dim=-1, keepdim=True) + eps) + matrix = matrix / (matrix.sum(dim=-2, keepdim=True) + eps) + return matrix + + +def residual_mix(streams, matrix): + """Rows are source streams and columns are destination streams.""" + return torch.einsum("...mn,...mc->...nc", matrix, streams) + + +class ControllerRMSNorm(nn.Module): + def __init__(self, width): + super().__init__() + self.weight = nn.Parameter(torch.ones(width)) + + def forward(self, x): + return x * torch.rsqrt(x.square().mean(dim=-1, keepdim=True) + 1e-20) * self.weight + + +class HyperConnection(nn.Module): + """Four-stream pre/post controller with optional constrained residual map.""" + + def __init__(self, width, sublayer_id, streams=4, identity=False): + super().__init__() + self.streams, self.identity = streams, identity + count = 2 * streams + (0 if identity else streams * streams) + self.norm = ControllerRMSNorm(streams * width) + self.projection = nn.Linear(streams * width, count, bias=False) + nn.init.zeros_(self.projection.weight) + self.pre_bias = nn.Parameter(torch.full((streams,), -3.0)) + with torch.no_grad(): + self.pre_bias[sublayer_id % streams] = 3.0 + self.post_bias = nn.Parameter(torch.zeros(streams)) + self.alpha_pre = nn.Parameter(torch.tensor(0.01)) + self.alpha_post = nn.Parameter(torch.tensor(0.01)) + if not identity: + self.res_bias = nn.Parameter(6 * torch.eye(streams) - 3) + self.alpha_res = nn.Parameter(torch.tensor(0.01)) + + def coefficients(self, x): + n = self.streams + with torch.autocast(x.device.type, enabled=False): + dynamic = self.projection(self.norm(x.float().flatten(-2))) + pre = torch.sigmoid(dynamic[..., :n] * self.alpha_pre + self.pre_bias) + 1e-6 + post = 2 * torch.sigmoid(dynamic[..., n : 2 * n] * self.alpha_post + self.post_bias) + res = None + if not self.identity: + logits = dynamic[..., 2 * n :].reshape(*x.shape[:-2], n, n) + res = sinkhorn(logits * self.alpha_res + self.res_bias) + return pre, post, res + + def forward(self, x, sublayer): + pre, post, res = self.coefficients(x) + with torch.autocast(x.device.type, enabled=False): + contracted = (pre[..., None] * x.float()).sum(dim=-2) + y = sublayer(contracted.to(x.dtype)) + with torch.autocast(x.device.type, enabled=False): + residual = x.float() if res is None else residual_mix(x.float(), res) + output = residual + post[..., None] * y.float().unsqueeze(-2) + return output.to(x.dtype) + + +def _initialize_mlp(mlp, initializer_range): + # Eight-block GPT-2 reference residual projection scale, also for loops. + nn.init.normal_(mlp.c_fc.weight, std=initializer_range) + nn.init.normal_(mlp.c_proj.weight, std=initializer_range / math.sqrt(2 * 8)) + nn.init.zeros_(mlp.c_fc.bias) + nn.init.zeros_(mlp.c_proj.bias) + + +class DroplessMoE(nn.Module): + """Top-2 normalized routing, one output dropout, no capacity/token drops.""" + + def __init__(self, config, experts=8, top_k=2): + super().__init__() + self.expert_count, self.top_k = experts, top_k + self.router = nn.Linear(config.n_embd, experts, bias=False) + nn.init.normal_(self.router.weight, std=config.initializer_range) + self.experts = nn.ModuleList() + for _ in range(experts): + expert = GPT2MLP(2 * config.n_embd, config) + expert.dropout = nn.Identity() + _initialize_mlp(expert, config.initializer_range) + self.experts.append(expert) + self.dropout = nn.Dropout(config.resid_pdrop) + + def forward(self, x, valid_mask=None): + flat = x.reshape(-1, x.shape[-1]) + if valid_mask is None: + selected_tokens = torch.arange(len(flat), device=x.device) + else: + selected_tokens = valid_mask.flatten().nonzero(as_tuple=True)[0] + valid = flat.index_select(0, selected_tokens) + with torch.autocast(x.device.type, enabled=False): + probabilities = F.linear(valid.float(), self.router.weight.float()).softmax(-1) + top_weights, expert_ids = probabilities.topk(self.top_k, dim=-1) + weights = top_weights / top_weights.sum(dim=-1, keepdim=True) + # Accumulate selected expert outputs in FP32 for consistent BF16 routing. + combined = torch.zeros_like(valid, dtype=torch.float32) + for expert_id, expert in enumerate(self.experts): + token_ids, slots = (expert_ids == expert_id).nonzero(as_tuple=True) + if token_ids.numel(): + values = expert(valid.index_select(0, token_ids)) + weighted = values.float() * weights[token_ids, slots, None] + combined = combined.index_add(0, token_ids, weighted) + output = torch.zeros_like(flat).index_copy(0, selected_tokens, combined.to(flat.dtype)) + counts = torch.bincount(expert_ids.flatten(), minlength=self.expert_count).detach() + n_valid = probabilities.new_tensor(len(valid)) + stats = { + "assignment_counts": counts, + "probability_sum": probabilities.sum(dim=0), + "valid_tokens": n_valid, + "top_k": self.top_k, + "processed_assignments": counts.sum(), + "dropped_assignments": counts.new_zeros(()), + "entropy_sum": -(probabilities * probabilities.clamp_min(1e-30).log()).sum().detach(), + "selected_mass_sum": top_weights.sum().detach(), + } + return self.dropout(output.view_as(x)), stats + + +def combine_router_fractions(stats_by_microbatch: Sequence[Sequence[dict]]): + """Combine detached counts before a replay that computes exact batch aux. + + Counts are per executed block (thus distinguish Loop passes). Replay must + restore dropout RNG state, so its hard routes equal the counting pass. + """ + if not stats_by_microbatch or not stats_by_microbatch[0]: + return [], 0 + layers = len(stats_by_microbatch[0]) + if any(len(stats) != layers for stats in stats_by_microbatch): + raise ValueError("All microbatches must have the same executed routing layers") + total = sum(stats[0]["valid_tokens"] for stats in stats_by_microbatch) + fractions = [] + for layer in range(layers): + counts = sum(stats[layer]["assignment_counts"] for stats in stats_by_microbatch) + fractions.append( + counts.float() / (total * stats_by_microbatch[0][layer]["top_k"]).clamp_min(1) + ) + return fractions, total + + +def router_balance_loss(stats, assignment_fractions=None, total_valid_tokens=None): + """N * sum(f * p), averaged over executed layers. + + With externally supplied whole-batch fractions and denominator, this returns + the current microbatch's additive contribution to the exact batch objective. + Assignment fractions are discrete and intentionally detached. + """ + if not stats: + return torch.tensor(0.0) + if assignment_fractions is not None and len(assignment_fractions) != len(stats): + raise ValueError("One assignment-fraction vector is required per executed layer") + losses = [] + for index, record in enumerate(stats): + count = record["valid_tokens"] + denominator = count if total_valid_tokens is None else total_valid_tokens + denominator = torch.as_tensor(denominator, device=count.device).clamp_min(1) + fractions = ( + record["assignment_counts"].float() / (count * record["top_k"]).clamp_min(1) + if assignment_fractions is None + else assignment_fractions[index].detach() + ) + probabilities = record["probability_sum"] / denominator + losses.append(probabilities.numel() * (fractions * probabilities).sum()) + return torch.stack(losses).mean() + + +class ParametricGPT(ReproductionGPT): + def __init__(self, config, architecture="D8", module_seed=0): + blocks, repeats, kind = ARMS[architecture] + # Always initialize the same independent eight blocks before slicing. + config.n_layer = 8 + super().__init__(config, repeats=repeats) + self.transformer.h = nn.ModuleList(list(self.transformer.h)[:blocks]) + self.config.n_layer = blocks + self.architecture, self.kind, self.module_seed = architecture, kind, module_seed + with torch.random.fork_rng(devices=[]): + torch.manual_seed(module_seed) + if kind in {"wide", "moe"}: + for block in self.transformer.h: + if kind == "moe": + block.mlp = DroplessMoE(config) + else: + block.mlp = GPT2MLP(16 * config.n_embd, config) + _initialize_mlp(block.mlp, config.initializer_range) + elif kind in {"mhc", "identity_mhc"}: + self.connections = nn.ModuleList( + HyperConnection(config.n_embd, index, identity=kind == "identity_mhc") + for index in range(2 * blocks) + ) + + def _attention(self, block, x): + cfg = self.config + batch, length = x.shape[:2] + q, k, v = block.attn.c_attn(block.ln_1(x)).split(cfg.n_embd, dim=2) + shape = (batch, 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(batch, length, cfg.n_embd)) + return F.dropout(y, cfg.resid_pdrop, self.training) + + def forward(self, tokens, positions=None, *, valid_mask=None, return_aux=False): + if valid_mask is not None and ( + valid_mask.shape != tokens.shape or valid_mask.dtype != torch.bool + ): + raise ValueError("valid_mask must be boolean and have the tokens' shape") + if self.kind in {"dense", "wide"}: + logits = super().forward(tokens, positions) + if return_aux: + return logits, {"balance_loss": logits.new_zeros(()), "router_stats": []} + return logits + 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) + stats = [] + if self.kind in {"mhc", "identity_mhc"}: + x = x.unsqueeze(-2).expand(-1, -1, 4, -1) + for _ in range(self.repeats): + for index, block in enumerate(t.h): + if self.kind == "moe": + x = x + self._attention(block, x) + y, layer_stats = block.mlp(block.ln_2(x), valid_mask) + x = x + y + stats.append(layer_stats) + else: + x = self.connections[2 * index](x, lambda z, b=block: self._attention(b, z)) + x = self.connections[2 * index + 1](x, lambda z, b=block: b.mlp(b.ln_2(z))) + if self.kind in {"mhc", "identity_mhc"}: + x = x.mean(dim=-2) + x = t.ln_f(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, t.wte.weight) + if return_aux: + loss = router_balance_loss(stats) if stats else logits.new_zeros(()) + return logits, {"balance_loss": loss, "router_stats": stats} + return logits + + +def construct(config, spec, device): + """Historical config/spec convention, extended by ``spec['architecture']``.""" + architecture = spec["architecture"] + if architecture not in ARMS: + raise ValueError(f"Unknown architecture: {architecture}") + torch.manual_seed(spec["initialization"]) + cfg = GPT2Config( + vocab_size=config["vocab_size"], + n_positions=config.get("positions", 1024), + n_embd=config["hidden_size"], + n_head=config.get("attention_heads", config.get("heads", 12)), + n_layer=8, + resid_pdrop=config["dropout"], + embd_pdrop=config["dropout"], + attn_pdrop=config["dropout"], + activation_function="gelu_new", + use_cache=False, + ) + # Separate reproducible new-shape RNG, explicitly recorded in the manifest. + module_seed = spec.get("module_initialization", spec["initialization"] + 1_000_003) + model = ParametricGPT(cfg, architecture, module_seed) + model.initialization_seed = spec["initialization"] + return model.to(device) + + +def optimizer_for(model, lr, decay): + groups = [{"params": [], "weight_decay": decay}, {"params": [], "weight_decay": 0.0}] + for name, parameter in model.named_parameters(): + if not parameter.requires_grad: + continue + exempt = any(part in name for part in ("bias", "ln")) + exempt |= name.startswith("connections.") and (".norm." in name or ".alpha_" in name) + groups[int(exempt)]["params"].append(parameter) + return torch.optim.AdamW( + groups, lr=lr, betas=(0.9, 0.999), eps=1e-8, fused=next(model.parameters()).is_cuda + ) + + +def parameter_ledger(model): + d, layers = model.config.n_embd, len(model.transformer.h) + total = sum(parameter.numel() for parameter in model.parameters()) + expert = sum(p.numel() for n, p in model.named_parameters() if ".experts." in n) + controller = sum(p.numel() for n, p in model.named_parameters() if n.startswith("connections.")) + router = sum(p.numel() for n, p in model.named_parameters() if ".router." in n) + fixed = (model.config.vocab_size + model.config.n_positions) * d + 2 * d + attention_and_norms = 4 * d * d + 8 * d + if model.kind == "moe": + per_block = attention_and_norms + 8 * (4 * d * d + 3 * d) + 8 * d + else: + width = (16 if model.kind == "wide" else 4) * d + per_block = attention_and_norms + 2 * d * width + width + d + expected_controller = 0 + if model.kind in {"mhc", "identity_mhc"}: + n = 4 + count = 2 * n + (n * n if model.kind == "mhc" else 0) + alphas = 3 if model.kind == "mhc" else 2 + expected_controller = 2 * layers * (n * d * count + n * d + count + alphas) + if controller != expected_controller: + raise AssertionError( + f"Controller parameter mismatch: {controller} != {expected_controller}" + ) + expected = fixed + layers * per_block + expected_controller + if total != expected: + raise AssertionError(f"Parameter ledger mismatch: {total} != {expected}") + return { + "architecture": model.architecture, + "total_parameters": total, + "trainable_parameters": sum(p.numel() for p in model.parameters() if p.requires_grad), + "expected_parameters": expected, + "expert_parameters": expert, + "router_parameters": router, + "controller_parameters": controller, + "nominal_parameters_selected_per_token": total - expert + expert // 4, + "active_parameter_convention": ( + "All nonexpert parameters (including whole embedding table) plus two of eight " + "experts; not FLOPs or touched embedding rows." + ), + "unique_blocks": layers, + "repeats": model.repeats, + "executed_blocks": layers * model.repeats, + "residual_streams": 4 if controller else 1, + "parameter_dtype": str(next(model.parameters()).dtype), + "residual_dtype_under_bf16_autocast": "torch.float32 with FP32 parameters", + "controller_dtype": "torch.float32", + } + + +def flop_ledger(model, *, executed_tokens, projected_positions, attention_pairs, valid_tokens=None): + """Leading forward matmuls with actual padding/dispatch/readout counts. + + ``attention_pairs`` is sum(B*T*T) over microbatches, before block count. + Training 3x is explicitly an approximation; Sinkhorn autograd, scalar ops, + and a counting/replay pass are not silently folded into this estimate. + """ + d, blocks = model.config.n_embd, len(model.transformer.h) * model.repeats + valid_tokens = executed_tokens if valid_tokens is None else valid_tokens + attention = blocks * (8 * executed_tokens * d * d + 4 * attention_pairs * d) + readout = 2 * projected_positions * d * model.config.vocab_size + router = controller = 0 + if model.kind == "moe": + ffn = blocks * 4 * valid_tokens * d * (2 * 2 * d) + router = blocks * 2 * valid_tokens * d * 8 + else: + inner = (16 if model.kind == "wide" else 4) * d + ffn = blocks * 4 * executed_tokens * d * inner + if model.kind in {"mhc", "identity_mhc"}: + n = 4 + count = 2 * n + (n * n if model.kind == "mhc" else 0) + controller = ( + 2 * blocks * (2 * executed_tokens * n * d * count + 2 * executed_tokens * d * count) + ) + forward = attention + readout + ffn + router + controller + return { + "forward_attention_matmul_flops": attention, + "forward_ffn_matmul_flops": ffn, + "forward_readout_matmul_flops": readout, + "forward_router_matmul_flops": router, + "forward_controller_matmul_flops": controller, + "forward_leading_matmul_flops": forward, + "estimated_matmul_training_flops": 3 * forward, + "sinkhorn_normalization_passes": 39 if model.kind == "mhc" else 0, + "sinkhorn_matrix_elements_per_forward": 2 * blocks * executed_tokens * 16 + if model.kind == "mhc" + else 0, + "selected_expert_assignments": blocks * valid_tokens * 2 if model.kind == "moe" else 0, + "executed_input_tokens": executed_tokens, + "effective_input_tokens": valid_tokens, + "projected_positions": projected_positions, + "excluded_ops": ( + "Nonlinearities, normalization, dropout, dispatch/index-add, softmax, Sinkhorn " + "scalar arithmetic/autograd, final mean, counting/replay and optimizer; " + "3x is approximate." + ), + } + + +def initialization_manifest(model): + """CPU-byte hashes of each actual initialized tensor; no sampled hash.""" + shared, introduced = {}, {} + for name, tensor in model.state_dict().items(): + is_new = name.startswith("connections.") or ( + model.kind in {"moe", "wide"} and ".mlp." in name + ) + raw = tensor.detach().cpu().contiguous().reshape(-1).view(torch.uint8).numpy().tobytes() + (introduced if is_new else shared)[name] = hashlib.sha256(raw).hexdigest() + return { + "architecture": model.architecture, + "reference_initialization": getattr(model, "initialization_seed", None), + "module_initialization": model.module_seed, + "reference_blocks_before_slicing": 8, + "shared_tensor_sha256": shared, + "introduced_tensor_sha256": introduced, + } diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/parametric_architecture_train.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/parametric_architecture_train.py new file mode 100644 index 0000000000000000000000000000000000000000..55c77a2f48a116b87a2159b90bb2ab76a6730887 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/parametric_architecture_train.py @@ -0,0 +1,626 @@ +"""Resumable, exposure-matched training for the parametric architecture study. + +The ordinary data stream, answer-plus-EOS objective and generated evaluator are +shared with the historical experiment. MoE balancing is computed over the true +effective batch using an RNG-replayed routing pass, not a sum of local products. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import random +import time +from pathlib import Path + +import numpy as np +import torch +import transformers +from transformers import GPT2TokenizerFast + +from . import realworld_composition as historical +from .grok_depth import utc +from .grokking_reproduction import model_digest +from .realworld_composition_data import sha256, write_json + + +def _architecture(): + from . import parametric_architecture + + return parametric_architecture + + +def rng_state(device): + state = { + "python": random.getstate(), + "numpy": np.random.get_state(), + "cpu": torch.get_rng_state(), + } + if torch.device(device).type == "cuda": + state["cuda"] = torch.cuda.get_rng_state(device) + return state + + +def restore_rng(state, device): + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["cpu"].cpu()) + if "cuda" in state: + torch.cuda.set_rng_state(state["cuda"].cpu(), device) + + +def pack(records, pad, device): + """EOS is a valid input token; validity comes from lengths, never token IDs.""" + tokens, positions, labels = historical.pack(records, pad, device) + lengths = torch.tensor([len(r["encoded"]["input"]) for r in records], device=device) + valid = torch.arange(tokens.shape[1], device=device)[None] < lengths[:, None] + return tokens, positions, labels, valid + + +def _synchronize(device): + if torch.device(device).type == "cuda": + torch.cuda.synchronize(device) + + +def _finite(value, name): + if not math.isfinite(float(value)): + raise FloatingPointError(f"Nonfinite {name}; this candidate must retain its failure") + + +def update(model, optimizer, records, spec, device, pad): + """One historical effective batch, with exact full-batch routing gradients. + + Hard assignment fractions have no gradient. A no-grad pass collects their + global values when there are multiple microbatches; replaying the same + dropout RNG realizes the same routing in the differentiable pass. One + microbatch already contains the full objective and needs no prepass. + """ + if not records: + raise ValueError("An update requires at least one example") + microbatch = int(spec["microbatch_size"]) + if microbatch < 1: + raise ValueError("microbatch_size must be positive") + api = _architecture() + model.train() + optimizer.zero_grad(set_to_none=True) + chunks = [records[i : i + microbatch] for i in range(0, len(records), microbatch)] + is_moe = spec["architecture"] in {"M8", "M4", "LM4R2"} + needs_prepass = is_moe and len(chunks) > 1 + coefficient = float(spec.get("balance_coefficient", 0.01)) if is_moe else 0.0 + global_fractions, total_tokens, collected = None, None, [] + if needs_prepass: + before = rng_state(device) + try: + with torch.no_grad(): + for chunk in chunks: + tokens, positions, _, valid = pack(chunk, pad, device) + with historical.autocast(device): + _, aux = model(tokens, positions, valid_mask=valid, return_aux=True) + collected.append(aux["router_stats"]) + global_fractions, total_tokens = api.combine_router_fractions(collected) + finally: + restore_rng(before, device) + answer_loss, balance_loss = 0.0, 0.0 + executed, readout, attention = 0, 0, 0 + replay_count_error = torch.zeros((), dtype=torch.int64, device=device) + for chunk_index, chunk in enumerate(chunks): + tokens, positions, labels, valid = pack(chunk, pad, device) + with historical.autocast(device): + logits, aux = model(tokens, positions, valid_mask=valid, return_aux=True) + answer = historical.example_losses(logits, labels).sum() / len(records) + balance = ( + api.router_balance_loss( + aux["router_stats"], + assignment_fractions=global_fractions, + total_valid_tokens=total_tokens, + ) + if is_moe + else answer.new_zeros(()) + ) + loss = answer + coefficient * balance + if needs_prepass: + replay_count_error += sum( + (left["assignment_counts"] - right["assignment_counts"]).abs().sum() + for left, right in zip(collected[chunk_index], aux["router_stats"], strict=True) + ) + elif is_moe: + collected = [aux["router_stats"]] + global_fractions, total_tokens = api.combine_router_fractions(collected) + _finite(loss.detach(), "objective") + loss.backward() + answer_loss += float(answer.detach()) + balance_loss += float(balance.detach()) + executed += tokens.numel() + readout += positions.numel() + attention += len(chunk) * tokens.shape[1] ** 2 + if int(replay_count_error) != 0: + raise RuntimeError("MoE RNG replay did not reproduce routing assignment counts") + norm = torch.nn.utils.clip_grad_norm_( + model.parameters(), float(spec.get("clip_grad_norm", 1.0)), error_if_nonfinite=True + ) + _finite(norm, "gradient norm") + optimizer.step() + effective = sum(len(r["encoded"]["input"]) for r in records) + result = { + "loss": answer_loss, + "answer_ce": answer_loss, + "balance_loss": balance_loss, + "balance_coefficient": coefficient, + "objective": answer_loss + coefficient * balance_loss, + "gradient_norm": float(norm), + "executed_input_tokens": executed, + "effective_input_tokens": effective, + "padding_input_tokens": executed - effective, + "readout_positions": readout, + "attention_token_pairs": attention, + "routing_prepass_executed_input_tokens": executed if needs_prepass else 0, + "routing_prepass_effective_input_tokens": effective if needs_prepass else 0, + } + result["compute"] = api.flop_ledger( + model, + executed_tokens=executed, + valid_tokens=effective, + projected_positions=readout, + attention_pairs=attention, + ) + prepass = result["compute"]["forward_leading_matmul_flops"] if needs_prepass else 0 + result["compute"]["routing_prepass_matmul_flops"] = prepass + result["estimated_matmul_training_flops"] = ( + result["compute"]["estimated_matmul_training_flops"] + prepass + ) + result["compute"]["estimated_total_training_matmul_flops"] = result[ + "estimated_matmul_training_flops" + ] + if is_moe: + layer_count = len(global_fractions) + assignments = torch.stack( + [sum(c[layer]["assignment_counts"] for c in collected) for layer in range(layer_count)] + ) + processed = torch.stack( + [ + sum(c[layer]["processed_assignments"] for c in collected) + for layer in range(layer_count) + ] + ) + dropped = sum(s["dropped_assignments"] for c in collected for s in c) + if int(dropped) != 0 or not torch.equal(processed, assignments.sum(-1)): + raise AssertionError("Dropless routing lost selected token assignments") + result["router"] = { + "assignment_fractions": torch.stack(global_fractions).detach().cpu().tolist(), + "assignment_counts": assignments.detach().cpu().tolist(), + "valid_tokens_per_layer": effective, + "selected_assignments_per_layer": assignments.sum(-1).detach().cpu().tolist(), + "processed_assignments_per_layer": processed.detach().cpu().tolist(), + "router_entropy_per_layer": torch.stack( + [ + sum(c[layer]["entropy_sum"] for c in collected) / effective + for layer in range(layer_count) + ] + ) + .detach() + .cpu() + .tolist(), + "selected_probability_mass_per_layer": torch.stack( + [ + sum(c[layer]["selected_mass_sum"] for c in collected) / effective + for layer in range(layer_count) + ] + ) + .detach() + .cpu() + .tolist(), + "dropped_assignments": int(dropped), + "replay_assignment_count_error": int(replay_count_error), + "replay_checked": needs_prepass, + "balance_scope": ( + "full_effective_batch_two_pass_rng_replay" + if needs_prepass + else "full_effective_batch_single_forward" + ), + } + return result + + +def selection_score(metrics): + """Frozen development panels only; no held-out-composition selection.""" + atomic, composition = metrics["atomic"]["nll"], metrics["train_composition"]["nll"] + if atomic is None or composition is None: + raise ValueError("Both fixed development panels need answer NLL measurements") + value = 0.5 * atomic + 0.5 * composition + _finite(value, "development selection NLL") + return value + + +def _routing_metrics(router): + """Expose numeric dictionaries to the existing W&B sidecar's flattening.""" + if not router: + return {} + return { + "dropped_assignments": router["dropped_assignments"], + "replay_assignment_count_error": router["replay_assignment_count_error"], + "layers": { + str(layer): { + "entropy": router["router_entropy_per_layer"][layer], + "selected_probability_mass": router["selected_probability_mass_per_layer"][layer], + "expert_fraction": {str(i): value for i, value in enumerate(fractions)}, + } + for layer, fractions in enumerate(router["assignment_fractions"]) + }, + } + + +def save_checkpoint(path, model, optimizer, stream, counts, step, counters, device, **extra): + path = Path(path) + temporary = path.with_suffix(".tmp") + torch.save( + { + "format_version": 1, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "step": step, + "counters": counters, + "rng": rng_state(device), + **extra, + }, + temporary, + ) + temporary.replace(path) + + +def load_checkpoint(path, model, optimizer, stream, device): + state = torch.load(path, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + stream.load_state_dict(state["stream"]) + restore_rng(state["rng"], device) + return state + + +def _identity(config, spec): + payload = { + "model": config["model"], + "spec": spec, + "data_sha256": config["data_sha256"], + "tokenizer_sha256": config.get("tokenizer_sha256", config.get("tokenizer_files", {})), + "source_files": config.get("source_files", {}), + } + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + + +def verify(config, config_path=None): + """Check the concrete execution freeze; the historical design is not mutated.""" + if config.get("launch_enabled") is False: + raise ValueError("This configuration explicitly disables execution") + if sha256(config["data_file"]) != config["data_sha256"]: + raise ValueError("Frozen data changed") + for name, expected in config.get("tokenizer_sha256", {}).items(): + path = Path(config["tokenizer"]) / name + if sha256(path) != expected: + raise ValueError(f"Frozen tokenizer changed: {path}") + for group in ("tokenizer_files", "source_files"): + for path, expected in config.get(group, {}).items(): + if sha256(path) != expected: + raise ValueError(f"Frozen {group} changed: {path}") + if config.get("source_root"): + root = Path(config["source_root"]).resolve() + for module in (Path(__file__), Path(_architecture().__file__), Path(historical.__file__)): + if not module.resolve().is_relative_to(root): + raise ValueError(f"Imported code is outside the frozen source_root: {module}") + if config_path is not None: + if not config.get("execution_lock"): + raise ValueError("CLI requires an execution_lock with the frozen config hash") + lock = json.loads(Path(config["execution_lock"]).read_text()) + if lock["config_sha256"] != sha256(config_path): + raise ValueError("Frozen configuration changed") + if "torch" in lock.get("environment", {}): + if str(torch.__version__) != lock["environment"]["torch"]: + raise ValueError("Frozen torch version changed") + if "transformers" in lock.get("environment", {}): + if transformers.__version__ != lock["environment"]["transformers"]: + raise ValueError("Frozen transformers version changed") + + +def _setup(device, config): + torch.set_num_threads(int(config.get("cpu_threads", 4))) + if torch.device(device).type == "cuda": + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.cuda.reset_peak_memory_stats(device) + + +def _resources(device): + if torch.device(device).type != "cuda": + return {"peak_gpu_memory_bytes": 0, "peak_gpu_reserved_bytes": 0} + return { + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device), + "peak_gpu_reserved_bytes": torch.cuda.max_memory_reserved(device), + } + + +def _process_identity(): + """Different containers can both run Python as PID 1; identify the namespace.""" + identity = {"pid": os.getpid()} + if Path("/proc/self/stat").exists(): + identity["pid_namespace"] = os.readlink("/proc/self/ns/pid") + identity["start_ticks"] = Path("/proc/self/stat").read_text().rsplit(")", 1)[1].split()[19] + return identity + + +def run(config, spec, out, device="cuda:0"): + """Train one frozen candidate. An independent process must subsequently audit.""" + verify(config) + _setup(device, config) + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "trained.json").exists(): + trained = json.loads((out / "trained.json").read_text()) + if trained["identity"] != _identity(config, spec): + raise ValueError("Existing output belongs to a different frozen training recipe") + return trained + api = _architecture() + data = json.loads(Path(config["data_file"]).read_text()) + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + records = data["atoms"] + data["train_compositions"] + model = api.construct(config["model"], spec, device) + optimizer = api.optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + stream = historical.BatchStream(len(records), spec["sampling_seed"]) + identity = _identity(config, spec) + counts = np.zeros(len(records), dtype=np.int64) + counters = { + "training_seconds": 0.0, + "examples": 0, + "supervised_tokens": 0, + "executed_input_tokens": 0, + "effective_input_tokens": 0, + "estimated_matmul_training_flops": 0, + "routing_prepass_executed_input_tokens": 0, + } + initial_step, wall_offset, history, last = 0, 0.0, [], {} + if (out / "latest.pt").exists(): + saved = load_checkpoint(out / "latest.pt", model, optimizer, stream, device) + if saved["identity"] != identity: + raise ValueError("Checkpoint belongs to a different frozen training recipe") + counts, initial_step, counters = saved["counts"], saved["step"], saved["counters"] + wall_offset, last = saved.get("wall_seconds", 0.0), saved.get("last_update", {}) + learning = out / "learning.json" + history = [r for r in json.loads(learning.read_text()) if r["step"] <= initial_step] + metadata = json.loads((out / "run.json").read_text()) + metadata.update(pid=os.getpid(), resumed_from_step=initial_step) + del saved + else: + torch.manual_seed(spec["dropout_seed"]) + random.seed(spec["dropout_seed"]) + np.random.seed(spec["dropout_seed"]) + metadata = { + "spec": spec, + "model": config["model"], + "phase": config.get("phase", "development"), + "evaluation_nodes": config["evaluation_nodes"], + "world_sha256": config["data_sha256"], + "initial_model_sha256": model_digest(model), + "initial_tensor_sha256": historical.tensor_digests(model), + "initialization_manifest": api.initialization_manifest(model), + "parameters": sum(p.numel() for p in model.parameters()), + "parameter_ledger": api.parameter_ledger(model), + "atomic_examples": len(data["atoms"]), + "composition_examples": len(data["train_compositions"]), + "vocab_size": len(tokenizer), + "dtype": "BF16 AMP; FP32 parameters and Adam states", + "device": str(device), + "gpu": torch.device(device).index or 0, + "gpu_name": torch.cuda.get_device_name(device) + if torch.device(device).type == "cuda" + else "cpu", + "pid": os.getpid(), + "job_type": config.get("phase", "development") + "-training", + "tracking_group": config.get("tracking", {}).get("group", config.get("experiment")), + "learning_step_unit": "optimizer_updates", + "identity": identity, + "selection": "0.5 atomic + 0.5 train-composition NLL on original fixed panels", + "selection_panel_sizes": { + key: len(data["panels"][key]) for key in ("atomic", "train_composition") + }, + "moe_balance": ( + "full-effective-batch; single forward when one microbatch, otherwise two-pass " + "RNG replay; actual prepass compute included" + ), + "learning_rate_schedule": "historical lr * min((step - 1) / warmup_steps, 1)", + } + if config.get("execution_lock"): + metadata["execution_lock_sha256"] = sha256(config["execution_lock"]) + write_json(out / "run.json", metadata) + write_json(out / "learning.json", history) + nodes = set(config["evaluation_nodes"]) | {int(spec["steps"])} + log_interval = int(config.get("log_interval", 100)) + checkpoint_interval = int(config.get("resume_checkpoint_interval", 1000)) + started = time.perf_counter() + + def checkpoint(step): + save_checkpoint( + out / "latest.pt", + model, + optimizer, + stream, + counts, + step, + counters, + device, + identity=identity, + wall_seconds=wall_offset + time.perf_counter() - started, + last_update=last, + ) + + for step in range(initial_step, spec["steps"] + 1): + if step > initial_step: + warmup = int(spec["warmup_steps"]) + lr = spec["learning_rate"] * (min((step - 1) / warmup, 1.0) if warmup else 1.0) + for group in optimizer.param_groups: + group["lr"] = lr + ids = stream.batch(spec["batch_size"]) + selected = [records[i] for i in ids] + _synchronize(device) + begin = time.perf_counter() + last = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id) + _synchronize(device) + counters["training_seconds"] += time.perf_counter() - begin + 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", + "routing_prepass_executed_input_tokens", + ): + counters[key] += last[key] + if step in nodes or step % log_interval == 0: + if not any(r["step"] == step for r in history): + metrics = {} + if step in nodes: + metrics, predictions = historical.evaluate_dataset( + model, data, tokenizer, device + ) + write_json(out / f"predictions-{step:07d}.json", predictions) + metrics["selection"] = { + "mixed_answer_nll": selection_score(metrics), + "atomic_n": metrics["atomic"]["nll_n"], + "train_composition_n": metrics["train_composition"]["nll_n"], + } + if last.get("router"): + metrics["routing"] = _routing_metrics(last["router"]) + record = { + "step": step, + "metrics": metrics, + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "loss": last.get("answer_ce"), + "answer_ce": last.get("answer_ce"), + "balance_loss": last.get("balance_loss"), + "objective": last.get("objective"), + "gradient_norm": last.get("gradient_norm"), + "learning_rate": optimizer.param_groups[0]["lr"], + "atomic_epochs": float(counts[: len(data["atoms"])].mean()), + "composition_epochs": float(counts[len(data["atoms"]) :].mean()), + "router": last.get("router", {}), + "compute_per_update": last.get("compute", {}), + **_resources(device), + "created_utc": utc(), + } + history.append(record) + write_json(out / "learning.json", history) + print( + json.dumps({"step": step, "loss": record["loss"], "metrics": metrics}), + flush=True, + ) + write_json( + out / "status.json", + { + "state": "training", + "step": step, + "target_step": spec["steps"], + "loss": last.get("answer_ce"), + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "pid": os.getpid(), + "updated_utc": utc(), + }, + ) + if step in nodes or (step > initial_step and step % checkpoint_interval == 0): + checkpoint(step) + if step in nodes: + target = out / f"checkpoint-{step:07d}.pt" + temporary = target.with_suffix(".tmp") + torch.save( + {"model": model.state_dict(), "step": step, "identity": identity}, temporary + ) + temporary.replace(target) + np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts) + metrics, predictions = historical.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(), + "process_identity": _process_identity(), + "identity": identity, + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + **counters, + "selection_mixed_answer_nll": next( + r["metrics"]["selection"]["mixed_answer_nll"] + for r in reversed(history) + if r["step"] == spec["steps"] + ), + "wall_seconds": wall_offset + time.perf_counter() - started, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + return result + + +def audit(config, spec, out, device="cuda:0"): + """Reconstruct and regenerate the full endpoint in an independent process.""" + verify(config) + _setup(device, config) + out = Path(out) + trained = json.loads((out / "trained.json").read_text()) + same_process = ( + trained["process_identity"] == _process_identity() + if "process_identity" in trained + else trained["pid"] == os.getpid() + ) + if same_process: + raise ValueError("Independent audit must run in a different process") + if trained["identity"] != _identity(config, spec): + raise ValueError("Audit recipe differs from the training freeze") + if sha256(out / "latest.pt") != trained["checkpoint_sha256"]: + raise ValueError("Training checkpoint changed") + model = _architecture().construct(config["model"], spec, device) + checkpoint = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) + if checkpoint["step"] != spec["steps"]: + raise ValueError("Final checkpoint does not contain the requested endpoint") + model.load_state_dict(checkpoint["model"]) + del checkpoint + if model_digest(model) != trained["model_sha256"]: + raise ValueError("Reloaded model does not match the trained endpoint") + data = json.loads(Path(config["data_file"]).read_text()) + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + metrics, predictions = historical.evaluate_dataset( + model, data, tokenizer, device, full=True, autonomous=True + ) + if predictions != json.loads((out / "endpoint-predictions.json").read_text()): + raise AssertionError("Independent endpoint generation or NLL failed exact reproduction") + if metrics != json.loads((out / "endpoint.json").read_text()): + raise AssertionError("Independent endpoint metric recount failed") + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "process_identity": _process_identity(), + "source_process_identity": trained.get("process_identity"), + "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, + }, + ) + return result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/qwen_constraints.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/qwen_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..6181f6dad22ab1a99443ffddb19f67c7c6ad701b --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/qwen_constraints.py @@ -0,0 +1,94 @@ +"""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) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/qwen_path_learning.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/qwen_path_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..bc113a47da9c9fc22e346812c7f48f5ae7bc8b92 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/qwen_path_learning.py @@ -0,0 +1,416 @@ +"""Position-routed down updates, complete-answer objectives, and audited data helpers.""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import time +from datetime import datetime, timezone +from pathlib import Path + +os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") +os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import AutoModelForCausalLM, AutoTokenizer + +from .hebbian_data import TEMPLATE, encode_answer, score_answer +from .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 articles diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/qwen_path_train.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/qwen_path_train.py new file mode 100644 index 0000000000000000000000000000000000000000..fabb31112396100c708fafd83993acdb8c46f918 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/qwen_path_train.py @@ -0,0 +1,627 @@ +"""Frozen-matrix execution and development-only selection for path learning.""" + +from __future__ import annotations + +import json +import os +import platform +import shutil +import time + +import numpy as np +import torch +import 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 result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/realworld_composition.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/realworld_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..a05d1c9d956093315cedab365228e2fce72b6022 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/realworld_composition.py @@ -0,0 +1,629 @@ +"""Complete GPT/Loop training on original 2Wiki questions and atomic facts.""" + +from __future__ import annotations + +import copy +import hashlib +import json +import math +import os +import time +from contextlib import nullcontext +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import GPT2Config, GPT2TokenizerFast + +from .grok_depth import utc +from .grokking_reproduction import ReproductionGPT, model_digest +from .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), + canonical_answer_globally_unambiguous=row.get( + "canonical_answer_globally_unambiguous", True + ), + 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_unambiguous_canonical_answers": lambda r: r.get( + "canonical_answer_globally_unambiguous", True + ), + "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) + 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": row["id"], + "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": bool(row.get("unambiguous_answers", [])), + "canonical_answer_globally_unambiguous": row.get( + "canonical_answer_globally_unambiguous", True + ), + "invalid_generated_bridge_length": True, + } + for row 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, wall_seconds=None): + 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, + "wall_seconds": wall_seconds, + "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) + phase = config.get("phase", "development") + out = Path(config["results_root"]) / phase / 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 = checkpoint.get("wall_seconds") + if wall_offset is None: + wall_offset = history[-1]["wall_seconds"] if history else 0.0 + metadata = json.loads((out / "run.json").read_text()) + metadata.update(pid=os.getpid(), gpu=gpu, resumed_from_step=initial_step) + write_json(out / "run.json", metadata) + del checkpoint + else: + torch.manual_seed(spec["dropout_seed"]) + metadata = { + "spec": spec, + "model": config["model"], + "phase": phase, + "evaluation_nodes": config["evaluation_nodes"], + "execution_lock_sha256": sha256(config["execution_lock"]), + "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": phase + "-training", + "tracking_group": config["tracking"]["group"], + } + 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, + "training_seconds": counters["training_seconds"], + "examples": counters["examples"], + "wall_seconds": wall_offset + time.perf_counter() - started, + "pid": os.getpid(), + "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, + wall_offset + time.perf_counter() - started, + ) + 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, + ) + elif ( + step > initial_step and step % config.get("resume_checkpoint_interval", 1000000000) == 0 + ): + save_checkpoint( + out / "latest.pt", + model, + optimizer, + stream, + counts, + step, + counters, + wall_offset + time.perf_counter() - started, + ) + 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"]) / config.get("phase", "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}, + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/realworld_composition_data.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/realworld_composition_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e907ece415c9c6e027e965818c1b8e6f82a2462e --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/realworld_composition_data.py @@ -0,0 +1,270 @@ +"""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 which +evaluation facts may be learned separately, never with evaluation chain labels. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import string +import zipfile +from collections import Counter, defaultdict +from 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]} diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/realworld_confirmation.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/realworld_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..5cfed1010e1cc6f386e54d10c69675d34f4bed4a --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/realworld_confirmation.py @@ -0,0 +1,322 @@ +"""Data-only confirmation isolation and independent endpoint recounting.""" + +from __future__ import annotations + +import ast +import copy +import json +import re +import statistics +import string +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from .realworld_composition_data import normalize_answer, order, sha256, write_json + + +def head_bridge_names(data, canonical, aliases): + names = defaultdict(set) + for row in data["train_compositions"] + data["evaluation_compositions"]: + for index in (0, 2): + identifier = row["edges"][0][index] + labels = [canonical[identifier], row["surfaces"][0][index]] + for label in labels + aliases.get(identifier, []): + normalized = normalize_answer(label) + if normalized: + names[identifier].add(normalized) + return names + + +def answer_owners(canonical, aliases): + owners = defaultdict(set) + for identifier in set(canonical) | set(aliases): + for name in [canonical.get(identifier, ""), *aliases.get(identifier, [])]: + normalized = normalize_answer(name) + if normalized: + owners[normalized].add(identifier) + return owners + + +def isolate_confirmation(candidate, development, canonical, aliases): + """Exclude every chain touching a development head/bridge name, then rebuild.""" + dev_names = set().union(*head_bridge_names(development, canonical, aliases).values()) + formal_names = head_bridge_names(candidate, canonical, aliases) + excluded_entities = {e for e, names in formal_names.items() if names & dev_names} + excluded = {} + parts = {} + for key in ("train_compositions", "evaluation_compositions"): + excluded[key] = [ + r["id"] + for r in candidate[key] + if {r["edges"][0][0], r["edges"][0][2]} & excluded_entities + ] + excluded_ids = set(excluded[key]) + parts[key] = [copy.deepcopy(r) for r in candidate[key] if r["id"] not in excluded_ids] + all_chains = parts["train_compositions"] + parts["evaluation_compositions"] + used = {a for r in all_chains for a in r["atom_ids"]} + atoms = [copy.deepcopy(r) for r in candidate["atoms"] if r["id"] in used] + first, second = ({r["atom_ids"][i] for r in parts["train_compositions"]} for i in (0, 1)) + seen = first | second + direct = {(r["edge"][0], r["edge"][2]) for r in atoms} + pairs = {(r["edges"][0][0], r["edges"][1][2]) for r in parts["train_compositions"]} + operations = {tuple(e[1] for e in r["edges"]) for r in parts["train_compositions"]} + owners = answer_owners(canonical, aliases) + for row in atoms + all_chains: + identifier = row["edge"][2] if "edge" in row else row["edges"][1][2] + row["canonical_answer_globally_unambiguous"] = owners[normalize_answer(row["answer"])] == { + identifier + } + for row in all_chains: + a, b = row["atom_ids"] + row["role"] = ("I" if a in seen else "O") + ("I" if b in seen else "O") + row["required_role"] = ("I" if a in first else "O") + ("I" if b in second else "O") + pair = row["edges"][0][0], row["edges"][1][2] + row["known_direct_shortcut"] = pair in direct + row["head_tail_seen_in_combination_training"] = pair in pairs + row["operation_seen"] = tuple(e[1] for e in row["edges"]) in operations + panels = { + "test_" + role.lower(): [ + r["id"] + for r in sorted( + [r for r in parts["evaluation_compositions"] if r["role"] == role], + key=lambda r: order(r["id"], "panel:"), + )[:64] + ] + for role in ("II", "IO", "OI", "OO") + } + panels["train_composition"] = [ + r["id"] + for r in sorted(parts["train_compositions"], key=lambda r: order(r["id"], "panel:"))[:128] + ] + selected = {i for ids in panels.values() for i in ids} + required = {a for r in all_chains if r["id"] in selected for a in r["atom_ids"]} + panels["atomic"] = sorted( + required + | {r["id"] for r in sorted(atoms, key=lambda r: order(r["id"], "atom-panel:"))[:128]} + ) + data = {"atoms": atoms, **parts, "panels": panels} + report = { + "rule": ( + "Exclude chains whose head/bridge canonical, annotated surface or official alias " + "name overlaps development head/bridge names after author normalization; " + "retain shared tails." + ), + "excluded_entities": sorted(excluded_entities), + "excluded_case_ids": excluded, + "excluded_counts": {key: len(ids) for key, ids in excluded.items()}, + "colliding_names": sorted(dev_names & set().union(*formal_names.values())), + "model_results_used": False, + } + return data, report + + +def audit_confirmation(data, development, canonical, aliases): + """Recount from the selected records rather than selection bookkeeping.""" + atoms = {r["id"]: r for r in data["atoms"]} + train, held = data["train_compositions"], data["evaluation_compositions"] + rows = train + held + dev_names = head_bridge_names(development, canonical, aliases) + formal_names = head_bridge_names(data, canonical, aliases) + assert not set(dev_names) & set(formal_names) + assert not set().union(*dev_names.values()) & set().union(*formal_names.values()) + assert len(atoms) == len(data["atoms"]) + assert len({r["id"] for r in rows}) == len(rows) + + def chain(row): + return tuple(tuple(e) for e in row["edges"]) + + assert not {chain(r) for r in train} & {chain(r) for r in held} + held_questions = {normalize_answer(r["question"]) for r in held} + assert not {normalize_answer(r["question"]) for r in train} & held_questions + assert not {normalize_answer(r["question"]) for r in atoms.values()} & held_questions + assert not {normalize_answer(r["question"]) for r in atoms.values()} & { + normalize_answer(r["question"]) for r in development["atoms"] + } + seen = {a for r in train for a in r["atom_ids"]} + first, second = ({r["atom_ids"][i] for r in train} for i in (0, 1)) + owners = answer_owners(canonical, aliases) + for row in rows: + a, b = row["atom_ids"] + assert [atoms[a]["edge"], atoms[b]["edge"]] == row["edges"] + assert row["edges"][0][2] == row["edges"][1][0] + assert row["role"] == ("I" if a in seen else "O") + ("I" if b in seen else "O") + assert row["required_role"] == ("I" if a in first else "O") + ("I" if b in second else "O") + assert not row["structural_errors"] + assert not any(r["known_prior_case"] for r in held) + for pool in (list(atoms.values()), train, held): + prompt_answers = defaultdict(set) + for row in pool: + prompt_answers[normalize_answer(row["question"])].add(normalize_answer(row["answer"])) + identifier = row["edge"][2] if "edge" in row else row["edges"][1][2] + assert row["canonical_answer_globally_unambiguous"] == ( + owners[normalize_answer(row["answer"])] == {identifier} + ) + e = row["encoded"] + assert e["target"][-1] == 50256 and len(e["target"]) <= 64 + assert e["input"] == (e["prefix"] + e["target"])[:-1] + assert len(e["prefix"]) + len(e["target"]) <= 256 + assert all(len(answers) == 1 for answers in prompt_answers.values()) + panel_ids = {i for name, ids in data["panels"].items() if name != "atomic" for i in ids} + assert {a for r in rows if r["id"] in panel_ids for a in r["atom_ids"]} <= set( + data["panels"]["atomic"] + ) + return { + "passed": True, + "atoms": len(atoms), + "train_compositions": len(train), + "evaluation_compositions": len(held), + "evaluation_roles": dict(Counter(r["role"] for r in held)), + "required_role_counts": dict(Counter(r["required_role"] for r in held)), + "canonical_unambiguous_evaluation_count": sum( + r["canonical_answer_globally_unambiguous"] for r in held + ), + "panels": {name: len(ids) for name, ids in data["panels"].items()}, + "head_bridge_id_overlap": 0, + "head_bridge_normalized_name_overlap": 0, + "necessary_atomic_coverage": 1.0, + "known_direct_shortcuts": sum(r["known_direct_shortcut"] for r in held), + "unseen_operations": sum(not r["operation_seen"] for r in held), + "max_input_tokens": max(len(r["encoded"]["input"]) for r in list(atoms.values()) + rows), + "atomic_relations": dict(Counter(r["edge"][1] for r in atoms.values())), + "train_relation_pairs": dict(Counter(" -> ".join(e[1] for e in r["edges"]) for r in train)), + } + + +def finalize_confirmation(config): + """Independently score raw outputs using the pinned author's scorer functions.""" + root, art = Path(config["results_root"]), Path(config["artifact_root"]) + data = json.loads(Path(config["data_file"]).read_text()) + scorer = Path(config["official_scorer"]) + scope = dict(re=re, string=string, Counter=Counter) + tree = ast.parse(scorer.read_text()) + functions = [ + n + for n in tree.body + if isinstance(n, ast.FunctionDef) and n.name in {"normalize_answer", "exact_match_score"} + ] + exec(compile(ast.Module(body=functions, type_ignores=[]), str(scorer), "exec"), scope) + + def score(prediction, row): + return float( + any( + scope["exact_match_score"](prediction, g) + for g in [row["answer"], *row.get("aliases", [])] + ) + ) + + held = data["evaluation_compositions"] + summary, scores, atom_scores, exposures, metadata = {}, {}, {}, {}, {} + for spec in config["runs"]: + name = spec["name"] + out = root / config["phase"] / name + complete = json.loads((out / "complete.json").read_text()) + assert complete["step"] == spec["steps"] and complete["independently_reloaded"] + raw = json.loads((out / "endpoint-predictions.json").read_text()) + metrics = json.loads((out / "endpoint.json").read_text()) + for group, records in [ + ("atomic", data["atoms"]), + ("train_composition", data["train_compositions"]), + ("test_all", held), + ]: + by_id = {p["id"]: p for p in raw[group]} + assert len(by_id) == len(records) == len(raw[group]) + assert set(by_id) == {r["id"] for r in records} + recomputed = {r["id"]: score(by_id[r["id"]]["prediction"], r) for r in records} + assert all(recomputed[i] == by_id[i]["alias_em"] for i in recomputed) + assert abs(sum(recomputed.values()) / len(records) - metrics[group]["alias_em"]) < 1e-12 + if group == "test_all": + scores[name] = recomputed + for role in ("II", "IO", "OI", "OO"): + selected = [r for r in held if r["role"] == role] + assert ( + abs( + sum(recomputed[r["id"]] for r in selected) / len(selected) + - metrics["test_" + role.lower()]["alias_em"] + ) + < 1e-12 + ) + if group == "atomic": + atom_scores[name] = recomputed + summary[name] = metrics + exposures[name] = { + step: np.load(out / f"exposure-{step:07d}.npz")["counts"] + for step in config["evaluation_nodes"] + } + metadata[name] = json.loads((out / "run.json").read_text()) + assert complete["checkpoint_sha256"] == sha256(out / "latest.pt") + comparisons = [] + for seed in sorted({s["initialization"] for s in config["runs"]}): + specs = {s["architecture"]: s for s in config["runs"] if s["initialization"] == seed} + assert set(specs) == {"standard8", "loop4x2", "standard4"} + names = [s["name"] for s in specs.values()] + assert len({metadata[n]["common_four_block_initial_sha256"] for n in names}) == 1 + for step in config["evaluation_nodes"]: + assert all( + np.array_equal(exposures[names[0]][step], exposures[n][step]) for n in names[1:] + ) + for baseline in ("standard8", "standard4"): + loop, base = specs["loop4x2"]["name"], specs[baseline]["name"] + for role in ("all", "OO"): + selected = held if role == "all" else [r for r in held if r["role"] == role] + common = [ + r + for r in selected + if all(atom_scores[n][a] for n in (loop, base) for a in r["atom_ids"]) + ] + comparisons.append( + { + "initialization": seed, + "baseline": baseline, + "pool": role, + "n": len(selected), + "paired_difference": sum( + scores[loop][r["id"]] - scores[base][r["id"]] for r in selected + ) + / len(selected), + "both_models_necessary_atoms_correct_n": len(common), + "both_models_necessary_atoms_correct_coverage": len(common) / len(selected), + "conditional_paired_difference": sum( + scores[loop][r["id"]] - scores[base][r["id"]] for r in common + ) + / len(common) + if common + else None, + } + ) + means = {} + for architecture in ("standard8", "loop4x2", "standard4"): + names = [s["name"] for s in config["runs"] if s["architecture"] == architecture] + means[architecture] = {} + for group in ( + "atomic", + "train_composition", + "test_all", + "test_ii", + "test_io", + "test_oi", + "test_oo", + "autonomous", + ): + values = [summary[n][group]["alias_em"] for n in names] + means[architecture][group] = { + "mean": statistics.mean(values), + "sample_sd": statistics.stdev(values), + "per_initialization": values, + } + result = { + "passed": True, + "runs": len(config["runs"]), + "scientific_updates": sum(s["steps"] for s in config["runs"]), + "independent_dataset_splits": 1, + "paired_initializations": 3, + "paired_exposures_equal_at_all_nodes": True, + "architecture_scores": means, + "paired_comparisons": comparisons, + "source_data_sha256": sha256(config["data_file"]), + "official_scorer_sha256": sha256(scorer), + } + write_json(art / "confirmation-summary.json", summary) + write_json(art / "confirmation-recount-audit.json", result) + return result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..1b6fcadbe2e7be2944fe6e398e29c0812ca1329f --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py @@ -0,0 +1,119 @@ +"""Registered relation/component and paired-knowledge trajectory descriptions.""" + +from __future__ import annotations + +import json +from collections import defaultdict +from pathlib import Path + +from .realworld_composition_data import write_json + + +def threshold_intervals(history, group, threshold): + passed = [r["metrics"][group]["alias_em"] >= threshold for r in history] + + def interval(index): + if index is None: + return None + return [history[index - 1]["step"] if index else None, history[index]["step"]] + + first = next((i for i, value in enumerate(passed) if value), None) + sustained = next((i for i, value in enumerate(passed) if value and all(passed[i:])), None) + return { + "first_observed_interval": interval(first), + "sustained_observed_interval": interval(sustained), + } + + +def analyze_confirmation(config): + root = Path(config["results_root"]) / config["phase"] + data = json.loads(Path(config["data_file"]).read_text()) + held = {r["id"]: r for r in data["evaluation_compositions"]} + endpoint_groups, thresholds, nodes = {}, {}, {} + for spec in config["runs"]: + name = spec["name"] + out = root / name + raw = json.loads((out / "endpoint-predictions.json").read_text())["test_all"] + by_relation, by_component = defaultdict(list), defaultdict(list) + for prediction in raw: + row = held[prediction["id"]] + by_relation[" -> ".join(e[1] for e in row["edges"])].append(prediction["alias_em"]) + by_component[row["group"]].append(prediction["alias_em"]) + endpoint_groups[name] = { + key: {k: {"n": len(v), "alias_em": sum(v) / len(v)} for k, v in groups.items()} + for key, groups in [ + ("relation_pair", by_relation), + ("source_head_bridge_component", by_component), + ] + } + history = json.loads((out / "learning.json").read_text()) + thresholds[name] = { + f"{group}_{value}": threshold_intervals(history, group, value) + for group, value in [("train_composition", 0.99), ("test_all", 0.5), ("test_all", 0.9)] + } + nodes[name] = {} + for step in config["evaluation_nodes"]: + node = json.loads((out / f"predictions-{step:07d}.json").read_text()) + nodes[name][step] = { + group: {r["id"]: r["alias_em"] for r in node[group]} + for group in ("atomic", "test_all") + } + trajectories = [] + for seed in sorted({s["initialization"] for s in config["runs"]}): + specs = {s["architecture"]: s for s in config["runs"] if s["initialization"] == seed} + loop = specs["loop4x2"]["name"] + for baseline in ("standard8", "standard4"): + base = specs[baseline]["name"] + for step in config["evaluation_nodes"]: + left, right = nodes[loop][step], nodes[base][step] + assert set(left["test_all"]) == set(right["test_all"]) + for pool in ("all", "OO"): + selected = [ + held[i] + for i in left["test_all"] + if pool == "all" or held[i]["role"] == pool + ] + common = [ + r + for r in selected + if all(n["atomic"][a] for n in (left, right) for a in r["atom_ids"]) + ] + trajectories.append( + { + "initialization": seed, + "baseline": baseline, + "step": step, + "pool": pool, + "panel_n": len(selected), + "both_models_necessary_atoms_correct_n": len(common), + "both_models_necessary_atoms_correct_coverage": len(common) + / len(selected), + "full_panel_paired_difference": sum( + left["test_all"][r["id"]] - right["test_all"][r["id"]] + for r in selected + ) + / len(selected), + "conditional_paired_difference": sum( + left["test_all"][r["id"]] - right["test_all"][r["id"]] + for r in common + ) + / len(common) + if common + else None, + } + ) + result = { + "endpoint_groups": endpoint_groups, + "threshold_intervals": thresholds, + "paired_knowledge_trajectories": trajectories, + "trajectory_scope": ( + "Fixed panels at registered nodes; threshold brackets are descriptive and do not " + "identify exact crossing times or establish grokking." + ), + "endpoint_scope": ( + "Full registered evaluation pool; source components are shared by questions, " + "not independent worlds." + ), + } + write_json(Path(config["artifact_root"]) / "confirmation-analysis.json", result) + return result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/recurrence_use.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/recurrence_use.py new file mode 100644 index 0000000000000000000000000000000000000000..3f2cf4432769a0bc1ea0278bf25468307718877b --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/recurrence_use.py @@ -0,0 +1,416 @@ +"""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 frequency +from creating additional scientific observations. +""" + +from __future__ import annotations + +import time + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import EOS, prompt_rows, truth_path_details +from .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, + } diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/representation_alignment.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/representation_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..923e412fdf09bfaf85ca6de1fcb11cf4d6e754de --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/representation_alignment.py @@ -0,0 +1,269 @@ +"""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 hashlib +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .latent_scaling import build_world, construct, model_digest +from .storage_composition import data_digest, evaluate, file_hash, pack_sentences +from .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}, + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/residual_cache.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/residual_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..20f4f21ac38bfedf6fa1d48968333c80c07f06ea --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/residual_cache.py @@ -0,0 +1,258 @@ +"""Shared LoopGPT backbone with independently controlled residual and KV access. + +The single/gamma=1 numerical path delegates to the historical shared-cache +implementation. Eight unique controllers are reused across every loop; streams +and the first-loop per-layer KV are carried through the complete unroll. +""" + +from __future__ import annotations + +import torch +from torch import nn +from torch.nn import functional as F + +from .grok_depth import make_optimizer as ordinary_optimizer +from .grok_loop_model import _positive_integer +from .latent_scaling import construct as ordinary_construct +from .parametric_architecture import HyperConnection, residual_mix, sinkhorn +from .shared_cache import SharedCacheGPT +from .shared_cache import executed_flops as cache_flops + +KINDS = ("single", "identity_mhc", "mhc") +_compiled_sinkhorn = None + + +def training_sinkhorn(logits): + global _compiled_sinkhorn + if _compiled_sinkhorn is None: + _compiled_sinkhorn = torch.compile( + sinkhorn, fullgraph=True, dynamic=False, options={"triton.cudagraphs": False} + ) + return _compiled_sinkhorn(logits) + + +class LoopHyperConnection(HyperConnection): + def coefficients(self, x): + n = self.streams + with torch.autocast(x.device.type, enabled=False): + dynamic = self.projection(self.norm(x.float().flatten(-2))) + pre = torch.sigmoid(dynamic[..., :n] * self.alpha_pre + self.pre_bias) + 1e-6 + post = 2 * torch.sigmoid(dynamic[..., n : 2 * n] * self.alpha_post + self.post_bias) + matrix = None + if not self.identity: + logits = dynamic[..., 2 * n :].reshape(*x.shape[:-2], n, n) + logits = logits * self.alpha_res + self.res_bias + projection = training_sinkhorn if self.training and x.is_cuda else sinkhorn + matrix = projection(logits) + return pre, post, matrix + + +class ResidualCacheGPT(SharedCacheGPT): + def __init__( + self, + config, + repeats, + dropout=0.0, + arm="local", + window=2, + residual_kind="single", + gamma=1.0, + controller_seed=107260751, + ): + super().__init__(config, repeats, dropout, arm, window) + if residual_kind not in KINDS or gamma <= 0: + raise ValueError("Invalid residual kind or branch scale") + self.residual_kind, self.gamma = residual_kind, float(gamma) + self.diagnostic_records = None + if residual_kind != "single": + with torch.random.fork_rng(devices=[]): + torch.manual_seed(controller_seed) + self.connections = nn.ModuleList( + LoopHyperConnection(config.width, i, identity=residual_kind == "identity_mhc") + for i in range(2 * config.layers) + ) + + def _record(self, x, update, recursion, layer, branch, matrix=None): + if self.diagnostic_records is None: + return + xf, uf = x.detach().float(), update.detach().float() + if self.residual_kind == "single": + mean, contrast = xf, xf.new_zeros(()) + else: + mean = xf.mean(-2) + contrast = (xf - mean.unsqueeze(-2)).square().mean() + record = dict( + loop=recursion + 1, + layer=layer, + branch=branch, + mean_square=float(mean.square().mean()), + coordinate_variance=float(mean.var(-1, unbiased=False).mean()), + stream_contrast_square=float(contrast), + update_square=float(uf.square().mean()), + ) + if matrix is not None: + a = matrix.detach().float() + previous = getattr(self, "diagnostic_product", None) + product = a if previous is None else previous @ a + self.diagnostic_product = product + record.update( + max_row_error=float((a.sum(-1) - 1).abs().max()), + max_column_error=float((a.sum(-2) - 1).abs().max()), + max_spectral_norm=float(torch.linalg.matrix_norm(a, ord=2).max()), + product_max_row_error=float((product.sum(-1) - 1).abs().max()), + product_max_column_error=float((product.sum(-2) - 1).abs().max()), + product_max_spectral_norm=float(torch.linalg.matrix_norm(product, ord=2).max()), + ) + self.diagnostic_records.append(record) + + def _connection(self, x, sublayer, connection, recursion, layer, branch): + pre, post, matrix = connection.coefficients(x) + with torch.autocast(x.device.type, enabled=False): + contracted = (pre[..., None] * x.float()).sum(-2) + y = sublayer(contracted.to(x.dtype)) + with torch.autocast(x.device.type, enabled=False): + residual = x.float() if matrix is None else residual_mix(x.float(), matrix) + update = post[..., None] * (self.gamma * y.float()).unsqueeze(-2) + output = residual + update + self._record(output, update, recursion, layer, branch, matrix) + return output.to(x.dtype) + + def forward(self, tokens, positions=None, repeats=None): + count = self.repeats if repeats is None else _positive_integer(repeats, "repeats") + if self.residual_kind == "single" and self.gamma == 1 and self.diagnostic_records is None: + return super().forward(tokens, positions, count) + length = tokens.shape[1] + if length > self.config.context: + raise ValueError("Input exceeds mask context") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(length, device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + if self.residual_kind != "single": + x = x.unsqueeze(-2).expand(*x.shape[:-1], 4, x.shape[-1]) + causal = self.shared_causal_mask[:length, :length] + joined_mask = torch.cat((causal, causal), dim=-1) + shared = [] + for recursion in range(count): + for layer, block in enumerate(self.blocks): + + def attention_branch(state, block=block, recursion=recursion, layer=layer): + z = block.ln1(state) + batch, size, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, size, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + q, k, v = (t.transpose(1, 2) for t in (q, k, v)) + if recursion == 0: + shared.append((k, v)) + if recursion == 0 or self.memory_arm == "local" or self.disable_shared: + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=p) + else: + first_k, first_v = (k, v) if self.duplicate_current else shared[layer] + y = F.scaled_dot_product_attention( + q, + torch.cat((first_k, k), dim=-2), + torch.cat((first_v, v), dim=-2), + attn_mask=joined_mask, + dropout_p=p, + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, size, width)) + return F.dropout(y, p=p, training=self.training) + + def mlp_branch(state, block=block): + return F.dropout(block.mlp(block.ln2(state)), p=p, training=self.training) + + if self.residual_kind == "single": + for branch, sublayer in [("attention", attention_branch), ("mlp", mlp_branch)]: + update = self.gamma * sublayer(x) + x = x + update + self._record(x, update, recursion, layer, branch) + else: + x = self._connection( + x, + attention_branch, + self.connections[2 * layer], + recursion, + layer, + "attention", + ) + x = self._connection( + x, mlp_branch, self.connections[2 * layer + 1], recursion, layer, "mlp" + ) + if self.residual_kind != "single": + x = x.mean(-2) + 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 construct(spec, device): + reference = ordinary_construct(spec, "cpu") + torch.manual_seed(spec["initialization"]) + return ResidualCacheGPT( + reference.config, + spec["repeats"], + spec["dropout"], + spec.get("memory_arm", "local"), + spec.get("window", 2), + spec.get("residual_kind", "single"), + spec.get("gamma", 1), + spec.get("controller_initialization_seed", 107260751), + ).to(device) + + +def make_optimizer(model, lr, weight_decay): + if model.residual_kind == "single": + return ordinary_optimizer(model, lr, weight_decay) + decay, no_decay = [], [] + for name, parameter in model.named_parameters(): + # res_bias is a matrix but, like the other controller biases, has no decay. + group = no_decay if parameter.ndim < 2 or name.endswith(".res_bias") else decay + group.append(parameter) + return torch.optim.AdamW( + [{"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0}], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + fused=True, + capturable=True, + ) + + +def executed_flops(config, repeats, batch, sequence, arm, kind, output_positions=9, backward=True): + """Historical matmul ledger plus controller projections and stream mixing. + + Sinkhorn and elementwise operations are excluded and measured in wall time. + The inherited three-forward backward convention is an approximation. + """ + base = cache_flops(config, repeats, batch, sequence, arm, output_positions, backward) + if kind == "single": + return base + n, d = 4, config.width + count = 2 * n + (n * n if kind == "mhc" else 0) + controllers = 2 * config.layers * repeats + per_token = 2 * n * d * count + (2 * n * n * d if kind == "mhc" else 0) + return base + batch * sequence * controllers * per_token * (3 if backward else 1) + + +def install_training_adapter(spec): + from . import latent_scaling as latent + + latent.construct = construct + latent.make_optimizer = make_optimizer + latent.flops = lambda config, repeats, batch, sequence, output_positions=9, backward=True: ( + executed_flops( + config, + repeats, + batch, + sequence, + spec.get("memory_arm", "local"), + spec.get("residual_kind", "single"), + output_positions, + backward, + ) + ) + return latent diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/sequential_data.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/sequential_data.py new file mode 100644 index 0000000000000000000000000000000000000000..dbd398e9973bad820eec8616d2c30ce3b7dd0626 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/sequential_data.py @@ -0,0 +1,379 @@ +"""Deterministic, source-grounded splits for sequential knowledge acquisition. + +The source examples are existing audited 2Wiki adaptations. We change only their +training availability, never their facts, names, answers, or tokenization. +""" + +from __future__ import annotations + +import copy +from collections import Counter, defaultdict +from dataclasses import asdict, dataclass + +from .realworld_composition_data import normalize_answer, order + + +@dataclass(frozen=True) +class SplitSettings: + split: str + bb_count: int = 64 + train_count: int = 512 + evaluation_count: int = 64 + max_shared_b_fact: int = 4 + + +def chain_key(row): + return tuple(tuple(edge) for edge in row["edges"]) + + +def operation(row): + return tuple(edge[1] for edge in row["edges"]) + + +def entities(row): + return {value for edge in row["edges"] for value in (edge[0], edge[2])} + + +def balanced_order(rows, salt): + """Round-robin relation pairs rather than favor the largest answer families.""" + groups = defaultdict(list) + for row in rows: + groups[operation(row)].append(row) + for group in groups.values(): + group.sort(key=lambda row: order(row["id"], salt)) + pairs = sorted(groups, key=lambda pair: order(pair, salt)) + for position in range(max(map(len, groups.values()), default=0)): + for pair in pairs: + if position < len(groups[pair]): + yield groups[pair][position] + + +def safe_atom_ids(atoms, b_ids): + """Exclude exact answer-equivalent addresses and explicit inverse facts. + + This guards known label leakage, not every possible real-world inference. + Entity names may appear in unrelated facts, as required for name familiarity. + """ + direct = {(atoms[key]["edge"][0], atoms[key]["edge"][2]) for key in b_ids} + inverse = set() + for key in b_ids: + head, relation, tail = atoms[key]["edge"] + if relation == "spouse": + inverse.add((tail, "spouse", head)) + elif relation in {"father", "mother"}: + inverse.add((tail, "child", head)) + elif relation == "child": + inverse.update({(tail, "father", head), (tail, "mother", head)}) + return { + key + for key, row in atoms.items() + if key not in b_ids + and (row["edge"][0], row["edge"][2]) not in direct + and tuple(row["edge"]) not in inverse + } + + +def build_split(source, settings, labels=None): + """Select BB first, reserve real A witnesses, then add A-only practice.""" + atoms = {row["id"]: row for row in source["atoms"]} + incident = defaultdict(set) + for key, row in atoms.items(): + for entity in (row["edge"][0], row["edge"][2]): + incident[entity].add(key) + label_owners = defaultdict(set) + for entity, label in (labels or {}).items(): + label_owners[normalize_answer(label)].add(entity) + + def unambiguous(row): + return all( + len(label_owners[normalize_answer(labels[entity])]) == 1 + for entity in entities(row) + if labels and entity in labels + ) + + unique = {} + for row in source["train_compositions"] + source["evaluation_compositions"]: + if row.get("structural_errors") or row.get("known_direct_shortcut"): + continue + if not unambiguous(row): + continue + key = chain_key(row) + if key not in unique or row["id"] < unique[key]["id"]: + unique[key] = row + rows = list(unique.values()) + counts = Counter(operation(row) for row in rows) + candidates = [ + row + for row in rows + if counts[operation(row)] >= 12 + and all(incident[entity] - set(row["atom_ids"]) for entity in entities(row)) + ] + b_ids, witness_ids, selected_bb = set(), set(), [] + b_uses = Counter() + for row in balanced_order(candidates, settings.split + ":bb:"): + proposed = b_ids | set(row["atom_ids"]) + if proposed & witness_ids: + continue + if any(b_uses[key] >= settings.max_shared_b_fact for key in row["atom_ids"]): + continue + safe = safe_atom_ids(atoms, proposed) + if not witness_ids <= safe: + continue + witnesses = set() + for entity in entities(row): + options = incident[entity] & safe + if not options: + break + # Reuse an existing witness when possible; otherwise use a fixed hash. + options = (options & witness_ids) or options + witnesses.add(min(options, key=lambda key: order(key, settings.split + ":witness:"))) + else: + b_ids = proposed + witness_ids |= witnesses + selected_bb.append(row) + b_uses.update(row["atom_ids"]) + if len(selected_bb) == settings.bb_count: + break + if len(selected_bb) < settings.bb_count: + raise ValueError(f"Only {len(selected_bb)} valid BB chains for {settings.split}") + + safe = safe_atom_ids(atoms, b_ids) + b_head_answers = {(atoms[key]["edge"][0], atoms[key]["edge"][2]) for key in b_ids} + + def admissible_a_chain(row): + return ( + set(row["atom_ids"]) <= safe + and (row["edges"][0][0], row["edges"][1][2]) not in b_head_answers + ) + + aa = [row for row in rows if admissible_a_chain(row)] + available_operations = Counter(operation(row) for row in aa) + required_operations = {operation(row) for row in selected_bb} + if any(available_operations[pair] < 2 for pair in required_operations): + raise ValueError("A target operation lacks A-only training and evaluation examples") + # Reserve held-out AA chains and real training witnesses for both old roles. + # BA/AB likewise require the old constituent to have prior use in that role. + by_first, by_second = defaultdict(list), defaultdict(list) + for row in aa: + by_first[row["atom_ids"][0]].append(row) + by_second[row["atom_ids"][1]].append(row) + chosen_train, train_keys, heldout_keys = [], set(), set() + pools = {"AA": [], "BA": [], "AB": [], "BB": selected_bb} + + def choose_witness(options, forbidden): + options = [row for row in options if chain_key(row) not in forbidden] + if not options: + return None + existing = [row for row in options if chain_key(row) in train_keys] + return min(existing or options, key=lambda row: order(row["id"], settings.split + ":role:")) + + def add_training(row): + key = chain_key(row) + if key not in train_keys: + chosen_train.append(row) + train_keys.add(key) + + heldout_operations = Counter() + for row in balanced_order(aa, settings.split + ":eval:AA"): + key = chain_key(row) + if ( + key in train_keys + or heldout_operations[operation(row)] >= available_operations[operation(row)] - 2 + ): + continue + forbidden = heldout_keys | {key} + first = choose_witness(by_first[row["atom_ids"][0]], forbidden) + second = choose_witness(by_second[row["atom_ids"][1]], forbidden) + if first is None or second is None: + continue + pools["AA"].append(row) + heldout_keys.add(key) + heldout_operations[operation(row)] += 1 + add_training(first) + add_training(second) + if len(pools["AA"]) == settings.evaluation_count: + break + for role in ["BA", "AB"]: + candidates = [ + row + for row in rows + if set(row["atom_ids"]) <= safe | b_ids + and "".join("B" if key in b_ids else "A" for key in row["atom_ids"]) == role + and operation(row) in available_operations + ] + for row in balanced_order(candidates, settings.split + ":eval:" + role): + old_index = 1 if role == "BA" else 0 + index = by_second if old_index else by_first + witness = choose_witness(index[row["atom_ids"][old_index]], heldout_keys) + if witness is None: + continue + pools[role].append(row) + add_training(witness) + if len(pools[role]) == settings.evaluation_count: + break + for role in ["AA", "BA", "AB"]: + if len(pools[role]) < min(8, settings.evaluation_count): + raise ValueError(f"Insufficient role-experienced {role}: {len(pools[role])}") + required_operations |= {operation(row) for pool in pools.values() for row in pool} + operation_support = Counter(operation(row) for row in chosen_train) + for row in balanced_order(aa, settings.split + ":operation-support:"): + pair = operation(row) + target = min(8, max(1, available_operations[pair] // 2)) + if ( + pair in required_operations + and operation_support[pair] < target + and chain_key(row) not in heldout_keys + ): + before = len(chosen_train) + add_training(row) + operation_support[pair] += len(chosen_train) - before + if len(chosen_train) > settings.train_count: + raise ValueError( + f"Training size below required role/operation support: {len(chosen_train)}" + ) + target_entities = {entity for row in selected_bb for entity in entities(row)} + relevant_aa = [row for row in aa if entities(row) & target_entities] + for pool in [relevant_aa, aa]: + if len(chosen_train) == settings.train_count: + break + for row in balanced_order(pool, settings.split + ":train:"): + if chain_key(row) in train_keys | heldout_keys: + continue + add_training(row) + if len(chosen_train) == settings.train_count: + break + trained_operations = {operation(row) for row in chosen_train} + if not required_operations <= trained_operations: + raise ValueError(f"A training lacks operations: {required_operations - trained_operations}") + + a_ids = witness_ids | { + key + for row in chosen_train + [row for pool in pools.values() for row in pool] + for key in row["atom_ids"] + if key not in b_ids + } + final_atoms = [] + for key in sorted(a_ids | b_ids): + row = copy.deepcopy(atoms[key]) + row["subset"] = "A" if key in a_ids else "B" + final_atoms.append(row) + training = copy.deepcopy(chosen_train) + for row in training: + row["sequential_role"] = row["role"] = "AA" + evaluation = [] + for role, pool in pools.items(): + for original in pool: + row = copy.deepcopy(original) + row["sequential_role"] = row["role"] = role + row["all_entities_seen_in_a"] = entities(row) <= { + entity for key in a_ids for entity in (atoms[key]["edge"][0], atoms[key]["edge"][2]) + } + row["operation_seen"] = operation(row) in trained_operations + evaluation.append(row) + data = { + "schema": "sequential-transfer-v1", + "split": settings.split, + "settings": asdict(settings), + "atoms": final_atoms, + "train_compositions": training, + "evaluation_compositions": evaluation, + "stage_a_atom_ids": sorted(a_ids), + "stage_b_atom_ids": sorted(b_ids), + "entity_witness_atom_ids": sorted(witness_ids), + "panels": { + "atomic_A": sorted(a_ids), + "atomic_B": sorted(b_ids), + "train_composition": [row["id"] for row in training], + **{role: [row["id"] for row in pool] for role, pool in pools.items()}, + }, + "selection_audit": { + "source_unique_eligible_chains": len(rows), + "source_known_entity_bb_candidates": len(candidates), + "selection_uses_model_outputs": False, + "selection_uses_original_official_split": False, + "known_entity_definition": "Each entity occurs in at least one real A atomic fact.", + "facts_are_original_source_edges": True, + "training_and_evaluation_use_original_questions": True, + "semantic_scope": ( + "Reuse prior structural/semantic exclusions; not an exhaustive new human review. " + "Exclude exact B head-answer supervision and explicit spouse/parent inverses. " + "Other possible real-world inferences are not ruled out." + ), + }, + } + data["audit"] = audit_split(data) + return data + + +def audit_split(data): + atoms = {row["id"]: row for row in data["atoms"]} + a_ids, b_ids = set(data["stage_a_atom_ids"]), set(data["stage_b_atom_ids"]) + if a_ids & b_ids or a_ids | b_ids != set(atoms): + raise ValueError("Atomic A/B partition is not disjoint and exhaustive") + a_entities = { + entity for key in a_ids for entity in (atoms[key]["edge"][0], atoms[key]["edge"][2]) + } + trains = data["train_compositions"] + evaluations = data["evaluation_compositions"] + train_keys = {chain_key(row) for row in trains} + if train_keys & {chain_key(row) for row in evaluations}: + raise ValueError("A held-out semantic chain appears in composition training") + if not all(set(row["atom_ids"]) <= a_ids for row in trains): + raise ValueError("B fact leaked through A composition training") + if not a_ids <= safe_atom_ids(atoms, b_ids): + raise ValueError("An equivalent or explicit inverse B fact leaked into A") + b_answers = {(atoms[key]["edge"][0], atoms[key]["edge"][2]) for key in b_ids} + if any((row["edges"][0][0], row["edges"][1][2]) in b_answers for row in trains): + raise ValueError("A composition label directly teaches a B head-answer pair") + train_operations = {operation(row) for row in trains} + trained_first = {row["atom_ids"][0] for row in trains} + trained_second = {row["atom_ids"][1] for row in trains} + for row in trains + evaluations: + if not set(row["atom_ids"]) <= set(atoms): + raise ValueError("Missing required atomic knowledge") + if [atoms[key]["edge"] for key in row["atom_ids"]] != row["edges"]: + raise ValueError("Atom IDs disagree with the real evidence chain") + for row in evaluations: + role = "".join("A" if key in a_ids else "B" for key in row["atom_ids"]) + if role != row["sequential_role"]: + raise ValueError("Incorrect sequential role") + if operation(row) not in train_operations: + raise ValueError("An evaluation operation was not trained on A") + if role[0] == "A" and row["atom_ids"][0] not in trained_first: + raise ValueError("An old first-hop fact lacks prior composition use") + if role[1] == "A" and row["atom_ids"][1] not in trained_second: + raise ValueError("An old second-hop fact lacks prior composition use") + if role == "BB" and not entities(row) <= a_entities: + raise ValueError("BB contains an entity absent from A") + counts = Counter(row["sequential_role"] for row in evaluations) + return { + "passed": True, + "atomic_A": len(a_ids), + "atomic_B": len(b_ids), + "train_compositions": len(trains), + "evaluation_counts": dict(counts), + "bb_all_entities_seen_in_a": all( + entities(row) <= a_entities for row in evaluations if row["sequential_role"] == "BB" + ), + "b_fact_composition_training_overlap": 0, + "heldout_semantic_chain_training_overlap": 0, + "all_evaluation_a_facts_have_prior_role_experience": True, + "relation_pairs": { + role: dict( + Counter( + " -> ".join(operation(row)) + for row in evaluations + if row["sequential_role"] == role + ) + ) + for role in counts + }, + "bb_unique_atomic_facts": len( + { + key + for row in evaluations + if row["sequential_role"] == "BB" + for key in row["atom_ids"] + } + ), + } diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/sequential_transfer.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/sequential_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..865c5a8343f84fdb340f7961bca649b71b1efd76 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/sequential_transfer.py @@ -0,0 +1,629 @@ +"""Sequential acquisition of source-grounded facts in a complete Transformer. + +All histories train from random initialization. The joint history is an exact +permutation of the sequential-composition training-example multiset. Evaluation +questions, including every chain containing a B fact, never enter that stream. +""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch +from transformers import GPT2TokenizerFast + +from .grok_depth import utc +from .realworld_composition import ( + aggregate, + construct, + evaluate, + model_digest, + optimizer_for, + update, +) +from .realworld_composition_data import atomic_question, encode_example, sha256, write_json + +HISTORIES = ( + "sequential_composition", + "sequential_atomic", + "joint", + "sequential_composition_sham", +) + + +def validate_data(data): + """Reject leakage or a missing evaluation role before model allocation.""" + atoms = {row["id"]: row for row in data["atoms"]} + if len(atoms) != len(data["atoms"]): + raise ValueError("Duplicate atomic IDs") + a = {key for key, row in atoms.items() if row["subset"] == "A"} + b = {key for key, row in atoms.items() if row["subset"] == "B"} + if not a or not b or a | b != set(atoms): + raise ValueError("Every atom must belong to a nonempty A or B partition") + for key, expected in (("stage_a_atom_ids", a), ("stage_b_atom_ids", b)): + if key in data and set(data[key]) != expected: + raise ValueError(f"{key} differs from atomic subset fields") + train = data["train_compositions"] + evaluation = data["evaluation_compositions"] + train_ids = {row["id"] for row in train} + evaluation_ids = {row["id"] for row in evaluation} + if not train or train_ids & evaluation_ids: + raise ValueError("Training chains must be nonempty and held-out IDs disjoint") + if len(train_ids) != len(train) or len(evaluation_ids) != len(evaluation): + raise ValueError("Duplicate composition IDs") + if (train_ids | evaluation_ids) & set(atoms): + raise ValueError("Atom and composition IDs must be globally unique") + train_chains = {tuple(row["atom_ids"]) for row in train} + if any(not set(row["atom_ids"]) <= a for row in train): + raise ValueError("A training chain includes a held-out B fact") + roles = set() + for row in evaluation: + if len(row["atom_ids"]) != 2 or not set(row["atom_ids"]) <= set(atoms): + raise ValueError("Every chain needs exactly two known atomic IDs") + role = "".join(atoms[key]["subset"] for key in row["atom_ids"]) + if row.get("sequential_role") != role: + raise ValueError("Evaluation role does not match its constituent facts") + if tuple(row["atom_ids"]) in train_chains: + raise ValueError("Evaluation chain identity occurs in training") + roles.add(role) + if roles != {"AA", "BA", "AB", "BB"}: + raise ValueError("All four fixed evaluation roles must be nonempty") + return atoms + + +def _sample_cycles(ids, count, rng): + """Balanced random epochs, preserving every requested sample slot.""" + ids = np.asarray(ids, dtype=np.int32) + if count < 0 or not len(ids): + raise ValueError("Sampling requires a nonempty pool and nonnegative count") + if not count: + return np.empty(0, dtype=np.int32) + chunks = [rng.permutation(ids) for _ in range(math.ceil(count / len(ids)))] + return np.concatenate(chunks)[:count] + + +def training_plan(data, spec): + """Materialize deterministic example IDs; histories differ only as declared.""" + validate_data(data) + history = spec["history"] + if history not in HISTORIES: + raise ValueError(f"Unknown training history: {history}") + records = data["atoms"] + data["train_compositions"] + index = {row["id"]: i for i, row in enumerate(records)} + a = [index[row["id"]] for row in data["atoms"] if row["subset"] == "A"] + b = [index[row["id"]] for row in data["atoms"] if row["subset"] == "B"] + c = [index[row["id"]] for row in data["train_compositions"]] + batch = int(spec["batch_size"]) + sa, sb = int(spec["stage_a_steps"]), int(spec["stage_b_steps"]) + if batch < 2 or sa < 1 or sb < 1: + raise ValueError("Need batch>=2 and positive budgets in both stages") + rng = np.random.default_rng(spec["sampling_seed"]) + # Exactly half (rounded down) of A slots contain composition examples; + # exactly half of B slots contain genuinely new atomic examples. + ca = int(spec.get("stage_a_composition_per_batch", batch // 2)) + nb = int(spec.get("stage_b_new_per_batch", batch // 2)) + if not (0 < ca < batch and 0 < nb < batch): + raise ValueError("Both stage mixtures need positive constituent counts") + first = np.concatenate( + ( + _sample_cycles(a, sa * (batch - ca), rng).reshape(sa, batch - ca), + _sample_cycles(c, sa * ca, rng).reshape(sa, ca), + ), + axis=1, + ) + second = np.concatenate( + ( + _sample_cycles(a, sb * (batch - nb), rng).reshape(sb, batch - nb), + _sample_cycles(b, sb * nb, rng).reshape(sb, nb), + ), + axis=1, + ) + # Seeded replacement streams are generated for every history, so selecting + # a history cannot affect either the common A exposure or B sampling. + atomic_replacement = _sample_cycles(a, sa * ca, rng).reshape(sa, ca) + sham_replacement = _sample_cycles(a, sb * nb, rng).reshape(sb, nb) + if history == "sequential_atomic": + first[:, batch - ca :] = atomic_replacement + elif history == "sequential_composition_sham": + second[:, batch - nb :] = sham_replacement + plan = np.concatenate((first, second), axis=0) + if history == "joint": + plan = rng.permutation(plan.reshape(-1)).reshape(plan.shape) + return records, plan + + +def plan_manifest(records, plan, spec): + counts = np.bincount(plan.reshape(-1), minlength=len(records)) + return { + "history": spec["history"], + "shape": list(plan.shape), + "plan_sha256": hashlib.sha256(plan.tobytes()).hexdigest(), + "multiset_sha256": hashlib.sha256(counts.tobytes()).hexdigest(), + "examples": int(counts.sum()), + "supervised_tokens": sum( + int(n) * len(row["encoded"]["target"]) for row, n in zip(records, counts, strict=True) + ), + "input_tokens": sum( + int(n) * len(row["encoded"]["input"]) for row, n in zip(records, counts, strict=True) + ), + "counts": {row["id"]: int(n) for row, n in zip(records, counts, strict=True)}, + } + + +def learning_rate(spec, step): + """Same staged cosine by global update index for *all* histories.""" + boundary = spec["stage_a_steps"] + length = boundary if step <= boundary else spec["stage_b_steps"] + local = step if step <= boundary else step - boundary + warmup = min(spec.get("warmup_steps", 200), length) + peak = spec["learning_rate"] + if warmup and local <= warmup: + return peak * local / warmup + progress = (local - warmup) / max(1, length - warmup) + floor = spec.get("minimum_lr_fraction", 0.1) + return peak * (floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * progress))) + + +def evaluation_groups(data, full): + atoms = {row["id"]: row for row in data["atoms"]} + chains = {row["id"]: row for row in data["evaluation_compositions"]} + panels = data.get("panels", {}) + selected = ( + list(chains.values()) + if full + else [chains[key] for role in ("AA", "BA", "AB", "BB") for key in panels.get(role, [])] + ) + if not selected: + selected = list(chains.values()) + needed = {key for row in selected for key in row["atom_ids"]} + atom_ids = ( + set(atoms) + if full + else needed | set(panels.get("atomic_A", [])) | set(panels.get("atomic_B", [])) + ) + groups = { + "atomic_A": [row for key, row in atoms.items() if key in atom_ids and row["subset"] == "A"], + "atomic_B": [row for key, row in atoms.items() if key in atom_ids and row["subset"] == "B"], + "train_composition": data["train_compositions"] + if full + else [ + row + for row in data["train_compositions"] + if row["id"] in set(panels.get("train_composition", [])) + ], + } + for role in ("AA", "BA", "AB", "BB"): + groups[role] = [row for row in selected if row["sequential_role"] == role] + return groups + + +def evaluate_transfer(model, data, tokenizer, device, *, full=False, autonomous=False, batch=32): + groups = evaluation_groups(data, full) + metrics, predictions = {}, {} + for name, records in groups.items(): + metrics[name], predictions[name] = ( + evaluate(model, records, tokenizer, device, batch_size=batch) + if records + else (aggregate([]), []) + ) + lookup = {row["id"]: row for name in ("atomic_A", "atomic_B") for row in predictions[name]} + for role in ("AA", "BA", "AB", "BB"): + selected = groups[role] + correct = { + row["id"] for row in selected if all(lookup[key]["alias_em"] for key in row["atom_ids"]) + } + key = role + "_necessary_atoms_correct" + metrics[key] = aggregate([row for row in predictions[role] if row["id"] in correct]) + metrics[key]["coverage"] = len(correct) / len(selected) if selected else None + if not autonomous: + continue + calls, invalid = [], [] + for row in selected: + bridge = lookup[row["atom_ids"][0]]["prediction"] + question = atomic_question(bridge, row["edges"][1][1]) + try: + encoded = encode_example(tokenizer, question, row["answer"]) + except ValueError: + invalid.append(row) + continue + calls.append({**row, "encoded": encoded, "question": question, "bridge": bridge}) + _, raw = evaluate(model, calls, tokenizer, device, batch_size=batch) if calls else ({}, []) + for row, value in zip(calls, raw, strict=True): + value.update(bridge_prediction=row["bridge"], second_question=row["question"]) + raw.extend( + { + "id": row["id"], + "canonical_em": 0.0, + "alias_em": 0.0, + "unambiguous_alias_em": 0.0, + "f1": 0.0, + "nll": None, + "eos": False, + "truncated": True, + "invalid_generated_bridge_length": True, + } + for row in invalid + ) + predictions[role + "_autonomous"] = raw + metrics[role + "_autonomous"] = aggregate(raw) + metrics[role + "_autonomous"]["invalid_bridge_prompts"] = len(invalid) + return metrics, predictions + + +def _setup(spec, device): + torch.set_num_threads(spec.get("cpu_threads", 4)) + device = torch.device(device) + if device.type == "cuda": + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + data_path = Path(spec["data_file"]) + if sha256(data_path) != spec["data_sha256"]: + raise ValueError("Dataset hash differs from frozen spec") + data = json.loads(data_path.read_text()) + validate_data(data) + tokenizer = GPT2TokenizerFast.from_pretrained(spec["tokenizer"], local_files_only=True) + if len(tokenizer) != spec["model"]["vocab_size"]: + raise ValueError("Tokenizer vocabulary and model vocabulary differ") + model = construct(spec["model"], spec, device) + return data, tokenizer, model, device + + +def _sync(device): + if torch.device(device).type == "cuda": + torch.cuda.synchronize(device) + + +def save_checkpoint(path, model, optimizer, step, counts, counters, history, manifest): + path = Path(path) + temporary = path.with_suffix(".tmp") + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "counts": counts, + "counters": counters, + "history": history, + "plan_sha256": manifest["plan_sha256"], + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state() if next(model.parameters()).is_cuda else None, + }, + temporary, + ) + temporary.replace(path) + + +def restore_checkpoint(path, model, optimizer, manifest): + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + if checkpoint["plan_sha256"] != manifest["plan_sha256"]: + raise ValueError("Resume would change the frozen sampling plan") + model.load_state_dict(checkpoint["model"]) + optimizer.load_state_dict(checkpoint["optimizer"]) + torch.set_rng_state(checkpoint["cpu_rng"]) + if checkpoint["cuda_rng"] is not None: + torch.cuda.set_rng_state(checkpoint["cuda_rng"]) + return checkpoint + + +def run(spec, out, device): + """Train one frozen history; an independent audit finalizes completion.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + if json.loads((out / "run.json").read_text())["spec"] != spec: + raise ValueError("Completed run has a different experiment spec") + return json.loads((out / "complete.json").read_text()) + data, tokenizer, model, device = _setup(spec, device) + records, plan = training_plan(data, spec) + manifest = plan_manifest(records, plan, spec) + optimizer = optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + counts = np.zeros(len(records), dtype=np.int64) + counters = { + key: 0 + for key in ( + "examples", + "supervised_tokens", + "effective_input_tokens", + "executed_input_tokens", + "estimated_matmul_training_flops", + ) + } + counters.update(training_seconds=0.0, wall_seconds=0.0) + history, initial_step = [], 0 + if (out / "latest.pt").exists(): + previous = json.loads((out / "run.json").read_text()) + if previous["spec"] != spec: + raise ValueError("Refusing to resume under a changed experiment spec") + state = restore_checkpoint(out / "latest.pt", model, optimizer, manifest) + initial_step, counts, counters, history = ( + state["step"], + state["counts"], + state["counters"], + state["history"], + ) + metadata = {**previous, "pid": os.getpid(), "resumed_from_step": initial_step} + del state + else: + torch.manual_seed(spec.get("dropout_seed", spec["initialization"] + 1)) + metadata = { + "spec": spec, + "phase": spec.get("phase", "development"), + "model": spec["model"], + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else "cpu", + "initial_model_sha256": model_digest(model), + "parameters": sum(p.numel() for p in model.parameters()), + "world_sha256": spec["data_sha256"], + "dtype": "BF16 AMP; FP32 parameters/Adam", + "job_type": "sequential-transfer", + "tracking_group": spec.get("tracking_group"), + "created_utc": utc(), + "sampling_manifest": {key: value for key, value in manifest.items() if key != "counts"}, + } + write_json(out / "sampling-plan.json", manifest) + write_json(out / "run.json", metadata) + write_json(out / "learning.json", history) + nodes = set(spec.get("evaluation_nodes", [])) | {0, spec["stage_a_steps"], len(plan)} + wall_offset, started = counters["wall_seconds"], time.perf_counter() + loss = history[-1].get("loss") if history else None + latest_step = initial_step + for step in range(initial_step, len(plan) + 1): + if step > initial_step: + lr = learning_rate(spec, step) + for group in optimizer.param_groups: + group["lr"] = lr + ids = plan[step - 1] + selected = [records[i] for i in ids] + _sync(device) + began = time.perf_counter() + result = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id) + _sync(device) + counters["training_seconds"] += time.perf_counter() - began + loss = result["loss"] + np.add.at(counts, ids, 1) + counters["examples"] += len(ids) + counters["supervised_tokens"] += sum(len(row["encoded"]["target"]) for row in selected) + for key in ( + "effective_input_tokens", + "executed_input_tokens", + "estimated_matmul_training_flops", + ): + counters[key] += result[key] + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + if step % spec.get("status_interval", 50) == 0: + write_json( + out / "status.json", + { + "state": "training", + "step": step, + "target_step": len(plan), + "loss": loss, + "pid": os.getpid(), + **counters, + "updated_utc": utc(), + }, + ) + if step in nodes and not any(row["step"] == step for row in history): + endpoint = step in {spec["stage_a_steps"], len(plan)} + metrics, raw = evaluate_transfer( + model, + data, + tokenizer, + device, + full=endpoint, + autonomous=endpoint, + batch=spec.get("evaluation_batch_size", 32), + ) + write_json(out / f"predictions-{step:07d}.json", raw) + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + exposure = {} + for name, subset in (("A", "A"), ("B", "B"), ("composition", None)): + indices = [ + i + for i, row in enumerate(records) + if (row.get("subset") == subset if subset else i >= len(data["atoms"])) + ] + exposure[name] = float(counts[indices].mean()) if indices else 0.0 + history.append( + { + "step": step, + "stage": "A" if step <= spec["stage_a_steps"] else "B", + "condition": spec["history"], + "metrics": metrics, + "loss": loss, + "learning_rate": learning_rate(spec, max(step, 1)), + "exposures": exposure, + "atomic_A_epochs": exposure["A"], + "atomic_B_epochs": exposure["B"], + "atomic_epochs": float(counts[: len(data["atoms"])].mean()), + "composition_epochs": exposure["composition"], + **counters, + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "created_utc": utc(), + } + ) + write_json(out / "learning.json", history) + if step == spec["stage_a_steps"]: + save_checkpoint( + out / "stage-a.pt", model, optimizer, step, counts, counters, history, manifest + ) + save_checkpoint( + out / "latest.pt", model, optimizer, step, counts, counters, history, manifest + ) + latest_step = step + print(json.dumps({"step": step, "loss": loss, "metrics": metrics}), flush=True) + elif step > initial_step and step % spec.get("checkpoint_interval", 500) == 0: + save_checkpoint( + out / "latest.pt", model, optimizer, step, counts, counters, history, manifest + ) + latest_step = step + if latest_step != len(plan): + save_checkpoint( + out / "latest.pt", model, optimizer, len(plan), counts, counters, history, manifest + ) + final = next(row for row in history if row["step"] == len(plan)) + write_json(out / "endpoint.json", final["metrics"]) + result = { + "state": "trained_pending_independent_reload", + "step": len(plan), + "pid": os.getpid(), + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + "plan_sha256": manifest["plan_sha256"], + **counters, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + return result + + +def audit(out, device): + """Reload in a separate process and reproduce the full generated endpoint.""" + out = Path(out) + metadata = json.loads((out / "run.json").read_text()) + trained = json.loads((out / "trained.json").read_text()) + if trained["pid"] == os.getpid(): + raise ValueError("Endpoint audit requires a different process") + if sha256(out / "latest.pt") != trained["checkpoint_sha256"]: + raise ValueError("Checkpoint differs from recorded endpoint") + spec = metadata["spec"] + data, tokenizer, model, device = _setup(spec, device) + state = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + if state["step"] != trained["step"] or model_digest(model) != trained["model_sha256"]: + raise ValueError("Loaded model or update count differs") + records, plan = training_plan(data, spec) + manifest = plan_manifest(records, plan, spec) + if manifest["plan_sha256"] != trained["plan_sha256"]: + raise ValueError("Sampling plan changed") + expected_counts = np.bincount(plan.reshape(-1), minlength=len(records)) + if not np.array_equal(state["counts"], expected_counts): + raise ValueError("Observed example exposures differ from frozen plan") + metrics, raw = evaluate_transfer( + model, + data, + tokenizer, + device, + full=True, + autonomous=True, + batch=spec.get("evaluation_batch_size", 32), + ) + expected_raw = json.loads((out / f"predictions-{trained['step']:07d}.json").read_text()) + if raw != expected_raw or metrics != json.loads((out / "endpoint.json").read_text()): + raise AssertionError("Independent endpoint generations/scores failed exact reproduction") + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "model_sha256": trained["model_sha256"], + "checkpoint_sha256": trained["checkpoint_sha256"], + "predictions_recomputed": sum(map(len, raw.values())), + "exposures_exact": True, + "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": trained["step"], "independently_reloaded": True}, + ) + return result + + +def preflight(spec, out, device): + """Actual updates, fresh-model reload and exact optimizer/RNG continuation.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + data, tokenizer, model, device = _setup(spec, device) + records, plan = training_plan(data, spec) + optimizer = optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + times, losses = [], [] + for ids in plan[:8]: + _sync(device) + started = time.perf_counter() + result = update( + model, optimizer, [records[i] for i in ids], spec, device, tokenizer.eos_token_id + ) + _sync(device) + times.append(time.perf_counter() - started) + losses.append(result["loss"]) + saved_model = copy.deepcopy(model.state_dict()) + saved_optimizer = copy.deepcopy(optimizer.state_dict()) + cpu_rng = torch.get_rng_state() + gpu_rng = torch.cuda.get_rng_state() if device.type == "cuda" else None + # The next update uses the exact same record order, Adam moments and RNG. + next_records = [records[i] for i in plan[min(8, len(plan) - 1)]] + update(model, optimizer, next_records, spec, device, tokenizer.eos_token_id) + expected = model_digest(model) + restored = construct(spec["model"], spec, device) + restored.load_state_dict(saved_model) + restored_optimizer = optimizer_for(restored, spec["learning_rate"], spec["weight_decay"]) + restored_optimizer.load_state_dict(saved_optimizer) + torch.set_rng_state(cpu_rng) + if gpu_rng is not None: + torch.cuda.set_rng_state(gpu_rng) + update(restored, restored_optimizer, next_records, spec, device, tokenizer.eos_token_id) + if model_digest(restored) != expected: + raise AssertionError("Preflight optimizer/RNG continuation failed exact reproduction") + generation_metrics, predictions = evaluate( + restored, next_records[:4], tokenizer, device, batch_size=4 + ) + result = { + "passed": True, + "updates": len(times), + "continuation_check_updates": 2, + "optimizer_rng_restore_exact": True, + "generated_predictions": predictions, + "generation_metrics": generation_metrics, + "losses": losses, + "seconds_per_update_after_warmup": sum(times[2:]) / max(1, len(times) - 2), + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "parameters": sum(p.numel() for p in model.parameters()), + "created_utc": utc(), + } + write_json(out / "preflight.json", result) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path) + parser.add_argument("--run") + parser.add_argument("--out", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--audit", action="store_true") + parser.add_argument("--preflight", action="store_true") + args = parser.parse_args() + if args.audit: + if not args.out: + parser.error("--audit requires --out") + result = audit(args.out, args.device) + else: + if not args.config or not args.run: + parser.error("Training/preflight requires --config and --run") + config = json.loads(args.config.read_text()) + selected = next(row for row in config["runs"] if row["name"] == args.run) + spec = {**config.get("defaults", {}), **selected} + out = args.out or Path(config["results_root"]) / "runs" / args.run + result = (preflight if args.preflight else run)(spec, out, args.device) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/shared_cache.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/shared_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf5aec02ab0270e60a6c41882c24bdd4b3d34cc --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/shared_cache.py @@ -0,0 +1,133 @@ +"""First-recursion KV access in the historical closed-book LoopGPT backbone. + +Only attention access changes. Each layer retains its own first-pass K/V; +embeddings, normalization, residuals, MLPs and supervision are unchanged. +""" + +from __future__ import annotations + +from numbers import Integral + +import torch +from torch.nn import functional as F + +from .grok_loop_model import LoopGPT, _positive_integer +from .grok_loop_model import flops as ordinary_flops +from .latent_scaling import construct as ordinary_construct + +ARMS = ("local", "shared_full", "shared_window", "shared_detached") + + +class SharedCacheGPT(LoopGPT): + def __init__(self, config, repeats, dropout=0.0, arm="shared_full", window=2): + if arm not in ARMS: + raise ValueError(f"Unknown memory arm: {arm}") + if isinstance(window, bool) or not isinstance(window, Integral) or window < 0: + raise ValueError("window counts nonnegative preceding local positions") + super().__init__(config, repeats, dropout, "legacy_unique") + self.memory_arm, self.window = arm, int(window) + self.disable_shared = False + self.duplicate_current = False # engineering identity control only + positions = torch.arange(config.context) + causal = positions[None, :] <= positions[:, None] + local = causal & (positions[None, :] >= positions[:, None] - self.window) + self.register_buffer("shared_causal_mask", causal, persistent=False) + self.register_buffer("local_window_mask", local, persistent=False) + + def forward(self, tokens, positions=None, repeats=None): + count = self.repeats if repeats is None else _positive_integer(repeats, "repeats") + if self.memory_arm == "local" or count == 1: + return super().forward(tokens, positions, count) + length = tokens.shape[1] + if length > self.config.context: + raise ValueError("Input exceeds mask context") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(length, device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + causal = self.shared_causal_mask[:length, :length] + local_mask = ( + self.local_window_mask[:length, :length] + if self.memory_arm == "shared_window" + else causal + ) + joined_mask = torch.cat((causal, local_mask), dim=-1) + shared = [] + for recursion in range(count): + for layer, block in enumerate(self.blocks): + z = block.ln1(x) + batch, size, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, size, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + q, k, v = (t.transpose(1, 2) for t in (q, k, v)) + if recursion == 0: + shared.append((k, v)) + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=p) + elif self.disable_shared: + y = F.scaled_dot_product_attention(q, k, v, attn_mask=local_mask, dropout_p=p) + else: + first_k, first_v = (k, v) if self.duplicate_current else shared[layer] + if self.memory_arm == "shared_detached": + first_k, first_v = first_k.detach(), first_v.detach() + y = F.scaled_dot_product_attention( + q, + torch.cat((first_k, k), dim=-2), + torch.cat((first_v, v), dim=-2), + attn_mask=joined_mask, + dropout_p=p, + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, size, 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 construct(spec, device): + if "memory_arm" not in spec: + return ordinary_construct(spec, device) + reference = ordinary_construct(spec, "cpu") + torch.manual_seed(spec["initialization"]) + return SharedCacheGPT( + reference.config, spec["repeats"], spec["dropout"], spec["memory_arm"], spec["window"] + ).to(device) + + +def executed_flops(config, repeats, batch, sequence, arm, output_positions=9, backward=True): + """Executed dense matmul shapes, including masked work; excludes elementwise ops. + + Concatenated attention has twice the key dimension, even for a small window. + The ordinary estimate counts QK and AV over a square sequence, not only the + visible causal entries. Backward follows the historical 3-forward convention. + Detachment changes true backward work; this common estimate is approximate. + """ + base = ordinary_flops(config, repeats, batch, sequence, output_positions, backward) + if arm == "local": + return base + extra = 4 * batch * config.layers * (repeats - 1) * sequence**2 * config.width + return base + extra * (3 if backward else 1) + + +def cached_positions(layers, repeats, length, arm, window): + """Analytic decoding history slots, not measured training allocation.""" + if arm in {"local", "shared_full", "shared_detached"}: + return layers * repeats * length + return layers * (length + (repeats - 1) * min(window, length)) + + +def install_training_adapter(spec): + """Reuse the unchanged historical sampler, optimizer, scorer and audit.""" + from . import latent_scaling as latent + + latent.construct = construct + latent.flops = lambda config, repeats, batch, sequence, output_positions=9, backward=True: ( + executed_flops( + config, repeats, batch, sequence, spec["memory_arm"], output_positions, backward + ) + ) + return latent diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/small_lm_composition.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/small_lm_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..f7bc9b1ea8e7d825eb5f27c33bb4d7e38bb7bcc1 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/small_lm_composition.py @@ -0,0 +1,543 @@ +"""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 hashlib +import json +import math +import re +import shutil +import time +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +import transformers +from 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) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/small_lm_followup.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/small_lm_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..4c986ea475b4f0abe83ea3d0411a049344ac0e08 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/small_lm_followup.py @@ -0,0 +1,558 @@ +"""Small full-Qwen development: matched rehearsal, pairing, and factual updates.""" + +from __future__ import annotations + +import copy +import itertools +import json +import math +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import transformers +from 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) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/storage_composition.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/storage_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..094211c26edecbed2a534bad16c84c42b2cdebd0 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/storage_composition.py @@ -0,0 +1,424 @@ +"""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, and +all non-padding next tokens contribute to the training loss. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .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 result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/storage_frontier.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/storage_frontier.py new file mode 100644 index 0000000000000000000000000000000000000000..db36e560aed8b173bb72c836b3d02dc8381bbcc5 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/storage_frontier.py @@ -0,0 +1,262 @@ +"""Stable training and nested fact loads in ordinary GPT/Loop architectures. + +The historical storage_composition implementation is reused without changing its +frozen sources, truth, tokenizer, architecture or full-generation score. +""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .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 result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/text_loss_source.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/text_loss_source.py new file mode 100644 index 0000000000000000000000000000000000000000..6f9377848d4673a2937273cf26a33f8e859874d0 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/text_loss_source.py @@ -0,0 +1,256 @@ +"""Factorial loss-source interventions on an unchanged text-pretraining stream.""" + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, write_json +from .grok_loop_model import flops +from .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"), + ), + ) diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/text_pretrain.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/text_pretrain.py new file mode 100644 index 0000000000000000000000000000000000000000..2682a0925a00e0e8b0eef3781521830d891ef9d7 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/text_pretrain.py @@ -0,0 +1,401 @@ +"""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 in +supervision. This is controlled template-language pretraining, not a pretrained +natural-language model or a replication of the original bioS scale. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, GraphStep, make_optimizer, write_json +from .grok_loop_model import LoopGPT, flops + +WORDS = [ + "", + "", + "", + "'s", + "is", + ".", + "This", + "record", + "has", + "no", + "additional", + "fact", + "here", + "mentor", + "advisor", + "coach", + "supervisor", + "city", + "district", + "region", + "campus", +] +LENGTH = 26 +PAD, EOS, BOS = 0, 1, 2 + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def vocabulary(spec): + return ( + WORDS + + [f"Person{i:03d}" for i in range(spec["heads_n"])] + + [f"Expert{i:03d}" for i in range(spec["bridges_n"])] + + [f"Place{i:03d}" for i in range(spec["tails_n"])] + ) + + +def atomic_sentence(row): + h, r, t = map(int, row) + return [BOS, h, 3, r, 4, t, 5, EOS] + + +def composite_sentence(row): + h, r1, _b, r2, t = map(int, row) + return [BOS, h, 3, r1, 3, r2, 4, t, 5, EOS] + + +def pack_documents(documents, groups): + """Reset positions per record in every arm; BOS is an exogenous boundary. + + All remaining next-token targets, including names, relations and EOS, are + supervised. The next record's BOS and padding are never prediction targets. + """ + seq, positions, segments = [], [], [] + for doc, group in zip(documents, groups, strict=True): + seq.extend(doc) + positions.extend(range(len(doc))) + segments.extend([group] * len(doc)) + if len(seq) > LENGTH: + raise ValueError("Record exceeds fixed context") + n = len(seq) + seq += [PAD] * (LENGTH - n) + positions += [0] * (LENGTH - n) + segments += list(range(100, 100 + LENGTH - n)) + labels = np.asarray(seq[1:], dtype=np.int64) + labels[(labels == BOS) | (labels == PAD)] = -100 + seg = np.asarray(segments[:-1]) + mask = (seg[:, None] == seg[None, :]) & np.tri(LENGTH - 1, dtype=bool) + return ( + np.asarray(seq[:-1], dtype=np.int64), + np.asarray(positions[:-1], dtype=np.int64), + mask[None], + labels, + ) + + +def build_world(spec): + """One supplied world; complete head-tail pairs held out before rendering.""" + rng = np.random.default_rng(spec["world"]) + hn, bn, tn = spec["heads_n"], spec["bridges_n"], spec["tails_n"] + hs = np.arange(len(WORDS), len(WORDS) + hn) + bs = np.arange(hs[-1] + 1, hs[-1] + 1 + bn) + ts = np.arange(bs[-1] + 1, bs[-1] + 1 + tn) + first = np.array([(h, r, rng.choice(bs)) for h in hs for r in range(13, 17)]) + second = np.array([(b, r, rng.choice(ts)) for b in bs for r in range(17, 21)]) + lookup = {(int(h), int(r)): int(t) for h, r, t in second} + paths = np.array( + [(h, r1, b, r2, lookup[int(b), r2]) for h, r1, b in first for r2 in range(17, 21)], + dtype=np.int64, + ) + reserved = rng.random((hn, tn)) < spec["holdout_fraction"] + held = reserved[paths[:, 0] - hs[0], paths[:, 4] - ts[0]] + background = paths[:, 0] < hs[0] + hn // 2 + groups = { + "atomic_first": first, + "atomic_second": second, + "background_train": paths[background & ~held], + "background_test": paths[background & held], + "target_train": paths[~background & ~held], + "target_test": paths[~background & held], + } + for key, rows in groups.items(): + if not len(rows): + raise ValueError(f"Empty world stratum {key}; do not silently reroll") + train_pairs = {tuple(r[[0, 4]]) for r in paths[~held]} + test_pairs = {tuple(r[[0, 4]]) for r in paths[held]} + assert not train_pairs & test_pairs + # Typed atomics can never expose a head and a tail together. + assert not set(first[:, 0]) & set(second[:, 0]) + assert not set(first[:, 2]) & set(second[:, 2]) + groups["atomic"] = np.concatenate([first, second]) + groups["all_paths"] = paths + return groups + + +def training_table(world, arm): + if arm not in ("P0", "P1", "P2"): + raise ValueError(arm) + packed = [pack_documents([atomic_sentence(r)], [0]) for r in world["atomic"]] + base_end = len(packed) + packed.extend(pack_documents([composite_sentence(r)], [0]) for r in world["background_train"]) + background_end = len(packed) + neutral = [BOS, 6, 7, 8, 9, 10, 11, 12, 5, EOS] + for row in world["target_train"]: + h, r1, b, r2, t = row + third = composite_sentence(row) if arm == "P2" else neutral + packed.append( + pack_documents( + [atomic_sentence([h, r1, b]), atomic_sentence([b, r2, t]), third], + [0, 1, 2] if arm == "P0" else [0, 0, 2], + ) + ) + table = tuple(np.stack([row[i] for row in packed]) for i in range(4)) + return table, [0, base_end, background_end, len(packed)] + + +class TextGPT(LoopGPT): + def forward(self, tokens, position_ids=None, attention_mask=None, patch=None, cache=None): + if position_ids is None: + position_ids = torch.arange(tokens.shape[1], device=tokens.device)[None] + p = self.dropout if self.training else 0.0 + x = F.dropout(self.token(tokens) + self.position(position_ids), p=p, training=self.training) + for layer, block in enumerate(self.iter_blocks()): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=attention_mask, + is_causal=attention_mask is None, + dropout_p=p, + ) + attn = F.dropout( + a.proj(y.transpose(1, 2).reshape(batch, length, width)), p=p, training=self.training + ) + mlp = F.dropout(block.mlp(block.ln2(x + attn)), p=p, training=self.training) + if cache is not None: + cache[layer] = { + "attention": attn.detach(), + "mlp": mlp.detach(), + "full": (x + attn + mlp).detach(), + } + if patch is not None and layer == patch["layer"]: + pos, value, component = patch["position"], patch["value"], patch["component"] + if component == "full": + x = x + attn + mlp + x = x.clone() + x[:, pos] = value + continue + if component == "attention": + attn = attn.clone() + attn[:, pos] = value + elif component == "mlp": + mlp = mlp.clone() + mlp[:, pos] = value + else: + raise ValueError(component) + x = x + attn + mlp + return F.linear(self.ln_final(x), self.token.weight) + + +class TextGraphStep(GraphStep): + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, positions, mask, labels = (t[self.index] for t in self.table) + logits = self.model(x, position_ids=positions, attention_mask=mask) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def construct(spec, device): + torch.manual_seed(spec["initialization"]) + cfg = ModelConfig( + vocab_size=len(vocabulary(spec)), + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=LENGTH, + ) + return TextGPT(cfg, repeats=spec["repeats"], dropout=spec["dropout"]).to(device) + + +@torch.inference_mode() +def evaluate(model, rows, device, composite=False, patch=None, batch_size=256): + model.eval() + encode = composite_sentence if composite else atomic_sentence + prompts = np.asarray([encode(r)[:-3] for r in rows], dtype=np.int64) + answers, stops, probs = [], [], [] + for start in range(0, len(rows), batch_size): + x = torch.as_tensor(prompts[start : start + batch_size], device=device) + intervention = ( + None if patch is None else dict(patch, value=patch["value"][start : start + batch_size]) + ) + logits = model(x, patch=intervention)[:, -1] + target = torch.as_tensor(rows[start : start + batch_size, -1], device=device) + probs.extend(logits.softmax(-1).gather(1, target[:, None]).squeeze(1).tolist()) + prediction = logits.argmax(-1) + answers.extend(prediction.tolist()) + x = torch.cat([x, prediction[:, None]], dim=1) + period = model(x, patch=intervention)[:, -1].argmax(-1) + x = torch.cat([x, period[:, None]], dim=1) + eos = model(x, patch=intervention)[:, -1].argmax(-1) + stops.extend(torch.stack([period, eos], dim=1).tolist()) + ans, stop, probability = np.asarray(answers), np.asarray(stops), np.asarray(probs) + correct = ans == rows[:, -1] + full = correct & (stop[:, 0] == 5) & (stop[:, 1] == EOS) + return dict( + n=len(rows), + answer_accuracy=float(correct.mean()), + accuracy=float(full.mean()), + answer_probability=float(probability.mean()), + ), dict(answer=ans, stops=stop, probability=probability, target=rows[:, -1]) + + +def run(spec, output, device): + output = Path(output) + if (output / "complete.json").exists(): + return json.loads((output / "complete.json").read_text()) + output.mkdir(parents=True, exist_ok=True) + lock = json.loads(Path(spec["source_lock"]).read_text()) + for file, expected in lock["sources"].items(): + assert sha(file) == expected, file + assert lock["config_sha256"] == sha(spec["config_path"]) + torch.set_num_threads(2) + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_per_process_memory_fraction(0.08, device) + world = build_world(spec) + cpu_table, bounds = training_table(world, spec["arm"]) + np.savez_compressed(output / "world.npz", **world) + np.savez_compressed( + output / "training-table.npz", + **{k: v for k, v in zip(("tokens", "positions", "mask", "labels"), cpu_table, strict=True)}, + ) + write_json(output / "spec.json", spec) + write_json(output / "vocabulary.json", vocabulary(spec)) + model = construct(spec, device) + opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"]) + table = tuple(torch.as_tensor(t, device=device) for t in cpu_table) + streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(3)] + latest = output / "latest.pt" + start, elapsed, histories = 0, 0.0, [] + if latest.exists(): + state = torch.load(latest, map_location=device, weights_only=False) + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + for stream, saved in zip(streams, state["streams"], strict=True): + stream.load_state_dict(saved) + start, elapsed, histories = state["step"], state["seconds"], state["histories"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + counts = spec["batch_parts"] + supervised_per_step = sum(n * tokens for n, tokens in zip(counts, [7, 9, 23], strict=True)) + step_flops = flops( + model.config, spec["repeats"], sum(counts), LENGTH - 1, output_positions=LENGTH - 1 + ) + + def checkpoint(step, seconds): + metrics, predictions = {}, {} + for split in ( + "atomic", + "background_train", + "background_test", + "target_train", + "target_test", + ): + metrics[split], preds = evaluate( + model, world[split], device, composite=split != "atomic" + ) + predictions.update({split + "_" + k: v for k, v in preds.items()}) + atomic_ok = predictions["atomic_answer"] == world["atomic"][:, -1] + knowledge = { + (int(h), int(r)): bool(ok) + for (h, r, _t), ok in zip(world["atomic"], atomic_ok, strict=True) + } + eligible = np.array( + [ + knowledge[int(h), int(r1)] and knowledge[int(b), int(r2)] + for h, r1, b, r2, _t in world["target_test"] + ] + ) + target_ok = predictions["target_test_answer"] == world["target_test"][:, -1] + metrics["target_atomic_correct"] = dict( + n=int(eligible.sum()), + coverage=float(eligible.mean()), + answer_accuracy=float(target_ok[eligible].mean()) if eligible.any() else None, + ) + record = dict( + step=step, + seconds=seconds, + supervised_tokens=step * supervised_per_step, + estimated_flops=step * step_flops, + metrics=metrics, + ) + histories.append(record) + np.savez_compressed(output / f"predictions-{step:06d}.npz", **predictions) + write_json(output / "learning.json", histories) + model.train() + state = dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + step=step, + seconds=seconds, + histories=histories, + spec=spec, + streams=[s.state_dict() for s in streams], + cpu_rng=torch.get_rng_state(), + cuda_rng=torch.cuda.get_rng_state(device), + ) + tmp = output / "latest.tmp" + torch.save(state, tmp) + tmp.replace(latest) + if step in spec["weight_nodes"]: + torch.save( + dict(model=state["model"], step=step, spec=spec), output / f"weights-{step:06d}.pt" + ) + print(json.dumps(dict(run=output.name, **record)), flush=True) + + if start == 0: + checkpoint(0, elapsed) + model.train() + graph = TextGraphStep(model, opt, table, sum(counts)) + tick = time.monotonic() + for step in range(start + 1, spec["steps"] + 1): + idx = np.concatenate( + [ + stream.take(n) + offset + for stream, n, offset in zip(streams, counts, bounds[:-1], strict=True) + ] + ) + for group in opt.param_groups: + group["lr"].fill_(spec["lr"] * min(1.0, step / spec["warmup"])) + graph(torch.as_tensor(idx, device=device)) + if step in spec["nodes"]: + torch.cuda.synchronize() + elapsed += time.monotonic() - tick + checkpoint(step, elapsed) + tick = time.monotonic() + result = dict( + status="complete", + final=histories[-1], + parameters=sum(p.numel() for p in model.parameters()), + source_lock_sha256=sha(spec["source_lock"]), + world_sha256=sha(output / "world.npz"), + peak_memory_bytes=torch.cuda.max_memory_allocated(device), + ) + write_json(output / "complete.json", result) + return result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/text_structure.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/text_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c74f97848144e288267dedd2df039a1f8c1a52 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/text_structure.py @@ -0,0 +1,432 @@ +"""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 and +bridges are disjoint from background; answer values are deliberately shared. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .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 result diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/twohop_depth.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/twohop_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..19b9a4b76eadef68acf7603b8434567145244311 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/twohop_depth.py @@ -0,0 +1,362 @@ +"""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 contextlib +import hashlib +import json +import os +from pathlib import Path + +import numpy as np +import torch +from 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}" diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/write_target_editing.py b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/write_target_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f395611444591e300b48869efe3a3840054e582 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/src/llm_memory_editability/write_target_editing.py @@ -0,0 +1,628 @@ +"""Does writing the same new entity into the early state restore its later use? + +The three objectives use identical atomic labels, replay, shared-MLP parameters, +and update counts. Only the objective weights change. Graph-only strict first-hop +cases and the full-pool evaluator are inherited from the established edit study. +No downstream relation or composed answer is passed to the optimizer. +""" + +from __future__ import annotations + +import copy +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import interface_editing as ie +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import data_digest, file_hash + +OBJECTIVES = ("final_ce", "early_ce", "early_ce_align") + + +def objective(model, target_batch, replay_batch, parent_log, kind, spec): + """All early supervision is the exact entity label of the atomic answer.""" + if kind not in OBJECTIVES: + raise ValueError(f"Unknown writing objective: {kind}") + if parent_log.requires_grad: + raise ValueError("Replay reference must be detached") + logits, state = model(target_batch[0], positions=target_batch[1], return_bridge=True) + final_ce = F.cross_entropy(logits.flatten(0, 1), target_batch[2].flatten()) + entity = target_batch[2][:, 0] + early_logits = F.linear(model.ln_final(state), model.token.weight) + early_ce = F.cross_entropy(early_logits, entity) + canonical = model.token(entity).detach() + alignment = ( + (F.normalize(state, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1).mean() + ) + replay = model(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + kl = F.kl_div(replay, parent_log, log_target=True, reduction="none").sum(-1).mean() + # Compute the same graph in all arms, including the zero-weight components. + early_weight = spec.get("early_weight", 0.3) if kind != "final_ce" else 0.0 + alignment_weight = spec.get("alignment_weight", 0.3) if kind == "early_ce_align" else 0.0 + loss = ( + final_ce + + spec.get("replay_weight", 1.0) * kl + + early_weight * early_ce + + alignment_weight * alignment + ) + return loss, { + "final_ce": final_ce, + "replay_kl": kl, + "early_ce": early_ce, + "alignment": alignment, + } + + +@torch.no_grad() +def early_readout(model, case, device): + """Read the causal first-block state without fitting a probe or using D.""" + rows = np.asarray([case["new_fact"]], dtype=np.int64) + tokens, positions, _ = ie.answer_batch(rows, device) + _, state = model(tokens, positions=positions, return_bridge=True) + logits = F.linear(model.ln_final(state), model.token.weight) + old, new = int(case["old_fact"][2]), int(case["new_fact"][2]) + probabilities = logits.softmax(-1) + old_embedding = model.token.weight[old : old + 1] + new_embedding = model.token.weight[new : new + 1] + prediction = int(logits.argmax(-1).item()) + metrics = { + "n": 1, + "new_entity_accuracy": float(prediction == new), + "old_entity_accuracy": float(prediction == old), + "new_entity_probability": float(probabilities[0, new]), + "old_entity_probability": float(probabilities[0, old]), + "new_entity_nll": float(-logits.log_softmax(-1)[0, new]), + "new_direction_cosine": float(F.cosine_similarity(state, new_embedding).item()), + "old_direction_cosine": float(F.cosine_similarity(state, old_embedding).item()), + "state_norm": float(state.norm()), + } + raw = { + "early__state": state.cpu().numpy(), + "early__entity_prediction": np.asarray([prediction], dtype=np.int64), + "early__entity_probabilities": probabilities[:, [old, new]].cpu().numpy(), + } + return metrics, raw + + +def selected_cases(parent_spec, spec): + cases, qualification = ie.graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780101), + per_cell=spec.get("per_cell", 4), + replay_n=spec.get("replay_n", 32), + ) + cases = [case for case in cases if case["role"] == "first" and case["stratum"] == "strict"] + if "case_ids" in spec: + wanted = set(spec["case_ids"]) + if not wanted or not wanted <= {case["case_id"] for case in cases}: + raise ValueError("Only graph-selected strict first-hop cases are permitted") + cases = [case for case in cases if case["case_id"] in wanted] + return cases, qualification + + +def _evaluate(model, case, tasks, originals, parent_correct, device, batch_size): + metrics, raw = ie.evaluate_case( + model, tasks, originals, parent_correct, "first", device, batch_size + ) + metrics["early"], early_raw = early_readout(model, case, device) + raw.update(early_raw) + return metrics, raw + + +def _restore(parent, tensor_path, scope="mlp", block_index=0): + state = torch.load(tensor_path, map_location="cpu", weights_only=True) + model = copy.deepcopy(parent).eval() + selected = ie.editable_parameters(model, scope, block_index) + if set(state["edited_tensors"]) != set(selected): + raise AssertionError("Saved edit changes an unexpected parameter scope") + merged = model.state_dict() + merged.update(state["edited_tensors"]) + model.load_state_dict(merged) + if model_digest(model) != state["model_sha256"]: + raise AssertionError("Saved exact tensors do not reconstruct their model digest") + return model + + +def diagnostics(existing_dir, out, device="cuda:0"): + """Reload existing final-answer edits before any new training; never mutate them.""" + device, existing_dir, out = ie._configure(device), Path(existing_dir), Path(out) + if out.exists(): + raise FileExistsError(out) + manifest = json.loads((existing_dir / "run.json").read_text()) + spec = manifest["spec"] + parent, _world, parent_spec = ie._load_parent(spec["parent_dir"], device) + if model_digest(parent) != manifest["parent_model_sha256"]: + raise AssertionError("Historical parent digest changed") + cases, _ = ie.graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + cases = {c["case_id"]: c for c in cases if c["role"] == "first" and c["stratum"] == "strict"} + records = [] + summary = json.loads((existing_dir / "complete.json").read_text()) + for branch in summary["branches"]: + if branch["case_id"] not in cases: + continue + case = cases[branch["case_id"]] + directory = existing_dir / branch["path"] + parent_metrics, parent_raw = early_readout(parent, case, device) + for record in json.loads((directory / "learning.json").read_text()): + tensor_path = directory / f"tensors-{record['step']:06d}.pt" + model = _restore(parent, tensor_path, spec.get("parameter_scope", "mlp")) + if model_digest(model) != record["model_sha256"]: + raise AssertionError("Historical trajectory digest changed") + values, raw = early_readout(model, case, device) + values["state_delta_l2"] = float( + np.linalg.norm(raw["early__state"] - parent_raw["early__state"]) + ) + records.append( + { + "case_id": case["case_id"], + "arm": branch["arm"], + "step": record["step"], + "early": values, + "parent_early": parent_metrics, + "E_new": record["metrics"]["E_new"], + "E_old": record["metrics"]["E_old"], + "tensor_file_sha256": file_hash(tensor_path), + "model_sha256": model_digest(model), + } + ) + if not records: + raise ValueError("Historical run contains no strict first-hop edit nodes") + result = { + "status": "complete", + "training_updates": 0, + "existing_dir": str(existing_dir), + "parent_model_sha256": manifest["parent_model_sha256"], + "source_run_sha256": file_hash(existing_dir / "run.json"), + "records": records, + "finished_utc": utc(), + } + write_json(out, result) + return result + + +def _validate(spec): + nodes = spec.get("nodes", [0, 32, 128, 512]) + if not nodes or nodes[0] != 0 or nodes != sorted(set(nodes)) or nodes[-1] <= 0: + raise ValueError("Nodes must increase from zero to a positive fixed endpoint") + kinds = spec.get("objectives", list(OBJECTIVES)) + if not kinds or len(set(kinds)) != len(kinds) or set(kinds) - set(OBJECTIVES): + raise ValueError("Unknown or repeated objective") + if spec.get("lr", 1e-5) <= 0 or "learning_rates" in spec: + raise ValueError("Use one fixed positive learning rate") + if spec.get("parameter_scope", "mlp") != "mlp" or spec.get("block_index", 0) != 0: + raise ValueError("This comparison edits the same first shared MLP only") + return nodes, kinds + + +def run(spec, out, device="cuda:0"): + """One parent and one or more fixed objectives, each with all edit/sham pairs.""" + device, out = ie._configure(device), Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite an existing attempt: {out}") + nodes, kinds = _validate(spec) + parent, world, parent_spec = ie._load_parent(spec["parent_dir"], device) + parent_file_hash = file_hash(Path(spec["parent_dir"]) / "model.pt") + if spec.get("parent_checkpoint_sha256", parent_file_hash) != parent_file_hash: + raise AssertionError("Preselected parent checkpoint hash changed") + if parent_spec["layers"] != 1 or parent_spec["repeats"] != 2: + raise ValueError("Use the established two-execution shared GPT parent") + parent_hash = model_digest(parent) + cases, qualification = selected_cases(parent_spec, spec) + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "cases": cases, + "qualification": qualification, + "case_sha256": ie._hash_json(cases), + "parent_file_sha256": parent_file_hash, + "parent_model_sha256": parent_hash, + "initial_model_sha256": parent_hash, + "world_sha256": data_digest(world), + "created_utc": utc(), + "dtype": "float32", + "allow_tf32": True, + "pid": os.getpid(), + "gpu": device.index if device.type == "cuda" else None, + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else "CPU", + "branches": len(cases) * len(kinds) * 2, + "planned_updates": len(cases) * len(kinds) * 2 * nodes[-1], + "learning_step_unit": "evaluation_index", + "status_step_unit": "completed_branches", + "early_state": "first executed block at first relation token, position 3", + "scope_warning": "Selected MLP parameters are shared across both executions", + "supervision": "same atomic entity label; no second relation or composed answer", + } + write_json(out / "run.json", manifest) + write_json(out / "learning.json", []) + write_json(out / "cases.json", cases) + np.savez_compressed(out / "world.npz", **world) + if spec.get("diagnostic_existing_dir"): + diagnostic = diagnostics( + spec["diagnostic_existing_dir"], out / "existing-edit-diagnostics.json", device + ) + if diagnostic["parent_model_sha256"] != parent_hash: + raise AssertionError("Diagnostic and training parent must be identical") + root_learning, summaries = [], [] + completed_updates, early_presentations, alignment_presentations = 0, 0, 0 + started, training_seconds = time.perf_counter(), 0.0 + batch_size = spec.get("eval_batch_size", 512) + for case in cases: + tasks, originals = ie.case_tasks(world, case) + masks = ie._parent_masks(parent, originals, device, batch_size) + parent_metrics, parent_raw = _evaluate( + parent, case, tasks, originals, masks, device, batch_size + ) + case_out = out / case["case_id"] + case_out.mkdir() + write_json(case_out / "parent-metrics.json", parent_metrics) + np.savez_compressed(case_out / "parent-predictions.npz", **parent_raw) + np.savez_compressed(case_out / "tasks.npz", **tasks) + replay = ie.answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + reference = parent(replay[0], positions=replay[1]).log_softmax(-1).detach() + for kind in kinds: + for arm in ("edit", "sham"): + directory = case_out / f"{kind}-{arm}" + directory.mkdir() + model = copy.deepcopy(parent).eval() + selected = ie.editable_parameters(model) + parameters = dict(model.named_parameters()) + optimizer = torch.optim.Adam( + [parameters[n] for n in selected], lr=spec.get("lr", 1e-5) + ) + target_name = "E_new" if arm == "edit" else "E_old" + target = ie.answer_batch(tasks[target_name], device) + write_json( + directory / "run.json", + { + "case_id": case["case_id"], + "objective": kind, + "arm": arm, + "editable_parameters": selected, + "parent_model_sha256": parent_hash, + "target_batch_sha256": ie._batch_hash(target), + "replay_batch_sha256": ie._batch_hash(replay), + "parent_reference_sha256": ie._batch_hash((reference,)), + "optimizer": "Adam, fresh state, zero weight decay", + "sampling": "same fixed full replay batch every update; no dropout", + "nodes": nodes, + }, + ) + history, losses, step = [], [], 0 + for node in nodes: + if device.type == "cuda": + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, components = objective(model, target, replay, reference, kind, spec) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite loss at {case['case_id']}/{step}") + loss.backward() + norm = torch.nn.utils.clip_grad_norm_( + [parameters[n] for n in selected], spec.get("clip_norm", 1.0) + ) + optimizer.step() + step += 1 + losses.append( + { + "step": step, + "loss": float(loss.detach()), + "gradient_norm": float(norm), + **{key: float(value.detach()) for key, value in components.items()}, + } + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + metrics, predictions = _evaluate( + model, case, tasks, originals, masks, device, batch_size + ) + digest = model_digest(model) + record = { + "step": step, + "model_sha256": digest, + "metrics": metrics, + "loss": losses[-1] if losses else None, + } + history.append(record) + write_json(directory / "learning.json", history) + write_json(directory / "losses.json", losses) + np.savez_compressed(directory / f"predictions-{step:06d}.npz", **predictions) + torch.save( + { + "edited_tensors": { + n: parameters[n].detach().cpu().clone() for n in selected + }, + "model_sha256": digest, + "step": step, + }, + directory / f"tensors-{step:06d}.pt", + ) + updates = completed_updates + step + root_learning.append( + { + "step": len(root_learning), + "branch_step": step, + "optimizer_updates": updates, + "case_id": case["case_id"], + "condition": kind, + "arm": arm, + "metrics": metrics, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": updates * (1 + len(tasks["R_atomic"])), + "target_supervised_tokens": updates * 3, + "replay_distillation_positions": updates * len(tasks["R_atomic"]) * 3, + "early_target_presentations": early_presentations + + step * (kind != "final_ce"), + "alignment_target_presentations": alignment_presentations + + step * (kind == "early_ce_align"), + } + ) + write_json(out / "learning.json", root_learning) + write_json( + out / "status.json", + { + "state": "running", + "step": len(summaries), + "optimizer_updates": updates, + "budget": manifest["branches"], + "case_id": case["case_id"], + "objective": kind, + "arm": arm, + }, + ) + print( + json.dumps( + { + "case": case["case_id"], + "objective": kind, + "arm": arm, + "step": step, + "E": metrics[target_name]["accuracy"], + "early_new": metrics["early"]["new_entity_accuracy"], + "D": metrics["D_first_strict"]["accuracy"], + } + ), + flush=True, + ) + changed = [ + n + for n, value in model.state_dict().items() + if not torch.equal(value, parent.state_dict()[n]) + ] + if set(changed) - set(selected) or model_digest(parent) != parent_hash: + raise AssertionError("A frozen parameter or the parent changed") + complete = { + "case_id": case["case_id"], + "role": "first", + "stratum": "strict", + "objective": kind, + "arm": arm, + "path": str(directory.relative_to(out)), + "metrics": metrics, + "steps": step, + "changed_tensors": changed, + "parent_model_sha256": parent_hash, + "final_model_sha256": digest, + "delta_l2": float( + torch.sqrt( + sum( + (parameters[n] - dict(parent.named_parameters())[n]).square().sum() + for n in selected + ) + ).detach() + ), + "tensor_file_sha256": file_hash(directory / f"tensors-{step:06d}.pt"), + } + write_json(directory / "complete.json", complete) + summaries.append(complete) + completed_updates += step + early_presentations += step * (kind != "final_ce") + alignment_presentations += step * (kind == "early_ce_align") + result = { + "status": "complete", + "branches": summaries, + "updates": completed_updates, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "finished_utc": utc(), + "case_sha256": manifest["case_sha256"], + } + write_json(out / "complete.json", result) + write_json( + out / "status.json", + { + "state": "complete", + "step": len(summaries), + "optimizer_updates": completed_updates, + "budget": manifest["branches"], + }, + ) + return result + + +def audit(out, device="cuda:0"): + """Independently reconstruct every branch/node and compare stored predictions.""" + device, out = ie._configure(device), Path(out) + manifest = json.loads((out / "run.json").read_text()) + spec = manifest["spec"] + nodes, kinds = _validate(spec) + parent, world, parent_spec = ie._load_parent(spec["parent_dir"], device) + if ( + model_digest(parent) != manifest["parent_model_sha256"] + or file_hash(Path(spec["parent_dir"]) / "model.pt") != manifest["parent_file_sha256"] + ): + raise AssertionError("Parent changed") + cases, qualification = selected_cases(parent_spec, spec) + if ( + cases != manifest["cases"] + or qualification != manifest["qualification"] + or data_digest(world) != manifest["world_sha256"] + ): + raise AssertionError("Graph cases or world changed") + result = json.loads((out / "complete.json").read_text()) + branches = result["branches"] + expected = [ + (case["case_id"], kind, arm) for case in cases for kind in kinds for arm in ("edit", "sham") + ] + if [(b["case_id"], b["objective"], b["arm"]) for b in branches] != expected: + raise AssertionError("Incomplete paired objective matrix") + learning = json.loads((out / "learning.json").read_text()) + if len(learning) != len(expected) * len(nodes) or [r["step"] for r in learning] != list( + range(len(learning)) + ): + raise AssertionError("Root evaluation indices changed") + early_count, alignment_count = 0, 0 + for index, row in enumerate(learning): + branch_index, node_index = divmod(index, len(nodes)) + case_id, kind, arm = expected[branch_index] + node = nodes[node_index] + updates = branch_index * nodes[-1] + node + if (row["case_id"], row["condition"], row["arm"], row["branch_step"]) != ( + case_id, + kind, + arm, + node, + ): + raise AssertionError("Root branch ordering changed") + wanted = { + "optimizer_updates": updates, + "target_supervised_tokens": updates * 3, + "replay_distillation_positions": updates * spec.get("replay_n", 32) * 3, + "early_target_presentations": early_count + node * (kind != "final_ce"), + "alignment_target_presentations": alignment_count + node * (kind == "early_ce_align"), + } + if any(row[key] != value for key, value in wanted.items()): + raise AssertionError("Optimizer or exposure accounting changed") + if node_index == len(nodes) - 1: + early_count += node * (kind != "final_ce") + alignment_count += node * (kind == "early_ce_align") + checked, max_error = 0, 0.0 + batch_size = spec.get("eval_batch_size", 512) + for case in cases: + tasks, originals = ie.case_tasks(world, case) + masks = ie._parent_masks(parent, originals, device, batch_size) + replay = ie.answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + reference = parent(replay[0], positions=replay[1]).log_softmax(-1) + for branch in branches: + if branch["case_id"] != case["case_id"]: + continue + directory = out / branch["path"] + branch_spec = json.loads((directory / "run.json").read_text()) + target = ie.answer_batch(tasks["E_new" if branch["arm"] == "edit" else "E_old"], device) + hashes = { + "target_batch_sha256": ie._batch_hash(target), + "replay_batch_sha256": ie._batch_hash(replay), + "parent_reference_sha256": ie._batch_hash((reference,)), + } + if any(branch_spec[key] != value for key, value in hashes.items()): + raise AssertionError("Supervision or replay provenance changed") + history = json.loads((directory / "learning.json").read_text()) + if [r["step"] for r in history] != nodes: + raise AssertionError("Saved node matrix incomplete") + if ( + branch["metrics"] != history[-1]["metrics"] + or branch["final_model_sha256"] != history[-1]["model_sha256"] + ): + raise AssertionError("Final summary differs from audited trajectory") + if file_hash(directory / f"tensors-{nodes[-1]:06d}.pt") != branch["tensor_file_sha256"]: + raise AssertionError("Final tensor hash changed") + for record in history: + model = _restore(parent, directory / f"tensors-{record['step']:06d}.pt") + if model_digest(model) != record["model_sha256"]: + raise AssertionError("Recorded model digest changed") + metrics, raw = _evaluate(model, case, tasks, originals, masks, device, batch_size) + with np.load(directory / f"predictions-{record['step']:06d}.npz") as saved: + if set(saved.files) != set(raw): + raise AssertionError("Prediction keys changed") + for name, values in raw.items(): + if values.dtype.kind == "f": + np.testing.assert_allclose(values, saved[name], rtol=1e-5, atol=1e-5) + if values.size: + max_error = max( + max_error, float(np.max(np.abs(values - saved[name]))) + ) + else: + np.testing.assert_array_equal(values, saved[name]) + for name, values in metrics.items(): + for key, value in values.items(): + expected_value = record["metrics"][name][key] + if isinstance(value, float): + np.testing.assert_allclose(value, expected_value, rtol=1e-5, atol=1e-5) + elif value != expected_value: + raise AssertionError(f"Metric changed: {name}/{key}") + checked += 1 + result = { + "passed": True, + "nodes": checked, + "max_float_error": max_error, + "case_sha256": manifest["case_sha256"], + "finished_utc": utc(), + } + write_json(out / "audit.json", result) + return result + + +def development_decision(run_dirs): + """Operational calibration reads only E and independent atomic retention. + + This is an admissibility check for the fixed recipe, not selection using + downstream propagation. Early readout success is recorded, not an exclusion. + """ + records, observed = [], set() + for directory in map(Path, run_dirs): + manifest = json.loads((directory / "run.json").read_text()) + if manifest["spec"].get("phase") not in {"development", "engineering"}: + raise ValueError("Calibration may read development runs only") + if json.loads((directory / "audit.json").read_text()).get("passed") is not True: + raise ValueError("Calibration requires independent reload audit") + result = json.loads((directory / "complete.json").read_text()) + for branch in result["branches"]: + observed.add(branch["objective"]) + metrics = branch["metrics"] + target = "E_new" if branch["arm"] == "edit" else "E_old" + records.append( + { + "run": str(directory), + "case_id": branch["case_id"], + "objective": branch["objective"], + "arm": branch["arm"], + "target_accuracy": metrics[target]["accuracy"], + "U_atomic_accuracy": metrics["U_atomic"]["accuracy"], + "necessary_atomic_accuracy": metrics["necessary_atomic"]["accuracy"], + "early_target_accuracy": metrics["early"][ + "new_entity_accuracy" if branch["arm"] == "edit" else "old_entity_accuracy" + ], + } + ) + if observed != set(OBJECTIVES): + raise ValueError("Calibration requires all three objectives") + passed = bool(records) and all( + r["target_accuracy"] == 1 + and r["U_atomic_accuracy"] >= 0.95 + and r["necessary_atomic_accuracy"] >= 0.95 + for r in records + ) + return { + "operational_gate_passed": passed, + "decision_rule": "Every edit/sham E=1; U_atomic and necessary_atomic >=.95; no D access", + "configuration_search": False, + "records": records, + "created_utc": utc(), + } diff --git a/docs/development-artifacts/write-target-confirmation-v1/source/tests/test_write_target_editing.py b/docs/development-artifacts/write-target-confirmation-v1/source/tests/test_write_target_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..3283013d46bb219faecc1c36baf780b77d526df0 --- /dev/null +++ b/docs/development-artifacts/write-target-confirmation-v1/source/tests/test_write_target_editing.py @@ -0,0 +1,200 @@ +"""Same-label, causal-state and exact-reload contracts of the write comparison.""" + +import copy +import json + +import numpy as np +import pytest +import torch + +from llm_memory_editability import interface_editing as ie +from llm_memory_editability import write_target_editing as wt +from llm_memory_editability.latent_scaling import build_world, model_digest +from llm_memory_editability.representation_alignment import new_model + + +def small_spec(): + return dict( + world=771001, + initialization=772001, + stream_seed=773001, + heads_n=32, + bridges_n=32, + tails_n=16, + familiar_n=8, + strict_n=4, + anchor_n=4, + holdout_fraction=0.25, + low_extra="anchors", + composition_count=32, + width=16, + heads=2, + layers=1, + repeats=2, + dropout=0.0, + ) + + +def setup_case(): + torch.set_num_threads(1) + spec = small_spec() + model = new_model(spec, "cpu").eval() + cases, _ = wt.selected_cases(spec, {"per_cell": 1, "replay_n": 4}) + case = cases[0] + tasks, _ = ie.case_tasks(build_world(spec), case) + target = ie.answer_batch(tasks["E_new"], "cpu") + replay = ie.answer_batch(tasks["R_atomic"], "cpu") + with torch.no_grad(): + reference = model(replay[0], positions=replay[1]).log_softmax(-1) + return model, case, tasks, target, replay, reference + + +def test_final_baseline_loss_and_gradients_identical_to_existing_editor(): + model, _case, _tasks, target, replay, reference = setup_case() + baseline = copy.deepcopy(model) + loss, _ = wt.objective(model, target, replay, reference, "final_ce", {}) + old_loss, _, _ = ie.edit_objective(baseline, target, replay, reference) + loss.backward() + old_loss.backward() + torch.testing.assert_close(loss, old_loss, atol=0, rtol=0) + for p, q in zip(model.parameters(), baseline.parameters(), strict=True): + torch.testing.assert_close(p.grad, q.grad, atol=1e-7, rtol=1e-5) + + +def test_added_supervision_is_same_entity_and_early_state_cannot_see_it(): + model, case, _tasks, target, replay, reference = setup_case() + old_target = ie.answer_batch(np.asarray([case["old_fact"]]), "cpu") + _, new_state = model(target[0], return_bridge=True) + _, old_state = model(old_target[0], return_bridge=True) + torch.testing.assert_close(new_state, old_state, atol=0, rtol=0) + labels = target[2][:, 0] + assert labels.tolist() == [case["new_fact"][2]] + parts = [] + for kind in wt.OBJECTIVES: + loss, components = wt.objective(model, target, replay, reference, kind, {}) + parts.append((loss, components)) + torch.testing.assert_close(parts[1][0] - parts[0][0], 0.3 * parts[0][1]["early_ce"]) + torch.testing.assert_close(parts[2][0] - parts[1][0], 0.3 * parts[0][1]["alignment"]) + with pytest.raises(ValueError, match="detached"): + wt.objective(model, target, replay, reference.requires_grad_(), "early_ce", {}) + + +def test_same_shared_mlp_is_only_updated_scope(): + model, _case, _tasks, target, replay, reference = setup_case() + selected = ie.editable_parameters(model) + before = {key: value.clone() for key, value in model.state_dict().items()} + optimizer = torch.optim.Adam([p for p in model.parameters() if p.requires_grad], lr=1e-3) + loss, _ = wt.objective(model, target, replay, reference, "early_ce_align", {}) + loss.backward() + optimizer.step() + changed = { + key for key, value in model.state_dict().items() if not torch.equal(value, before[key]) + } + assert changed and changed <= set(selected) + assert model.token.weight.grad is None + + +def test_paired_matrix_exposure_accounting_and_independent_reload(tmp_path): + spec = small_spec() + model = new_model(spec, "cpu").eval() + parent_dir = tmp_path / "parent" + parent_dir.mkdir() + torch.save({"model": model.state_dict(), "spec": spec}, parent_dir / "model.pt") + out = tmp_path / "run" + result = wt.run( + { + "phase": "engineering", + "parent_dir": str(parent_dir), + "per_cell": 1, + "replay_n": 4, + "nodes": [0, 1], + }, + out, + "cpu", + ) + assert result["updates"] == 6 and len(result["branches"]) == 6 + assert {b["objective"] for b in result["branches"]} == set(wt.OBJECTIVES) + initial = model_digest(model) + for branch in result["branches"]: + history = json.loads((out / branch["path"] / "learning.json").read_text()) + assert history[0]["model_sha256"] == initial + assert branch["role"] == "first" and branch["stratum"] == "strict" + audit = wt.audit(out, "cpu") + assert audit["passed"] and audit["nodes"] == 12 and audit["max_float_error"] == 0 + decision = wt.development_decision([out]) + assert len(decision["records"]) == 6 + assert all(not any(key.startswith("D") for key in row) for row in decision["records"]) + learning_path = out / "learning.json" + learning = json.loads(learning_path.read_text()) + assert learning[-1]["early_target_presentations"] == 4 + assert learning[-1]["alignment_target_presentations"] == 2 + learning[-1]["early_target_presentations"] = 5 + learning_path.write_text(json.dumps(learning)) + with pytest.raises(AssertionError, match="exposure accounting"): + wt.audit(out, "cpu") + with pytest.raises(FileExistsError): + wt.run({}, out, "cpu") + + +def test_selection_uses_existing_strict_graph_cases_and_rejects_other_roles(): + spec = small_spec() + settings = {"candidate_seed": 15, "per_cell": 2, "replay_n": 4} + cases, _ = wt.selected_cases(spec, settings) + all_cases, _ = ie.graph_cases(spec, seed=15, per_cell=2, replay_n=4) + assert cases == [case for case in all_cases if case["case_id"].startswith("first_strict")] + with pytest.raises(ValueError, match="strict first-hop"): + wt.selected_cases(spec, {**settings, "case_ids": ["second_strict-00"]}) + + +def test_development_decision_is_invariant_to_all_downstream_scores(tmp_path): + directory = tmp_path / "development" + directory.mkdir() + (directory / "run.json").write_text(json.dumps({"spec": {"phase": "development"}})) + (directory / "audit.json").write_text(json.dumps({"passed": True})) + branches = [] + for kind in wt.OBJECTIVES: + for arm in ("edit", "sham"): + metrics = { + key: {"accuracy": 1.0} for key in ["E_new", "E_old", "U_atomic", "necessary_atomic"] + } + metrics["early"] = {"new_entity_accuracy": 1.0, "old_entity_accuracy": 1.0} + metrics["D_first_strict"] = {"accuracy": 0.0} + branches.append( + {"objective": kind, "arm": arm, "case_id": "first_strict-00", "metrics": metrics} + ) + (directory / "complete.json").write_text(json.dumps({"branches": branches})) + before = wt.development_decision([directory]) + for branch in branches: + branch["metrics"]["D_first_strict"] = {"accuracy": 1.0, "unexpected": "not consumed"} + (directory / "complete.json").write_text(json.dumps({"branches": branches})) + after = wt.development_decision([directory]) + assert before["records"] == after["records"] + assert before["operational_gate_passed"] and after["operational_gate_passed"] + + +def test_historical_diagnostics_reload_without_training_or_mutation(tmp_path): + spec = small_spec() + model = new_model(spec, "cpu").eval() + parent_dir = tmp_path / "parent" + parent_dir.mkdir() + torch.save({"model": model.state_dict(), "spec": spec}, parent_dir / "model.pt") + old_run = tmp_path / "existing-run" + ie.run( + { + "phase": "engineering", + "parent_dir": str(parent_dir), + "per_cell": 1, + "replay_n": 4, + "nodes": [0, 1], + "case_ids": ["first_strict-00"], + }, + old_run, + "cpu", + ) + before = {str(path): path.read_bytes() for path in old_run.rglob("*") if path.is_file()} + result = wt.diagnostics(old_run, tmp_path / "diagnostics.json", "cpu") + after = {str(path): path.read_bytes() for path in old_run.rglob("*") if path.is_file()} + assert before == after + assert result["training_updates"] == 0 + assert len(result["records"]) == 4 + assert all(row["early"]["state_delta_l2"] == 0 for row in result["records"] if row["step"] == 0) diff --git a/docs/development-artifacts/write-target-development-v1/execution-lock.json b/docs/development-artifacts/write-target-development-v1/execution-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..361344c3e8391d592a6a277dda0859c214cfbc69 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/execution-lock.json @@ -0,0 +1,3 @@ +{ + "config_sha256": "0a423e4bf917b952296e79582137f80c2bb3dd5afc9f7061c3ebd4738381d5e8" +} diff --git a/docs/development-artifacts/write-target-development-v1/frozen-config.json b/docs/development-artifacts/write-target-development-v1/frozen-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0809fb26af50cc0959811ea8bfc27e951c7eb235 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/frozen-config.json @@ -0,0 +1,266 @@ +{ + "batch": "write-target-development-v1", + "module": "write_target_editing", + "gpus": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "runtime": { + "docker_context": "lm-memory", + "docker_host": "unix:///run/docker-lm-memory/docker.sock", + "image": "sha256:a994f1a1886220693eb26b7ff201147fbd4b49477d335ab2707330cab771063f", + "python": "/opt/conda/bin/python", + "cpus": 4, + "memory": "24g", + "env": { + "PYTHONDONTWRITEBYTECODE": "1", + "XDG_CACHE_HOME": "/tmp/cache", + "TORCH_HOME": "/tmp/torch", + "TORCHINDUCTOR_CACHE_DIR": "/tmp/torchinductor", + "TRITON_CACHE_DIR": "/tmp/triton" + } + }, + "specs": [ + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "development-final_ce", + "phase": "development", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3", + "parent_checkpoint_sha256": "cb1e034f7174cc081d9802d27df7827f8aa8650927dd603be10fde07e4ed868d", + "candidate_seed": 780011, + "per_cell": 2, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-development-v1/runs/development-aligned_0.3-lr1e-05", + "tracking_group": "write-target-development-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "development-early_ce", + "phase": "development", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3", + "parent_checkpoint_sha256": "cb1e034f7174cc081d9802d27df7827f8aa8650927dd603be10fde07e4ed868d", + "candidate_seed": 780011, + "per_cell": 2, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-development-v1/runs/development-aligned_0.3-lr1e-05", + "tracking_group": "write-target-development-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "development-early_ce_align", + "phase": "development", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3", + "parent_checkpoint_sha256": "cb1e034f7174cc081d9802d27df7827f8aa8650927dd603be10fde07e4ed868d", + "candidate_seed": 780011, + "per_cell": 2, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-development-v1/runs/development-aligned_0.3-lr1e-05", + "tracking_group": "write-target-development-v1" + } + ], + "additional_sources": [ + "tests/test_write_target_editing.py", + "scripts/run_write_target_editing.py", + "docs/development-artifacts/learning-use-20261007/protocol.md", + "configs/write-target-editing-v1.json" + ], + "frozen_utc": "2026-10-07T04:46:16.333497+00:00", + "repository": "/ossfs/workspace/llm-memory-editability", + "source_root": "/ossfs/workspace/llm-memory-editability/docs/development-artifacts/write-target-development-v1/source", + "results_root": "/ossfs/workspace/llm-memory-editability/results/write-target-development-v1", + "source": { + "configs/experiment-tracking-defaults.json": "41d4b73b9d2f57f71fe51dd8500275f2c9fb3476ec24a9eeee3a8deadb5ecaa2", + "configs/write-target-development-v1.json": "56ee6dad03eb80c390f4f79414d4c9c5fecded60ee133410efa9df6d32a78d4f", + "configs/write-target-editing-v1.json": "8b80ee56e0be7f647310638e0c25dd8d6c9335be6903298ad6a14fc0c80520cf", + "docs/development-artifacts/learning-use-20261007/protocol.md": "e11e865b4bc74d8216221d694244c300a6a7a7c99794ec0060174b44d5942263", + "scripts/execute_learning_use.py": "e3409fdc1f74905e4969798988854844c62e7d4580d719fbbac1be2f87886026", + "scripts/run_memory_interface_next.py": "f80f1cfdd3fa0a2685489c4101c234387745e66e46427208b523886eefe96bb3", + "scripts/run_write_target_editing.py": "22b7b12134b022a800c2b6e14a4a8dbae8c48b8655df3ed635c57da157f0c13b", + "src/llm_memory_editability/__init__.py": "84e6bb4a97b68f67f3256135c2b5fc35d9a83ceb04914a6cf3d38d926b015f7f", + "src/llm_memory_editability/__main__.py": "0af76e0612dd46d8097cd06d02bcd6220d89354be49910110a80b9942fdb71b3", + "src/llm_memory_editability/alignment_coverage.py": "152b868b836ff3ae18d8bb572ffe6ce956ea26edde1d283726b82215125736ff", + "src/llm_memory_editability/architecture_bridge.py": "777fe51d98b09275f487386660106e93c6c8b49e25b94e804510ed968c2df04c", + "src/llm_memory_editability/architecture_bridge_toy.py": "320d859c4d11b68299266d3f9bdb9a7e6867d635eb3d347827be082c60f0ffca", + "src/llm_memory_editability/bios_analysis.py": "41d836fc201b9ae4f1988e0cdda3dc3be4ebc3ca898ab2ff69ca8445212407ff", + "src/llm_memory_editability/bios_branch.py": "f5b0f0ae79f84d64e33862e40fffbc4bd9a8fd102414995e8a2d41560009c09d", + "src/llm_memory_editability/bios_capacity.py": "a9c306f0e326a8b97eccc4c0b404d45a3e3d8697186092ac562f645b4b370ba4", + "src/llm_memory_editability/bios_causal_paths.py": "10ea265743293fff64cc2201b7b49f5a22dd3bc3ff6a320f469948c233e65620", + "src/llm_memory_editability/bios_confirmation_stats.py": "e40f0347bd44e8602c18fc2fbee9647010d509d6f6dc7bc3c5cb8e98036e9c9b", + "src/llm_memory_editability/bios_context_control.py": "9205a7f8d25e0f1311d78c73638b97466f425886e62165166ba104f53050a40d", + "src/llm_memory_editability/bios_context_gradient.py": "8376dec9883b1d2c3ef06e5e04ad01fec6a1b9eceaa5cd74db02a79629bc536f", + "src/llm_memory_editability/bios_cross.py": "47b8f55adbe13d9bc6e1c5c9170cc95e382261ffb1f31980706ac95be03623bf", + "src/llm_memory_editability/bios_cross_continue.py": "e6fd3a86157566559ab0e0571fbefcc1a28f22ec7add66da2105ea81d63cdaf8", + "src/llm_memory_editability/bios_cross_scale.py": "a1be3c598403b72661b9b2df642b2b1236ae1df6fdf46d982d4d89d19487f658", + "src/llm_memory_editability/bios_cross_train.py": "0106cae29be447319be2e7f6f0e1f5b60cc6224282331906f43ebc65ab795f38", + "src/llm_memory_editability/bios_data.py": "d5568901f2042a6d89d447f47eddae9764eced0a9e71e3ea5adc0038a7e636d6", + "src/llm_memory_editability/bios_direction.py": "1240f83f5ee558101bbf6f808522fa6c37ffe09dc2296749bd5e685eff8aa41d", + "src/llm_memory_editability/bios_direction_cross.py": "66cf337b3a52508e82da6190ea01916662f1fe6fddef036844f9d1be2c179888", + "src/llm_memory_editability/bios_direction_formation.py": "e2b19c17c6b7ebb7a884782f2c7750a7c65b935c17694d4424d354c62d0a24ed", + "src/llm_memory_editability/bios_direction_refresh.py": "4f80060d4232ec3bf4fb5d99b0823d20ee759e088aeedf4bd49ab841357d0127", + "src/llm_memory_editability/bios_edit.py": "dbbbc01ce57acef79d5cc46bcd39e301b256fa1e8c9eff7b1ce5ece693f86f2f", + "src/llm_memory_editability/bios_followup.py": "06b4ffd3bbb65e2ff4df0f68e3fbf9f368257196bd4ef36eb1ffb0f7b15ee43b", + "src/llm_memory_editability/bios_measure.py": "8c275b658c5c99316a19e2328eb53952f26b8a858b591784509391780ead3267", + "src/llm_memory_editability/bios_mechanism_causal.py": "41aeed0ba09eba1b869e74dc29236aaa2abf142a596916dc06316754c7f21d8a", + "src/llm_memory_editability/bios_mechanism_causal_v2.py": "bc37408e458014e746c061c65b4672e67e30adee2b5a85b325a0282fbec00dfe", + "src/llm_memory_editability/bios_mechanism_edit.py": "ca9351ef08189c643a5b0a009af3e52b2578d5ae6265510f603cb78b229667dd", + "src/llm_memory_editability/bios_mechanism_interventions.py": "190c75e0a2779fe96936bff38d13a03e17e0dfd9faba3d2909ffc4a65265d96f", + "src/llm_memory_editability/bios_model.py": "99efb7feeeb15f33dd3f08174c1190f4aa470e3877d8ac6692b2d43fed4c5f4d", + "src/llm_memory_editability/bios_organization.py": "42f714473695da4c8543f666fd15a7eab7cef1e571429b25f81818b5505bd9d5", + "src/llm_memory_editability/bios_organization_train.py": "833426232b693495711e38101553e8bff370c837c722d76e7f9f5f2d2ed3cad6", + "src/llm_memory_editability/bios_original_data.py": "092689c2a05aad564ff8a7c6e1ac669d7e0475908e525766cf70922037cd2488", + "src/llm_memory_editability/bios_original_diagnostics.py": "6dd51ead7d16c1960740716fb73cb4409828666ac0332baae4c14730e39dd120", + "src/llm_memory_editability/bios_original_model.py": "8a52e58d343320ccce9e2f1b43674cc6765b840bd4feebed4813f78296ab29a9", + "src/llm_memory_editability/bios_original_report.py": "3483f72d479a861a4513f0a1a5dc7cbf53bcbace6a652d39f389b46ffb82286e", + "src/llm_memory_editability/bios_original_train.py": "86b2ef1be03223dff26bc7997b91143be81fb46fd29ab8650a9cde8a39eb6891", + "src/llm_memory_editability/bios_path_diagnostics.py": "7d95f31f9fa9099d6b05666b9a638f880aa83a88554d934c3ff05e86880d0f7e", + "src/llm_memory_editability/bios_path_minimal.py": "6fe8f0f6dd0950adfbbc5ad0524c1fe7e96b5c054d04338c046728535257a12e", + "src/llm_memory_editability/bios_path_transfer.py": "2a079c54c2778e9bcb8fb36ebea4f90c43ac7bb7135e6d61e8a91a250ae3a0e1", + "src/llm_memory_editability/bios_readout_control.py": "545260dcaeac15766857271cbe8646ed3f096e445215064790b4ad62b6425afe", + "src/llm_memory_editability/bios_relation_response.py": "56a21f6b7cd028aff011f99c9222518d0ef04bb803eda79a176e355cd735e0ca", + "src/llm_memory_editability/bios_shortcut_confirmation.py": "92306cd8d88e0329916b52d9aadb992db286fae4ad7cf72cd846ab2b9a22553e", + "src/llm_memory_editability/bios_shortcut_confirmation_sets.py": "063d867951c621f8110c5c2547458aa5039899d64e44c199b86a45b4661e142e", + "src/llm_memory_editability/bios_shortcut_control.py": "a9369b1a042ef644b231763e2b62ac2b12451c3a526ccf121fd476a72fa27325", + "src/llm_memory_editability/bios_shortcut_edit.py": "68c4980269249cbb1acf787fe5679bfad762460487f4a0cfc8e5e7f728ed8a68", + "src/llm_memory_editability/bios_shortcut_edit_v2.py": "55ee452c248a44e0abb50f9806a00772dc6e72b683541db6cc17ffd1ac18e899", + "src/llm_memory_editability/bios_shortcut_matched_edit.py": "a8bba1a538fe4b3d5739a2ec4d223daf54b3988d74a7aa86854af3971acd4123", + "src/llm_memory_editability/bios_train.py": "c1d84d38aa1853815075041535ae3fa9890f5cf1f9f5d9019136c79521033046", + "src/llm_memory_editability/bridge_reencoding.py": "128c02424642e2a479b8a439bd0342c89f77bf3befe3783a5fef9ebe01375ae5", + "src/llm_memory_editability/bridge_workspace.py": "fe8f98ff6348d879c0b3c6db6b24f18eaabe03692729f0b0c967fe8d3b5a124a", + "src/llm_memory_editability/capacity_controls.py": "dc0b6ea601216b0997c45271a2ce8e02121148f37c88649e68d8960c9a6f1796", + "src/llm_memory_editability/capacity_scaling.py": "5ee176e8d16e6e2a7becca7b89109712f940e21ead6b73a61a2ae974435e8678", + "src/llm_memory_editability/cli.py": "01c814b9644988be1bf2ab660b2010ad5e7beab99067116c2afb2b6957f9fd3b", + "src/llm_memory_editability/composition_curves.py": "520c4503f3d1525612432dd2c0b9fbf56d2e39ee5d6dff9f1484f19a7bfae8ec", + "src/llm_memory_editability/curve_tracking.py": "50cc8a1d652c44ef14d42b4a44cc800fb15e2ed72f4b83c4848870d76ab56fec", + "src/llm_memory_editability/depth_step.py": "bd69879d5ec6124c05ca28a62c2c2459734e5b4b17d32ae92005308de63b8279", + "src/llm_memory_editability/depth_step_edit_calibration.py": "2dd20b15ae1f92eb6f685eca1e914923ff349a6a94277cfd3a5a74ad9155b4b8", + "src/llm_memory_editability/depth_step_mechanism.py": "546ce23095e755959d8114ed2bcf3f3f0d70f4a8e38e5c9b5d98c7a28ea7c5a6", + "src/llm_memory_editability/experiment_tracking.py": "2afe9e767123bee16cf56f59c6c2953a100338ecf1f971945c4968a064551866", + "src/llm_memory_editability/experiments.py": "e575aceb2e3804956655d91710809818aec04c0b16a22edb441f5757629371d1", + "src/llm_memory_editability/grok_depth.py": "7d6d5af38a5dc4438b1e7ff44df8e833169d500f0d60d8933932bdb8822aca26", + "src/llm_memory_editability/grok_depth_bridge.py": "414a0dbf17c369ad6d15714c2c026aafc4fb12bb1813a3c056efe8035fe2773d", + "src/llm_memory_editability/grok_depth_data.py": "c1451a0647ef7c25567398efd63848dbb44fdf066d07718c02f7e556e6c8b94a", + "src/llm_memory_editability/grok_depth_extension.py": "f91923d3a7f154c7432e4763a0a90c0863eb75b7b35c8742838c9949795ab9f6", + "src/llm_memory_editability/grok_loop_data.py": "504de57da94618578cf792a3963f99e2dac587424d74ceae6b4c02c1d9680a8e", + "src/llm_memory_editability/grok_loop_mechanism.py": "aa11f58d3aa378741218eee29106b55da5601e1ff9bc3ac7e39ae55f26e613e2", + "src/llm_memory_editability/grok_loop_model.py": "07e84388997a1710e5c821e54cf6d23726e4289aab178347761e060851fea6cc", + "src/llm_memory_editability/grok_loop_same_bridge.py": "06538ab83312484367f84eefdf4944bddc8f3f45507dfcb96e005cb3017a3349", + "src/llm_memory_editability/grok_loop_same_bridge_eval.py": "dea9ebb3130a0d7816b11cd01ac6d105f09e3aa4a051857b71693da261632410", + "src/llm_memory_editability/grok_loop_supervision.py": "a24661453cb82764f81d631b9a1fb4642df0fc7181c5adf7cd6ac46960c9f9b7", + "src/llm_memory_editability/grok_loop_train.py": "4931606ee614aaadebbc3460c9ad9a86fbb12b5b6a1bbda9f3714f81424ff142", + "src/llm_memory_editability/grok_multihop.py": "67ed1f37b04fbef7031f208e5ca140aea1b6158adb64ec8b0fe12217eb53cdbc", + "src/llm_memory_editability/grok_multihop_data.py": "d417b4d39e70cfa4010a8cd737a362d8159d73c2377330b04bf471a5079da851", + "src/llm_memory_editability/grok_usage_data.py": "cfce0e5835665933ee1a1561ee681ffa6520c564be7e2292d9206399f86e7ced", + "src/llm_memory_editability/grok_usage_train.py": "5509ab6b2ad0c93e185cdfc211a7ee5afef45a5021a74aa8ce8bce520f694f70", + "src/llm_memory_editability/grokking_dynamics_mechanism.py": "713470c8432ea27c602208cf0625452859924b83f8c62927c81894070815432c", + "src/llm_memory_editability/grokking_reproduction.py": "7e3a89d96f6fef7bd4665ac46dd1acb6e7cb461c6878647ecc7c6f425ac31117", + "src/llm_memory_editability/hebbian_data.py": "f2f5458d624fc4a49781a557641de7388937e90fda846ab03f7e17a3f455dd0e", + "src/llm_memory_editability/hebbian_followup.py": "752244bd78c5b02ba1d37a276e0547a5ff5bcf7a47986d64642f0db36cc4f4aa", + "src/llm_memory_editability/hebbian_future.py": "9fa7d88102e5b79e91735f530fe98fdd2bba20fad146238cde4f6eb591cf7105", + "src/llm_memory_editability/hebbian_interface.py": "a1ead4b413aef8f3082dcd569318fd132b64ed1a1ddb0c0c3a3aae4686589198", + "src/llm_memory_editability/hebbian_learning.py": "3dd0317b90943a22aabb80dcdc24eb38199623c5fb84a67641c3acd5de6a650e", + "src/llm_memory_editability/hebbian_model.py": "e0413d8288a679800f3f7bafc8ef072a0d6d5b29fc49de417077569eec49cc3e", + "src/llm_memory_editability/hebbian_statistics.py": "8c3a37806bed9661666c55bcb7c727ab78d9f4b2a1b384323f6a33c51d0a11f8", + "src/llm_memory_editability/hebbian_train.py": "71ca785eafbe3438da45c4f5fa543a62424f1fd5176b04b317b0c78e7c96ecbf", + "src/llm_memory_editability/independent_alignment.py": "e1c7937e1afc8908cd1e16d766bc63316f336a6b296738369eb79c2c08e8976b", + "src/llm_memory_editability/interface_editing.py": "f5a9aba43a4c03373bfb59510322a9be800de53af4c3f87e967c7e03f648e0a0", + "src/llm_memory_editability/interface_tracking.py": "e93609e37b5b8cdd7751b2ed546dc4d24ada6864bf90224d60f2c30161f4d378", + "src/llm_memory_editability/knowledge_change.py": "6d090144a090d2bb53d7034f18af305e6dc50dceb488b6dc724046a47e35ed4b", + "src/llm_memory_editability/latent_scaling.py": "231050e859da58c52b9ea47d09fb5de91271df0d24cbab42dead3f911adc6119", + "src/llm_memory_editability/latent_support.py": "71e2483f8b5eb7e447594bf04def731add89f4cf140954fe87f793a69cb440a3", + "src/llm_memory_editability/low_rank.py": "e1ddb5714d492311a43af2d5fd3dd5f578d8144db0b3d860ca71e3b603d018e1", + "src/llm_memory_editability/memory_reuse.py": "e95814cd98de22adc54e458f0b5933f2c3f13a0640c0c71a841780a9b1b52e57", + "src/llm_memory_editability/multihop_scaling.py": "cbb60954b2738d17a1fce125087f87ee203fe98c5d462d14ad22ccff5790c7c6", + "src/llm_memory_editability/natural_composition_confirmation.py": "e13986431617be78b05db8c1f84f522f5cf4b6af7cd1b2e9d89345423be977e2", + "src/llm_memory_editability/natural_composition_confirmation_v2.py": "9bfa6540da812d4e6e2a21d2a8942dd73908269ce46aff15915b1782382dee75", + "src/llm_memory_editability/neural.py": "f0df4d9bbb47b1febf0baf76d53b58319e598b6bbb29d31abca575e2dd13e025", + "src/llm_memory_editability/neural_data.py": "8812cb49f223dff57ac2fbbeb8055aa3017302e0450c194ecc984eaefcc3596e", + "src/llm_memory_editability/neural_models.py": "c5ecb2fd69aa205a22688c95049750a7b8a0fd58b7c888a026252273b3af9091", + "src/llm_memory_editability/parametric_architecture.py": "b19ebaa377705f582fef367163312f74c2b3d2cc0451d8df03f47eff16e37a19", + "src/llm_memory_editability/parametric_architecture_train.py": "232d2a9e1c3db2023cafd15cf107e57a6f37fc8139d8c81a45e5a3121ef31c5d", + "src/llm_memory_editability/qwen_constraints.py": "1b371c02d59becde87d61f3e8db20c9064588ff1908be66c06570ed2c5b1ab6f", + "src/llm_memory_editability/qwen_path_learning.py": "d62080bf19605df02e9a140332c8981094a6e65b4c84a14b35734248e278a231", + "src/llm_memory_editability/qwen_path_train.py": "09f03b01179a2cef8d98f803f61cea7e48ce636259222e394b0248d6744aec9d", + "src/llm_memory_editability/realworld_composition.py": "323f1cdb0f3c25a085e95b6f85fe352b1a91274aa5b3bbaca4e0686fdb4510c0", + "src/llm_memory_editability/realworld_composition_data.py": "7208e0d0789f0287963b6e36d2646171e334f40ee365af13af79944f81e221be", + "src/llm_memory_editability/realworld_confirmation.py": "e160fa1ab79580281753752b3e8f39584e5f2ba6a3b5d27abece6c99a291efe2", + "src/llm_memory_editability/realworld_confirmation_analysis.py": "c8a89a57f913e034d7fd2c805fc4567900cd1c4881d5b66e8ac0f44deee75802", + "src/llm_memory_editability/recurrence_use.py": "144fb9561ead5dbce0589ee986b6452af31405b1ff4fd30aae36a72076b62469", + "src/llm_memory_editability/representation_alignment.py": "9794218f052a19019a5cb6427b84877a5174de3c0485bad441cdaed0ec7bd6b6", + "src/llm_memory_editability/residual_cache.py": "fc78dec3d8cbaedb0ae9b0ca07d7dc35220f54b4158fb800b5112a47c65f9806", + "src/llm_memory_editability/sequential_data.py": "2a1b32c9dff7a507691a6cc7f3820d5bcfc90d90d2da58e4b6a84f81aa6cb1a4", + "src/llm_memory_editability/sequential_transfer.py": "6eab684539f4ce84f44058d3988dcec055471ab6ae7cd9cf0ffc3fc0150e424d", + "src/llm_memory_editability/shared_cache.py": "c207467bf357887be09e8cf5235ffbcbbd93762eb201027fc666c032e6d187cd", + "src/llm_memory_editability/small_lm_composition.py": "93796eee05e305ad538a498f013463d6bcde4a03de720eff6f4bfedf903f21d1", + "src/llm_memory_editability/small_lm_followup.py": "90fdbbc5c1509d30e0e369c201b5caccac0c063636ad99101f9e3ea603ce7780", + "src/llm_memory_editability/storage_composition.py": "fa4d8b073ecb3ac69a3204ee446a4bc1ecf0c36f9d8dd1dcd0b6835c245e4c5a", + "src/llm_memory_editability/storage_frontier.py": "2a1adcbbb0439ed771e17090878b9f7c9861d2fef4544172a88c35bd037d4a22", + "src/llm_memory_editability/text_loss_source.py": "579471a04def8a11e9cc072fcb909d6e84c3b61c8d901d0d029e126f14a6d3fe", + "src/llm_memory_editability/text_pretrain.py": "cd777a56ba270d3c71ed3260f68501ee0685d4cc58a4f7b952719236adf874cb", + "src/llm_memory_editability/text_structure.py": "9c8e3f00b263a62d53868a6224830e702dcb4348c05d52cc438c1e37e365287d", + "src/llm_memory_editability/twohop_depth.py": "870ad9f1f3a3736b77b1b0781d25961803d9d2e1df9aed1c709a669691b76def", + "src/llm_memory_editability/write_target_editing.py": "5d56acecd4385553d19235cebc03cc16720db5e6304b765b30b094f96e46be55", + "tests/test_write_target_editing.py": "901496e3df00a2d26c4b2d151830349e48f020c67efb333c2323bd413831bee4" + }, + "input_files": { + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3/model.pt": "cb1e034f7174cc081d9802d27df7827f8aa8650927dd603be10fde07e4ed868d", + "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3/run.json": "797e1b5b983132d58d7bafbdd5599a0a9ce20fb34258986e55c8ad56defc8e34" + }, + "git_commit": "f298768b6843c8e53a0009b3adc0291eda5fea2c" +} diff --git a/docs/development-artifacts/write-target-development-v1/source/configs/experiment-tracking-defaults.json b/docs/development-artifacts/write-target-development-v1/source/configs/experiment-tracking-defaults.json new file mode 100644 index 0000000000000000000000000000000000000000..92273f717dfdee8e79a02a1a3fd47f874f8435f8 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/configs/experiment-tracking-defaults.json @@ -0,0 +1,11 @@ +{ + "enabled": true, + "provider": "wandb", + "sdk_version": "0.30.0", + "entity": "zhusq20", + "project": "llm-memory-editability", + "mode": "online", + "poll_seconds": 15, + "system_metrics": true, + "scope": "Future experiment batches; do not attach to existing frozen runs without a request" +} diff --git a/docs/development-artifacts/write-target-development-v1/source/configs/write-target-development-v1.json b/docs/development-artifacts/write-target-development-v1/source/configs/write-target-development-v1.json new file mode 100644 index 0000000000000000000000000000000000000000..133cf9fe32e5333cedca3b1d7afca4a6b80d6519 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/configs/write-target-development-v1.json @@ -0,0 +1,124 @@ +{ + "batch": "write-target-development-v1", + "module": "write_target_editing", + "gpus": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "runtime": { + "docker_context": "lm-memory", + "docker_host": "unix:///run/docker-lm-memory/docker.sock", + "image": "sha256:a994f1a1886220693eb26b7ff201147fbd4b49477d335ab2707330cab771063f", + "python": "/opt/conda/bin/python", + "cpus": 4, + "memory": "24g", + "env": { + "PYTHONDONTWRITEBYTECODE": "1", + "XDG_CACHE_HOME": "/tmp/cache", + "TORCH_HOME": "/tmp/torch", + "TORCHINDUCTOR_CACHE_DIR": "/tmp/torchinductor", + "TRITON_CACHE_DIR": "/tmp/triton" + } + }, + "specs": [ + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "development-final_ce", + "phase": "development", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3", + "parent_checkpoint_sha256": "cb1e034f7174cc081d9802d27df7827f8aa8650927dd603be10fde07e4ed868d", + "candidate_seed": 780011, + "per_cell": 2, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-development-v1/runs/development-aligned_0.3-lr1e-05", + "tracking_group": "write-target-development-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "development-early_ce", + "phase": "development", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3", + "parent_checkpoint_sha256": "cb1e034f7174cc081d9802d27df7827f8aa8650927dd603be10fde07e4ed868d", + "candidate_seed": 780011, + "per_cell": 2, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-development-v1/runs/development-aligned_0.3-lr1e-05", + "tracking_group": "write-target-development-v1" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "development-early_ce_align", + "phase": "development", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3", + "parent_checkpoint_sha256": "cb1e034f7174cc081d9802d27df7827f8aa8650927dd603be10fde07e4ed868d", + "candidate_seed": 780011, + "per_cell": 2, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-development-v1/runs/development-aligned_0.3-lr1e-05", + "tracking_group": "write-target-development-v1" + } + ], + "additional_sources": [ + "tests/test_write_target_editing.py", + "scripts/run_write_target_editing.py", + "docs/development-artifacts/learning-use-20261007/protocol.md", + "configs/write-target-editing-v1.json" + ] +} diff --git a/docs/development-artifacts/write-target-development-v1/source/configs/write-target-editing-v1.json b/docs/development-artifacts/write-target-development-v1/source/configs/write-target-editing-v1.json new file mode 100644 index 0000000000000000000000000000000000000000..6d47a4de3a7da49ba7bb49ef506c3dd6564b5ac4 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/configs/write-target-editing-v1.json @@ -0,0 +1,626 @@ +{ + "batch": "write-target-editing-v1", + "module": "write_target_editing", + "development_specs": [ + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "development-final_ce", + "phase": "development", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3", + "parent_checkpoint_sha256": "cb1e034f7174cc081d9802d27df7827f8aa8650927dd603be10fde07e4ed868d", + "candidate_seed": 780011, + "per_cell": 2, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-development-v1/runs/development-aligned_0.3-lr1e-05" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "development-early_ce", + "phase": "development", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3", + "parent_checkpoint_sha256": "cb1e034f7174cc081d9802d27df7827f8aa8650927dd603be10fde07e4ed868d", + "candidate_seed": 780011, + "per_cell": 2, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-development-v1/runs/development-aligned_0.3-lr1e-05" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "development-early_ce_align", + "phase": "development", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/development-v2-w770011-i771011-aligned_0.3", + "parent_checkpoint_sha256": "cb1e034f7174cc081d9802d27df7827f8aa8650927dd603be10fde07e4ed868d", + "candidate_seed": 780011, + "per_cell": 2, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-development-v1/runs/development-aligned_0.3-lr1e-05" + } + ], + "confirmation_specs": [ + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775101-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned", + "parent_checkpoint_sha256": "9ba1147aa9e3593d1d02bcdb85e414d997537b95741d1961dcc26fddaac8642f", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775101-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned", + "parent_checkpoint_sha256": "9ba1147aa9e3593d1d02bcdb85e414d997537b95741d1961dcc26fddaac8642f", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775101-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775101-aligned", + "parent_checkpoint_sha256": "9ba1147aa9e3593d1d02bcdb85e414d997537b95741d1961dcc26fddaac8642f", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775102-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned", + "parent_checkpoint_sha256": "4dc0b7662668de0c0f5d01a696bef70ce46916fe9a04e229a31a26a59710aad3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775102-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned", + "parent_checkpoint_sha256": "4dc0b7662668de0c0f5d01a696bef70ce46916fe9a04e229a31a26a59710aad3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774101-i775102-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774101-i775102-aligned", + "parent_checkpoint_sha256": "4dc0b7662668de0c0f5d01a696bef70ce46916fe9a04e229a31a26a59710aad3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774101-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775101-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned", + "parent_checkpoint_sha256": "9fc43fcc48b8d82d8b3d0780ad92905888185ac037372d186668a249abf19808", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775101-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned", + "parent_checkpoint_sha256": "9fc43fcc48b8d82d8b3d0780ad92905888185ac037372d186668a249abf19808", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775101-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775101-aligned", + "parent_checkpoint_sha256": "9fc43fcc48b8d82d8b3d0780ad92905888185ac037372d186668a249abf19808", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775102-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned", + "parent_checkpoint_sha256": "f2432dd48e266c85a91b19a6c1049555bc9067142d63155ba84d666bb8a469b7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775102-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned", + "parent_checkpoint_sha256": "f2432dd48e266c85a91b19a6c1049555bc9067142d63155ba84d666bb8a469b7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774102-i775102-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774102-i775102-aligned", + "parent_checkpoint_sha256": "f2432dd48e266c85a91b19a6c1049555bc9067142d63155ba84d666bb8a469b7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774102-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775101-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned", + "parent_checkpoint_sha256": "56845c38b7bd88a6358cb31c3f375ccd63bd7bcac38d0edd0ddb46bf388c28d7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775101-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned", + "parent_checkpoint_sha256": "56845c38b7bd88a6358cb31c3f375ccd63bd7bcac38d0edd0ddb46bf388c28d7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775101-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775101-aligned", + "parent_checkpoint_sha256": "56845c38b7bd88a6358cb31c3f375ccd63bd7bcac38d0edd0ddb46bf388c28d7", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775101-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775102-final_ce", + "phase": "confirmation", + "arm": "final_ce", + "objectives": [ + "final_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned", + "parent_checkpoint_sha256": "b3679fba3d439b50ed1ea89f94e1bea5366f6fa9540cb9af40da4beddf5161a3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775102-early_ce", + "phase": "confirmation", + "arm": "early_ce", + "objectives": [ + "early_ce" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned", + "parent_checkpoint_sha256": "b3679fba3d439b50ed1ea89f94e1bea5366f6fa9540cb9af40da4beddf5161a3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775102-aligned" + }, + { + "module": "write_target_editing", + "nodes": [ + 0, + 32, + 128, + 512 + ], + "lr": 1e-05, + "parameter_scope": "mlp", + "block_index": 0, + "replay_n": 32, + "replay_weight": 1.0, + "early_weight": 0.3, + "alignment_weight": 0.3, + "eval_batch_size": 512, + "name": "confirmation-w774103-i775102-early_ce_align", + "phase": "confirmation", + "arm": "early_ce_align", + "objectives": [ + "early_ce_align" + ], + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/representation-alignment-v1/runs/confirmation-w774103-i775102-aligned", + "parent_checkpoint_sha256": "b3679fba3d439b50ed1ea89f94e1bea5366f6fa9540cb9af40da4beddf5161a3", + "candidate_seed": 780101, + "per_cell": 4, + "diagnostic_existing_dir": "/ossfs/workspace/llm-memory-editability/results/interface-editing-confirmation-v1/runs/confirmation-w774103-i775102-aligned" + } + ], + "scientific_scope": "Paired extension on three existing worlds and two initializations, not new-world confirmation.", + "calibration": "Fixed recipe admissibility using only target E, U_atomic and necessary_atomic; no downstream D selection.", + "independent_unit": "world; initialization and cases are paired repeated measures", + "development_gate": "all E=1, all U_atomic>=.95, all necessary_atomic>=.95; early readout reported separately", + "runtime": { + "docker_context": "lm-memory", + "docker_host": "unix:///run/docker-lm-memory/docker.sock", + "image": "sha256:bd2a622ec8273f54786cd4029f55b717bcc488afeb688bee4f98c0bd5127bfe5", + "python": "/opt/conda/bin/python", + "cpus": 4, + "memory": "16g", + "env": { + "PYTHONDONTWRITEBYTECODE": "1", + "XDG_CACHE_HOME": "/tmp/cache", + "TORCH_HOME": "/tmp/torch", + "TORCHINDUCTOR_CACHE_DIR": "/tmp/torchinductor", + "TRITON_CACHE_DIR": "/tmp/triton" + } + }, + "budget": { + "development_jobs": 3, + "development_branches": 12, + "development_updates": 6144, + "confirmation_jobs": 18, + "confirmation_branches": 144, + "confirmation_updates": 73728, + "training_updates_total": 79872, + "steps_per_branch": 512, + "notes": "Every case has all three writing objectives and each objective has an old-fact sham; every branch starts from its unchanged parent." + } +} diff --git a/docs/development-artifacts/write-target-development-v1/source/docs/development-artifacts/learning-use-20261007/protocol.md b/docs/development-artifacts/write-target-development-v1/source/docs/development-artifacts/learning-use-20261007/protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..fda8870bad8ed95d079e68e34131851bbe44a4e7 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/docs/development-artifacts/learning-use-20261007/protocol.md @@ -0,0 +1,36 @@ +# 知识学习与继续使用:2026-10-07执行协议 + +用户已授权设计并开展实验,使用当前空闲GPU并行观测。本协议记录本轮实际比较;当前研究路线仍只维护在 `docs/roadmap.md`。历史实验、权重与冻结源码均不修改。 + +## 主问题 + +先学会组合,再只学习从未见过的原子事实,原来的使用能力能否迁移?事实能回答、能组合、更新后能继续使用分别评价,不把第一层仅作为筛选条件。 + +## 顺序新知识实验 + +- 数据:既有2Wiki来源的真实名称、三元组、问题和答案。重新划分A/B,B的两条事实均不得进入阶段A原子或组合训练;目标实体须有其它真实A事实作为出现支持,关系搭配须在A组合中出现。源图中的显式直接/反向泄漏和名称歧义按数据审计排除。保留每条来源与实际分母;熟悉实体表示曾在A出现,不预先保证模型已掌握。 +- 一个开发划分,三个固定确认划分。三个确认划分来自同一真实图,不称三个独立世界;初始化与划分层级分开报告。数据选择只依据图和来源,不依据模型预测。 +- 固定普通四层完整Transformer,宽256、8头、GPT2 tokenizer、dropout=0,从随机初始化训练全部参数。首轮开发A阶段8,000更新、B阶段4,000更新,batch/microbatch=128,AdamW峰值lr=3e-4、wd=.1、两段余弦与200步warmup。所有历史共用按全局步定义的同一学习率日程。 +- 三种历史:A原子+AA组合后接B原子+A原子回放;A原子重复后接相同B阶段;前一种历史的同一份实际训练例总清单打乱后从头混合。另设组合父条件仅继续复习A原子的sham。主三历史都不提供含B的组合答案。 +- A阶段每批一半原子、一半组合,原子对照将组合槽换成A原子;B阶段一半B原子、一半A原子。顺序组合与混合的实际样本多重集、监督token相同;padding和批次构成带来的实际计算差异逐项记录,不声称FLOPs完全一致。 +- 初始开发采用两个配对初始化,每个初始化四历史。正式预算依据开发学习轨迹选择后固定,不能依据BB成绩挑配方或训练节点。所有开发结果保留。 +- 固定评价:A/B原子、训练组合、AA/BA/AB/BB直接生成、必要事实正确子集及其覆盖;阶段边界与终点另报模型自产第一跳后的第二次调用。别名EM为主,规范答案、无歧义别名、EOS/截断及NLL另报。 +- 开发首先看A原子、训练组合是否学会,以及AA留出上是否形成可测组合能力;B阶段看B原子学习和AA保持。操作失败先改开发配方,不把低BB本身当淘汰标准。确认集不参与任何选择。连续原子学习若损伤AA,使用sham区分继续训练与新事实干扰;必要的A组合回放另立修订,不暗中改变主臂。 +- 解释:组合历史优于原子历史支持先前使用经历的帮助;混合高而顺序低且AA保持支持学习顺序的额外困难;混合与顺序都低说明该配方的跨事实组合有限;AA下降时优先研究保持。 + +## 编辑写入目标实验 + +- 复用既有共享GPT对齐父模型,固定共享首块MLP参数可更新,其余冻结。只考察图选严格首跳事实,不按派生答案表现挑样本。 +- 三个目标:最终原子CE;再加早期实体CE;再加早期残差方向对新实体输入Embedding的对齐。额外CE和方向项系数均为.3,沿用父模型经过验证的权重。三个臂用同一新实体标签,不提供第二关系或派生答案。 +- 所有臂计算相同目标组件,未启用项权重置零;同lr=1e-5、32条旧原子父分布KL回放、Adam和512步。每个编辑配原旧事实复习sham;记录0/32/128/512步。 +- 开发父模型使用2个历史图选严格首跳事实,三个目标各独立容器。先重载历史编辑权重,测早期状态的新/旧实体读出及方向,再做新训练。开发判断只读E、必要事实及U原子保持,不能用D传播择优。 +- 确认采用三个既有世界、每世界两个初始化、每父模型四个图选事实、三个写入目标及edit/sham:18个独立作业、144个512步分支。属于配对扩展,不称新世界确认。 +- 主报全池D新答案、旧答案残留、未影响原子与组合保持;父模型会答子集同时报告覆盖。早期身份/方向是直接测量,不另训预测器。只改好身份、还是必须改表示形式、或两者都不足,由三个目标的端到端结果区分。 + +## 方法继承与执行 + +已阅读原文方法和相关附录:Grokking of Implicit Reasoning(NeurIPS 2024)§2–3及E.2,How do Transformers Learn Implicit Reasoning(NeurIPS 2025)§2.1–2.4,MQuAKE(EMNLP 2023)§2–4。继承原子/组合划分、首/次跳角色和编辑/后果/保持分开评价;扩展知识获得的时间顺序与同标签写入目标。完整阅读材料在 `results/literature-framing-review-20261007/`。 + +使用 `docker --context lm-memory`,固定已验证镜像,每作业独立容器、GPU、CPU/内存、tmpfs及持久结果目录,不开放端口。每次提交核对GPU实际占用及三个daemon容器预留,并取得GPU执行锁。全部科学作业同步启用W&B,团队zhusq20、项目llm-memory-editability;凭据只由主机记录进程读取。冻结配置、源码、输入哈希和配对训练计划;独立进程重载计分后才标为审计通过。工程失败停止该批后续提交,已运行任务正常结束,失败记录保留。 + +8张GPU的FP32/BF16矩阵计算、反向和同步检查已通过,证据为 `results/learning-use-runtime-20261007/summary.json`。开发与正式实验分别冻结,开发未完成不预先宣称正式结论或云端同步成功。 diff --git a/docs/development-artifacts/write-target-development-v1/source/scripts/execute_learning_use.py b/docs/development-artifacts/write-target-development-v1/source/scripts/execute_learning_use.py new file mode 100644 index 0000000000000000000000000000000000000000..232f6953684c7eaa24f1a989d43923ef87f6740d --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/scripts/execute_learning_use.py @@ -0,0 +1,335 @@ +"""Freeze and run new learning/use experiments without touching historical batches.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import json +import shutil +import subprocess +import sys +import time +import traceback +from pathlib import Path + +from run_memory_interface_next import environment, now, write + +PROJECT = Path("/ossfs/workspace/llm-memory-editability") +SCRIPT = "scripts/execute_learning_use.py" + + +def read(path): + return json.loads(Path(path).read_text()) + + +def sha(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def freeze(path): + config = read(path) + assert config["runtime"]["docker_context"] == "lm-memory" + assert config["runtime"]["image"].startswith("sha256:") + assert set(config["gpus"]) <= set(range(8)) and config["gpus"] + names = [spec["name"] for spec in config["specs"]] + assert names and len(names) == len(set(names)) + assert all(Path(name).name == name for name in names) + artifact = PROJECT / "docs/development-artifacts" / config["batch"] + source = artifact / "source" + if source.exists(): + raise FileExistsError("Frozen source already exists; use a new revision") + assert not (PROJECT / "results" / config["batch"] / "controller-state.json").exists() + inputs = {} + for spec in config["specs"]: + for key in ("data_file",): + if key in spec: + target = (PROJECT / spec[key]).resolve() + spec[key] = str(target) + spec[key + "_sha256"] = sha(target) + inputs[str(target)] = sha(target) + if "parent_dir" in spec: + parent = (PROJECT / spec["parent_dir"]).resolve() + spec["parent_dir"] = str(parent) + spec["parent_checkpoint_sha256"] = sha(parent / "model.pt") + inputs[str(parent / "model.pt")] = spec["parent_checkpoint_sha256"] + if (parent / "run.json").exists(): + inputs[str(parent / "run.json")] = sha(parent / "run.json") + files = list((PROJECT / "src/llm_memory_editability").glob("*.py")) + files += [PROJECT / SCRIPT, PROJECT / "scripts/run_memory_interface_next.py"] + files += [PROJECT / "configs/experiment-tracking-defaults.json", path.resolve()] + files += [PROJECT / name for name in config.get("additional_sources", [])] + hashes = {} + for file in sorted(set(files)): + relative = file.relative_to(PROJECT) + target = source / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(file, target) + hashes[str(relative)] = sha(target) + config.update( + frozen_utc=now(), + repository=str(PROJECT), + source_root=str(source), + results_root=str(PROJECT / "results" / config["batch"]), + source=hashes, + input_files=inputs, + git_commit=subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=PROJECT, text=True + ).strip(), + ) + destination = artifact / "frozen-config.json" + write(destination, config) + write(artifact / "execution-lock.json", {"config_sha256": sha(destination)}) + print(json.dumps({"config": str(destination), "runs": len(names)})) + + +def checked(path): + assert sha(path) == read(path.with_name("execution-lock.json"))["config_sha256"] + config = read(path) + for relative, expected in config["source"].items(): + assert sha(Path(config["source_root"]) / relative) == expected, relative + for target, expected in config["input_files"].items(): + assert sha(target) == expected, target + return config + + +def gpu_available(gpu): + result = subprocess.run( + [ + "nvidia-smi", + "-i", + str(gpu), + "--query-gpu=memory.used,utilization.gpu", + "--format=csv,noheader,nounits", + ], + capture_output=True, + text=True, + check=True, + ) + memory, utilization = [int(value.strip()) for value in result.stdout.strip().split(",")] + if memory >= 256 or utilization >= 5: + return False + # A container can reserve a GPU before its first CUDA allocation. + for context in ("default", "d157", "lm-memory"): + identifiers = subprocess.check_output( + ["docker", "--context", context, "ps", "-q"], text=True + ).split() + if not identifiers: + continue + snapshots = json.loads( + subprocess.check_output( + ["docker", "--context", context, "inspect", *identifiers], text=True + ) + ) + for snapshot in snapshots: + for request in snapshot["HostConfig"].get("DeviceRequests") or []: + if request.get("Count") == -1 or str(gpu) in (request.get("DeviceIDs") or []): + return False + return True + + +def claim_gpu(gpu): + lock = open(f"/tmp/lm-learning-use-gpu-{gpu}.lock", "w") + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if not gpu_available(gpu): + lock.close() + return None + return lock + except BlockingIOError: + lock.close() + return None + + +def start_tracker(config, root): + command = [ + str(PROJECT / ".venv-wandb/bin/python"), + "-u", + "-m", + "llm_memory_editability.interface_tracking", + "--root", + str(root), + "--runs-dir", + str(root / "runs"), + "--defaults", + config["source_root"] + "/configs/experiment-tracking-defaults.json", + ] + with (root / "tracking.log").open("a") as log: + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + ) + write(root / "tracking-process.json", {"pid": process.pid, "command": command}) + deadline = time.monotonic() + 45 + while not (root / "tracking-ready.json").exists(): + if process.poll() is not None or time.monotonic() > deadline: + raise RuntimeError("W&B sidecar failed to initialize; see tracking.log") + time.sleep(0.25) + return process + + +def controller(path): + config = checked(path) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + lock = (root / "controller.lock").open("w") + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if (root / "controller-state.json").exists(): + raise FileExistsError( + "Existing history must be explicitly recovered, never silently restarted" + ) + shutil.copy2(path, root / "frozen-config.json") + state = dict( + state="starting", + started_utc=now(), + completed=[], + failed=[], + active={}, + queued=[spec["name"] for spec in config["specs"]], + gpus=config["gpus"], + ) + write(root / "controller-state.json", state) + active, pending = {}, list(enumerate(config["specs"])) + tracker = None + try: + tracker = start_tracker(config, root) + state["state"] = "running" + while pending or active: + for gpu, job in list(active.items()): + if job["process"].poll() is None: + continue + job["log"].close() + out = job["out"] + audit = read(out / "audit.json") if (out / "audit.json").exists() else {} + passed = job["process"].returncode == 0 and audit.get("passed") is True + state["completed" if passed else "failed"].append(job["spec"]["name"]) + write( + out / "process-status.json", + { + "returncode": job["process"].returncode, + "passed": passed, + "utc": now(), + }, + ) + if not passed and not (out / "failure.json").exists(): + write(out / "failure.json", {"reason": "worker_or_independent_audit_failed"}) + job["gpu_lock"].close() + del active[gpu] + if tracker.poll() is not None: + state["tracking_failure"] = tracker.returncode + # A failed contract pauses further submissions; already running jobs finish normally. + can_schedule = not state["failed"] and "tracking_failure" not in state + if can_schedule: + for gpu in config["gpus"]: + if gpu in active or not pending: + continue + gpu_lock = claim_gpu(gpu) + if gpu_lock is None: + continue + index, spec = pending.pop(0) + out = root / "runs" / spec["name"] + out.mkdir(parents=True, exist_ok=False) + command = [ + sys.executable, + "-u", + config["source_root"] + "/scripts/run_memory_interface_next.py", + "worker", + "--config", + str(path), + "--index", + str(index), + "--gpu", + str(gpu), + ] + log = (out / "worker.log").open("a") + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + ) + active[gpu] = dict( + process=process, log=log, out=out, spec=spec, gpu_lock=gpu_lock + ) + write(out / "host-worker.json", {"pid": process.pid, "command": command}) + state.update( + active={ + str(gpu): {"name": job["spec"]["name"], "pid": job["process"].pid} + for gpu, job in active.items() + }, + queued=[spec["name"] for _, spec in pending], + updated_utc=now(), + ) + write(root / "controller-state.json", state) + if not can_schedule and not active: + break + time.sleep(2) + state.update( + state="complete" + if not pending and not state["failed"] and "tracking_failure" not in state + else "finished_with_failures", + finished_utc=now(), + ) + write(root / "controller-state.json", state) + except BaseException: + state.update( + state="finished_with_failures", error=traceback.format_exc(), updated_utc=now() + ) + write(root / "controller-state.json", state) + raise + finally: + # Do not kill scientific jobs on a controller error. Preserve ownership and evidence. + for job in active.values(): + job["log"].close() + if tracker is not None and tracker.poll() is not None: + write(root / "tracking-exit.json", {"returncode": tracker.returncode}) + + +def launch(path): + config = checked(path) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + if (root / "controller-process.json").exists(): + raise FileExistsError("Controller has already been launched") + command = [ + sys.executable, + "-u", + config["source_root"] + "/" + SCRIPT, + "controller", + "--config", + str(path), + ] + with (root / "controller.log").open("a") as log: + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + write(root / "controller-process.json", {"pid": process.pid, "command": command, "utc": now()}) + print( + json.dumps( + { + "pid": process.pid, + "results": str(root), + "wandb": "https://wandb.ai/zhusq20/llm-memory-editability", + } + ) + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["freeze", "launch", "controller"]) + parser.add_argument("--config", type=Path, required=True) + args = parser.parse_args() + {"freeze": freeze, "launch": launch, "controller": controller}[args.action]( + args.config.resolve() + ) diff --git a/docs/development-artifacts/write-target-development-v1/source/scripts/run_memory_interface_next.py b/docs/development-artifacts/write-target-development-v1/source/scripts/run_memory_interface_next.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c8e478944e615761647dd0d1c900a86e48ae81 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/scripts/run_memory_interface_next.py @@ -0,0 +1,397 @@ +"""Freeze and execute sequential research stages on explicitly assigned GPUs.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import importlib +import json +import os +import shutil +import subprocess +import sys +import time +import traceback +from datetime import datetime, timezone +from pathlib import Path + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temp.replace(path) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def environment(source): + env = dict(os.environ) + if not env.get("MEMORY_INTERFACE_CONTAINER"): + env["LD_LIBRARY_PATH"] = "/lib64" + ( + ":" + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "" + ) + env.update(OMP_NUM_THREADS="1", MKL_NUM_THREADS="1", PYTHONPATH=str(source / "src")) + return env + + +def freeze(input_path): + config = json.loads(input_path.read_text()) + root = Path.cwd().resolve() + artifact = root / "docs/development-artifacts" / config["batch"] + source = artifact / "source" + if source.exists(): + raise FileExistsError(source) + assert len(config["gpus"]) == 4 and set(config["gpus"]) == {2, 3, 4, 5} + assert config["runtime"]["image"].startswith("sha256:") + assert config["runtime"]["docker_host"].startswith("unix://") + assert config["runtime"]["docker_context"] == "lm-memory", "Use only the LM project's daemon" + assert config["runtime"]["docker_host"] == "unix:///run/docker-lm-memory/docker.sock" + names = [s["name"] for s in config["specs"]] + assert len(names) == len(set(names)) and names + files = sorted( + list(Path("src/llm_memory_editability").glob("*.py")) + + [Path(__file__).relative_to(root), Path("configs/experiment-tracking-defaults.json")] + + [Path(p) for p in config.get("additional_sources", [])] + ) + config["source"] = {} + for path in files: + dest = source / path + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, dest) + config["source"][str(path)] = digest(path) + config.update( + frozen_utc=now(), + repository=str(root), + source_root=str(source), + results_root=str(root / "results" / config["batch"]), + git_commit=subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), + ) + for spec in config["specs"]: + if "parent_dir" in spec: + parent = (root / spec["parent_dir"]).resolve() + spec["parent_dir"] = str(parent) + spec["parent_checkpoint_sha256"] = digest(parent / "model.pt") + path = artifact / "frozen-config.json" + write(path, config) + print(json.dumps({"config": str(path), "runs": len(names), "source_files": len(files)})) + + +def launch(config_path): + config = json.loads(config_path.read_text()) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + saved_config = root / "frozen-config.json" + if saved_config.exists() and saved_config.read_bytes() != config_path.read_bytes(): + raise RuntimeError("The result directory contains a different frozen configuration") + shutil.copyfile(config_path, saved_config) + state = root / "controller-state.json" + if state.exists() and json.loads(state.read_text()).get("state") == "running": + raise RuntimeError("A running controller already owns this stage") + script = Path(config["source_root"]) / "scripts" / Path(__file__).name + command = [sys.executable, "-u", str(script), "controller", "--config", str(config_path)] + with (root / "controller.log").open("a") as log: + proc = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + write(root / "controller-process.json", {"pid": proc.pid, "command": command}) + print(json.dumps({"pid": proc.pid, "root": str(root)})) + + +def controller(config_path): + config = json.loads(config_path.read_text()) + root, source = Path(config["results_root"]), Path(config["source_root"]) + for path, expected in config["source"].items(): + assert digest(source / path) == expected, f"Frozen source changed: {path}" + state = { + "state": "running", + "started_utc": now(), + "gpus": config["gpus"], + "completed": [], + "failed": [], + "active": {}, + } + write(root / "controller-state.json", state) + env = environment(source) + tracking_python = str(Path(config["repository"]) / ".venv-wandb/bin/python") + tracker_command = [ + tracking_python, + "-u", + "-m", + "llm_memory_editability.interface_tracking", + "--root", + str(root), + "--runs-dir", + str(root / "runs"), + "--defaults", + str(source / "configs/experiment-tracking-defaults.json"), + ] + tracking_log = (root / "tracking.log").open("a") + tracker = subprocess.Popen( + tracker_command, env=env, stdout=tracking_log, stderr=subprocess.STDOUT + ) + write(root / "tracking-process.json", {"pid": tracker.pid, "command": tracker_command}) + queue = list(range(len(config["specs"]))) + active = {} + try: + deadline = time.monotonic() + 30 + while not (root / "tracking-ready.json").exists() and tracker.poll() is None: + if time.monotonic() >= deadline: + break + time.sleep(0.2) + if tracker.poll() is not None or not (root / "tracking-ready.json").exists(): + state["tracking_failure"] = "Tracking process did not become ready" + state["state"] = "finished_with_failures" + write(root / "controller-state.json", state) + raise RuntimeError(state["tracking_failure"]) + while queue or active: + if tracker.poll() is not None: + state["tracking_failure"] = f"Tracking process exited early: {tracker.returncode}" + for gpu, (proc, index, log) in list(active.items()): + result = proc.poll() + if result is None: + continue + log.close() + name = config["specs"][index]["name"] + state["completed" if result == 0 else "failed"].append(name) + del active[gpu] + # Stop scheduling after a failed contract rather than silently run an invalid matrix. + if state["failed"] or state.get("tracking_failure"): + queue.clear() + for gpu in config["gpus"]: + if gpu in active or not queue: + continue + index = queue.pop(0) + spec = config["specs"][index] + out = root / "runs" / spec["name"] + if ( + (out / "complete.json").exists() + and (out / "audit.json").exists() + and json.loads((out / "audit.json").read_text()).get("passed") is True + ): + state["completed"].append(spec["name"]) + continue + out.mkdir(parents=True, exist_ok=True) + log = (out / "worker.log").open("a") + command = [ + sys.executable, + "-u", + __file__, + "worker", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + str(gpu), + ] + proc = subprocess.Popen(command, env=env, stdout=log, stderr=subprocess.STDOUT) + active[gpu] = (proc, index, log) + state["active"] = { + str(gpu): {"pid": p.pid, "name": config["specs"][i]["name"]} + for gpu, (p, i, _) in active.items() + } + state["updated_utc"] = now() + write(root / "controller-state.json", state) + time.sleep(2) + state["state"] = ( + "complete" + if not state["failed"] and not state.get("tracking_failure") + else "finished_with_failures" + ) + state["finished_utc"] = now() + write(root / "controller-state.json", state) + try: + tracker.wait(timeout=120) + except subprocess.TimeoutExpired: + write(root / "tracking-pending.json", {"pid": tracker.pid, "reason": "sync pending"}) + write(root / "tracking-exit.json", {"returncode": tracker.returncode}) + finally: + tracking_log.close() + + +def container_work(config_path, index, gpu): + """One isolated container per experiment, including its fresh-process audit.""" + config = json.loads(config_path.read_text()) + spec, runtime = config["specs"][index], config["runtime"] + out = Path(config["results_root"]) / "runs" / spec["name"] + docker = ( + ["docker", "--context", runtime["docker_context"]] + if runtime.get("docker_context") + else ["docker", "--host", runtime["docker_host"]] + ) + name = ( + "lm-interface-" + hashlib.sha256((config["batch"] + spec["name"]).encode()).hexdigest()[:20] + ) + command = docker + [ + "run", + "--name", + name, + "--label", + "project=llm-memory-editability", + "--label", + "batch=" + config["batch"], + "--network=none", + "--gpus", + f"device={gpu}", + "--cpus", + str(runtime.get("cpus", 4)), + "--memory", + runtime.get("memory", "16g"), + "--shm-size=1g", + "--read-only", + "--tmpfs", + "/tmp:rw,size=2g", + "--mount", + f"type=bind,src={config['repository']},dst={config['repository']},readonly", + "--mount", + f"type=bind,src={out},dst={out}", + "--workdir", + config["repository"], + "--env", + "MEMORY_INTERFACE_CONTAINER=1", + "--env", + f"PHYSICAL_GPU={gpu}", + "--env", + "PYTHONDONTWRITEBYTECODE=1", + "--env", + "OMP_NUM_THREADS=1", + "--env", + "MKL_NUM_THREADS=1", + "--env", + "PYTHONPATH=" + str(Path(config["source_root"]) / "src"), + ] + for key, value in runtime.get("env", {}).items(): + command += ["--env", f"{key}={value}"] + command += [ + runtime["image"], + runtime["python"], + "-u", + __file__, + "container-worker", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + "0", + ] + write(out / "container-command.json", {"name": name, "physical_gpu": gpu, "command": command}) + process = subprocess.Popen(command) + for _ in range(50): + snapshot = subprocess.run(docker + ["inspect", name], capture_output=True, text=True) + if snapshot.returncode == 0: + info = json.loads(snapshot.stdout)[0] + if info["State"].get("Running"): + write( + out / "container-runtime.json", + { + "physical_gpu": gpu, + "host_pid": info["State"]["Pid"], + "container_id": info["Id"], + "image": info["Image"], + "cpus": runtime.get("cpus", 4), + "memory": runtime.get("memory", "16g"), + }, + ) + break + if process.poll() is not None: + break + time.sleep(0.2) + result = process.wait() + inspected = subprocess.run(docker + ["inspect", name], capture_output=True, text=True) + if inspected.returncode == 0: + write(out / "container-inspect.json", json.loads(inspected.stdout)) + if result: + raise RuntimeError(f"Experiment container exited {result}: {name}") + + +def work(config_path, index, gpu, audit_only=False): + import torch + + config = json.loads(config_path.read_text()) + spec = config["specs"][index] + out = Path(config["results_root"]) / "runs" / spec["name"] + torch.set_num_threads(1) + device = torch.device(f"cuda:{gpu}") + if "parent_dir" in spec: + assert digest(Path(spec["parent_dir"]) / "model.pt") == spec["parent_checkpoint_sha256"] + module = importlib.import_module("llm_memory_editability." + config["module"]) + if audit_only: + module.audit(out, device) + return + if not (out / "complete.json").exists(): + if config["module"] == "alignment_coverage": + module.train(spec, out, config["source"], device) + else: + module.run(spec, out, device) + # Deliberately reload in a fresh Python process, not the writer's model object. + subprocess.run( + [ + sys.executable, + "-u", + __file__, + "audit", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + str(gpu), + ], + check=True, + env=environment(Path(config["source_root"])), + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "action", choices=["freeze", "launch", "controller", "worker", "container-worker", "audit"] + ) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--index", type=int, default=0) + parser.add_argument("--gpu", type=int, default=2) + args = parser.parse_args() + path = args.config.resolve() + if args.action == "freeze": + freeze(path) + elif args.action == "launch": + launch(path) + elif args.action == "controller": + controller(path) + else: + config = json.loads(path.read_text()) + out = Path(config["results_root"]) / "runs" / config["specs"][args.index]["name"] + try: + if args.action == "worker": + with open(f"/tmp/llm-memory-interface-gpu-{args.gpu}.lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + container_work(path, args.index, args.gpu) + elif args.action == "container-worker": + assert os.environ.get("MEMORY_INTERFACE_CONTAINER") == "1" + work(path, args.index, args.gpu) + else: + work(path, args.index, args.gpu, True) + except Exception: + write( + out / "failure.json", + {"action": args.action, "utc": now(), "traceback": traceback.format_exc()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-development-v1/source/scripts/run_write_target_editing.py b/docs/development-artifacts/write-target-development-v1/source/scripts/run_write_target_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..f0b4e0cb0cb70511569a1dec8aefffa8aa52e419 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/scripts/run_write_target_editing.py @@ -0,0 +1,46 @@ +"""Run, independently audit, or inspect fixed write-target edit comparisons.""" + +import argparse +import json +from pathlib import Path + +from llm_memory_editability import write_target_editing as experiment +from llm_memory_editability.grok_depth import write_json + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + run = sub.add_parser("run") + run.add_argument("--spec", type=Path, required=True) + run.add_argument("--out", type=Path, required=True) + run.add_argument("--device", default="cuda:0") + audit = sub.add_parser("audit") + audit.add_argument("--out", type=Path, required=True) + audit.add_argument("--device", default="cuda:0") + diagnostic = sub.add_parser("diagnostics") + diagnostic.add_argument("--existing-dir", type=Path, required=True) + diagnostic.add_argument("--out", type=Path, required=True) + diagnostic.add_argument("--device", default="cuda:0") + decision = sub.add_parser("development-decision") + decision.add_argument("--run-dirs", nargs="+", type=Path, required=True) + decision.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + if args.command == "run": + result = experiment.run(json.loads(args.spec.read_text()), args.out, args.device) + elif args.command == "audit": + result = experiment.audit(args.out, args.device) + elif args.command == "diagnostics": + result = experiment.diagnostics(args.existing_dir, args.out, args.device) + else: + result = experiment.development_decision(args.run_dirs) + write_json(args.out, result) + print( + json.dumps( + {key: value for key, value in result.items() if key not in {"branches", "records"}} + ) + ) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/__init__.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c606cfd654948ec99bedce5244b7c6608a801a1d --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/__init__.py @@ -0,0 +1,19 @@ +"""Analytical examples for research on shared structure and editability.""" + +from .experiments import run_minimal_example +from .low_rank import ( + best_rank_approximation, + evaluate_update, + numerical_rank, + representation_gap, +) + +__version__ = "0.1.0" + +__all__ = [ + "best_rank_approximation", + "evaluate_update", + "numerical_rank", + "representation_gap", + "run_minimal_example", +] diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/__main__.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..860f4f8babf02fc2d6920b26bf4ac11a3e254766 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/__main__.py @@ -0,0 +1,5 @@ +"""Support ``python -m llm_memory_editability``.""" + +from .cli import main + +raise SystemExit(main()) diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/alignment_coverage.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/alignment_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..6efacd7bf323dd87ad027292dee80a9f665032fa --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/alignment_coverage.py @@ -0,0 +1,503 @@ +"""Paired geometric-supervision coverage in the established complete GPT task. + +All arms retain full-token CE and all-example first-hop CE. Coverage changes +only a multiplicative mask on the per-example geometric objective; every arm +executes the same forward and backward operations, including the zero mask. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .latent_scaling import build_world, model_digest +from .representation_alignment import new_model +from .representation_alignment import pack_training as pack_base_training +from .storage_composition import data_digest, evaluate, file_hash +from .storage_frontier import learning_rate + +COVERAGES = ("none", "composition_only", "all_atomic_and_composition") +NORMALIZATIONS = ("selected_mean", "batch_mean") +STRATA = ("common_atomic", "train_composite", "anchor_atomic") +COMPONENTS = ( + "text_ce", + "bridge_ce", + "alignment_loss", + "alignment_all_mean", + "alignment_selected_mean", + "alignment_batch_mean", + "alignment_selected_count", + "alignment_denominator", +) + + +def make_specs(phase="development"): + """Return the proposed paired matrix without freezing files or starting jobs.""" + if phase not in ("development", "confirmation"): + raise ValueError("Phase must be development or confirmation") + worlds = [810011] if phase == "development" else [810101, 810102, 810103] + initializations = [811011] if phase == "development" else [811101, 811102] + base = { + "phase": phase, + "stream_seed": 812011 if phase == "development" else 812101, + "heads_n": 256, + "bridges_n": 128, + "tails_n": 64, + "familiar_n": 64, + "strict_n": 32, + "anchor_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "composition_count": 256, + "width": 128, + "heads": 4, + "layers": 1, + "repeats": 2, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 16000, + "nodes": [0, 256, 1000, 2000, 4000, 8000, 16000], + "bridge_weight": 0.3, + "alignment_weight": 0.3, + } + arms = ( + ("none", "none", "batch_mean"), + ("composition_batch", "composition_only", "batch_mean"), + ("composition_selected", "composition_only", "selected_mean"), + ("all_batch", "all_atomic_and_composition", "batch_mean"), + ) + return [ + { + **base, + "nodes": list(base["nodes"]), + "world": world, + "initialization": initialization, + "arm": arm, + "alignment_coverage": coverage, + "alignment_normalization": normalization, + } + for world in worlds + for initialization in initializations + for arm, coverage, normalization in arms + ] + + +def validate_spec(spec): + if spec["alignment_coverage"] not in COVERAGES: + raise ValueError(f"Unknown alignment coverage: {spec['alignment_coverage']}") + if spec["alignment_normalization"] not in NORMALIZATIONS: + raise ValueError(f"Unknown alignment normalization: {spec['alignment_normalization']}") + if spec["bridge_weight"] != 0.3: + raise ValueError("This comparison fixes all-example first-hop CE weight at 0.3") + if not np.isfinite(spec["alignment_weight"]) or spec["alignment_weight"] < 0: + raise ValueError("Alignment weight must be finite and nonnegative") + if spec["batch_size"] <= 0 or spec["batch_size"] % 3: + raise ValueError("Batch size must divide equally into the three fixed streams") + nodes = spec["nodes"] + if not nodes or nodes[0] != 0 or nodes[-1] != spec["steps"]: + raise ValueError("Nodes must include initialization and the fixed endpoint") + if nodes != sorted(set(nodes)) or any(type(n) is not int or n < 0 for n in nodes): + raise ValueError("Nodes must be strictly increasing nonnegative integer steps") + if spec["steps"] <= 0: + raise ValueError("Training needs a positive fixed step budget") + + +def pack_training(world, coverage): + """Keep base data byte-identical and append an explicit geometry mask.""" + if coverage not in COVERAGES: + raise ValueError(f"Unknown alignment coverage: {coverage}") + arrays, sizes = pack_base_training(world) + if min(sizes) <= 0: + raise ValueError("All three training strata must be nonempty") + mask = np.zeros(sum(sizes), dtype=np.float32) + if coverage == "composition_only": + mask[sizes[0] : sizes[0] + sizes[1]] = 1 + elif coverage == "all_atomic_and_composition": + mask[:] = 1 + return (*arrays, mask), sizes + + +def objective( + model, + tokens, + labels, + targets, + geometry_mask, + bridge_weight=0.3, + alignment_weight=0.3, + normalization="selected_mean", +): + """Return the training loss and named, unweighted objective components. + + selected_mean divides by selected examples (clamped to one for an empty + mask). batch_mean divides by all examples. Both reductions are always + evaluated, and mask coverage is recorded separately from loss strength. + """ + if normalization not in NORMALIZATIONS: + raise ValueError(f"Unknown alignment normalization: {normalization}") + 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() + per_example = (F.normalize(bridge, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1) + mask = geometry_mask.to(dtype=per_example.dtype) + selected_count = mask.sum() + numerator = (per_example * mask).sum() + selected_denominator = selected_count.clamp_min(1) + # Avoid creating a device scalar from host data during CUDA graph capture. + batch_denominator = torch.ones_like(selected_count) * per_example.numel() + selected_mean = numerator / selected_denominator + batch_mean = numerator / batch_denominator + use_selected = float(normalization == "selected_mean") + denominator = use_selected * selected_denominator + (1 - use_selected) * batch_denominator + alignment = numerator / denominator + parts = torch.stack( + ( + text_ce, + bridge_ce, + alignment, + per_example.mean(), + selected_mean, + batch_mean, + selected_count, + denominator, + ) + ) + return text_ce + bridge_weight * bridge_ce + alignment_weight * alignment, parts + + +class CoverageStep(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, mask = (part[self.index] for part in self.table) + loss, self.components = objective( + self.model, + tokens, + labels, + targets, + mask, + self.spec["bridge_weight"], + self.spec["alignment_weight"], + self.spec["alignment_normalization"], + ) + 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']}-" + f"{spec['alignment_coverage']}-{spec['alignment_normalization']}" + ) + + +def _draw_indices(streams, offsets, counts, steps, batch_size): + indices = [] + for j, stream in enumerate(streams): + drawn = stream.take(steps * batch_size // 3).reshape(steps, -1) + counts[j] += np.bincount(drawn.ravel(), minlength=len(counts[j])) + indices.append(drawn + offsets[j]) + return np.concatenate(indices, axis=1) + + +def _coverage_presentations(counts, mask, sizes): + offset, result = 0, {} + for name, count, size in zip(STRATA, counts, sizes, strict=True): + result[name] = int(np.dot(count, mask[offset : offset + size].astype(np.int64))) + offset += size + result["total"] = sum(result.values()) + return result + + +def train(spec, out, source, device): + """Train one immutable attempt; save weights and exposures at every node.""" + validate_spec(spec) + out, device = Path(out), torch.device(device) + out.mkdir(parents=True, exist_ok=True) + if any((out / name).exists() for name in ("run.json", "model.pt", "complete.json")): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + if device.type != "cuda": + raise ValueError("The captured training step requires an explicitly allocated CUDA device") + 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, spec["alignment_coverage"]) + mask = arrays[-1] + model = new_model(spec, device) + initial_hash, world_hash = model_digest(model), data_digest(world) + identity = { + "spec": spec, + "source": source, + "implementation_sha256": file_hash(Path(__file__)), + "world_sha256": world_hash, + "initial_model_sha256": initial_hash, + } + write_json( + out / "run.json", + { + **identity, + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device), + "dtype": "float32", + "allow_tf32": True, + "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, + "strata": dict(zip(STRATA, sizes, strict=True)), + "geometry_unique_examples": _coverage_presentations( + [np.ones(n, dtype=np.int64) for n in sizes], mask, sizes + ), + "geometry_definition": ( + "squared distance of normalized early state and detached input embedding" + ), + "bridge_ce_coverage": "all_atomic_and_composition", + "geometry_normalization": spec["alignment_normalization"], + "tracking_owner": "external read-only batch runner", + }, + ) + 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 = CoverageStep(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, checkpoints, step, training_seconds = [], [], 0, 0.0 + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 9, output_positions=9) + 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] * len(COMPONENTS) + coverage = _coverage_presentations(counts, mask, sizes) + row = { + "step": step, + "metrics": metrics, + **dict(zip(COMPONENTS, parts, strict=True)), + "alignment_normalization": spec["alignment_normalization"], + "alignment_weight": spec["alignment_weight"], + "geometry_target_presentations": coverage, + "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], + "sample_stream_sha256": input_hash.hexdigest(), + } + 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", **{f"stratum{j}": c for j, c in enumerate(counts)} + ) + checkpoint = out / f"model-{step:06d}.pt" + torch.save( + { + **identity, + "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), + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": coverage, + }, + checkpoint, + ) + checkpoints.append({"step": step, "file": checkpoint.name, "sha256": file_hash(checkpoint)}) + write_json(out / "checkpoints.json", checkpoints) + 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 = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) + 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() + # Keep the established downstream loader interface on filesystems without links. + shutil.copyfile(out / f"model-{step:06d}.pt", out / "model.pt") + np.savez_compressed(out / "exposures.npz", **{f"stratum{j}": c for j, c in enumerate(counts)}) + write_json( + out / "complete.json", + { + **identity, + "finished_utc": utc(), + "metrics": history[-1]["metrics"], + "training_seconds": training_seconds, + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": history[-1]["geometry_target_presentations"], + "model_sha256": file_hash(out / "model.pt"), + "nodes_saved": spec["nodes"], + }, + ) + write_json(out / "status.json", {"state": "complete", "step": step}) + + +def audit(out, device, *, all_nodes=False): + """Verify all artifacts; independently reload the endpoint (or all nodes).""" + out, device = Path(out), torch.device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + run = json.loads((out / "run.json").read_text()) + complete = json.loads((out / "complete.json").read_text()) + history = json.loads((out / "learning.json").read_text()) + manifest = json.loads((out / "checkpoints.json").read_text()) + spec = run["spec"] + validate_spec(spec) + assert spec == complete["spec"] + assert [row["step"] for row in history] == spec["nodes"] + assert [entry["step"] for entry in manifest] == spec["nodes"] + assert complete["nodes_saved"] == spec["nodes"] + assert file_hash(out / "model.pt") == complete["model_sha256"] == manifest[-1]["sha256"] + world = build_world(spec) + assert data_digest(world) == run["world_sha256"] == complete["world_sha256"] + with np.load(out / "world.npz") as saved_world: + assert set(saved_world.files) == set(world) + for key, value in world.items(): + np.testing.assert_array_equal(value, saved_world[key]) + arrays, sizes = pack_training(world, spec["alignment_coverage"]) + mask, offsets = arrays[-1], np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] + counts = [np.zeros(n, dtype=np.int64) for n in sizes] + input_hash, step, audits = hashlib.sha256(), 0, [] + model = new_model(spec, device) + assert model_digest(model) == run["initial_model_sha256"] == complete["initial_model_sha256"] + for entry, row in zip(manifest, history, strict=True): + while step < entry["step"]: + n = min(128, entry["step"] - step) + indices = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) + input_hash.update(indices.tobytes()) + step += n + checkpoint = out / entry["file"] + assert file_hash(checkpoint) == entry["sha256"] + payload = torch.load(checkpoint, map_location="cpu", weights_only=False) + assert payload["spec"] == spec and payload["step"] == step + for key in ("source", "implementation_sha256", "world_sha256", "initial_model_sha256"): + assert payload[key] == run[key] == complete[key] + assert ( + payload["sample_stream_sha256"] == row["sample_stream_sha256"] == input_hash.hexdigest() + ) + coverage = _coverage_presentations(counts, mask, sizes) + assert ( + payload["geometry_target_presentations"] + == row["geometry_target_presentations"] + == coverage + ) + with np.load(out / f"exposures-{step:06d}.npz") as saved_counts: + for j, count in enumerate(counts): + np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) + np.testing.assert_array_equal(count, payload["counts"][j]) + if step == 0: + model.load_state_dict(payload["model"]) + assert model_digest(model) == run["initial_model_sha256"] + if not all_nodes and step != spec["steps"]: + audits.append({"step": step, "passed": True, "predictions_recomputed": False}) + continue + model.load_state_dict(payload["model"]) + metrics, predictions = evaluate(model, world, "low", device) + max_nll_error = 0.0 + with np.load(out / f"predictions-{step:06d}.npz") as saved: + assert set(saved.files) == set(predictions) + 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]) + for split, values in metrics.items(): + for key, actual in values.items(): + expected = row["metrics"][split][key] + if actual is None: + assert expected is None + else: + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-5) + audits.append( + { + "step": step, + "passed": True, + "predictions_recomputed": True, + "max_nll_error": max_nll_error, + } + ) + assert complete["sample_stream_sha256"] == input_hash.hexdigest() + assert complete["geometry_target_presentations"] == _coverage_presentations(counts, mask, sizes) + with np.load(out / "exposures.npz") as saved_counts: + for j, count in enumerate(counts): + np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) + result = { + "passed": True, + "metrics": metrics, + "nodes": audits, + "max_nll_error": max(a.get("max_nll_error", 0.0) for a in audits), + "all_nodes": all_nodes, + "allow_tf32": True, + "world_sha256": data_digest(world), + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": _coverage_presentations(counts, mask, sizes), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/architecture_bridge.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/architecture_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..3d611f12f7be01721c8f453b8981605455e4b585 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/architecture_bridge.py @@ -0,0 +1,549 @@ +"""Paired interventions on MLP output and same-layer sequence cache. + +Oracle bridge hints define an assisted diagnostic, not an identified natural +reasoning circuit. Cache interventions do not change model parameters. +""" + +from __future__ import annotations + +import contextlib +import copy +import hashlib +import json +import re +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "data/architecture-bridge-v1" +ART = ROOT / "docs/development-artifacts/architecture-bridge-v1" +RESULTS = ROOT / "results/architecture-bridge-v1" +CONFIG = ROOT / "configs/architecture-bridge-v1.json" + + +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 order(value): + return hashlib.sha256(f"142935:{value}".encode()).hexdigest() + + +def normalize(value): + import string + + value = value.lower().translate(str.maketrans("", "", string.punctuation)) + return " ".join(re.sub(r"\b(a|an|the)\b", " ", value).split()) + + +def grade(text, answer, aliases=()): + value = text.rsplit("Final answer:", 1)[-1].strip() + value = re.sub(r"^(?:Answer|Bridge):\s*", "", value, flags=re.I).strip().strip('"*') + predicted, gold = normalize(value), normalize(answer) + a, b = Counter(predicted.split()), Counter(gold.split()) + common = sum((a & b).values()) + return { + "em": predicted == gold, + "f1": 2 * common / (sum(a.values()) + sum(b.values())) if common else 0.0, + "alias_em": predicted in {normalize(x) for x in [answer, *aliases]}, + } + + +def base_prompt(row, question=None): + context = row.get("support_context", "") + parts = ["Question: What is 2 + 2?\nAnswer: 4", "Output only the short answer."] + if context: + parts.append("Use the supplied passages.\nPassages:\n" + context) + parts.append("Question: " + (question if question is not None else row["question"])) + return "\n\n".join(parts) + + +def prefix(row, bridge): + return base_prompt(row) + "\nIntermediate entity: " + bridge + "\n" + + +def prepare(): + from transformers import AutoTokenizer + + if (ART / "data-lock.json").exists(): + raise FileExistsError("This data selection is already frozen") + cfg = read(CONFIG) + toks = { + k: AutoTokenizer.from_pretrained(ROOT / v["path"], local_files_only=True) + for k, v in cfg["models"].items() + } + source_path = ROOT / "data/twohop-frozen-v1/cases.json" + source, selected, audit = read(source_path), [], {} + for dataset in cfg["datasets"]: + for split, count in cfg["cases_per_dataset"].items(): + pool = sorted( + [x for x in source if x["dataset"] == dataset and x["split"] == split], + key=lambda x: order(x["id"]), + ) + for row in pool[:count]: + r = copy.deepcopy(row) + names = sorted({p["bridge"] for p in pool}, key=order) + forbidden = {normalize(x) for x in [r["bridge"], *r.get("bridge_aliases", [])]} + gold = {normalize(x) for x in [r["answer"], *r.get("aliases", [])]} + target = {k: len(t.encode(prefix(r, r["bridge"]))) for k, t in toks.items()} + chosen = [] + for name in names: + norm = normalize(name) + if norm in forbidden or any(g and g in norm for g in gold): + continue + if all(len(t.encode(prefix(r, name))) == target[k] for k, t in toks.items()): + chosen.append(name) + if len(chosen) == 2: + break + reason = None + if len(chosen) < 2: + reason = "fewer_than_two_length_matched_wrong_bridges" + if max(target.values()) > cfg["max_prefix_tokens"]: + reason = "prefix_exceeds_budget" + if any(g and g in normalize(r["bridge"]) for g in gold): + reason = "correct_bridge_contains_final_answer" + competitors = [ + x["answer"] for x in pool if normalize(x["answer"]) != normalize(r["answer"]) + ] + r.update( + prefix_tokens=target, + corrupted_bridge=chosen[0] if chosen else None, + control_bridge=chosen[1] if len(chosen) > 1 else None, + exclusion_reason=reason, + competitor=(r.get("wrong_donor") or {}).get("answer", competitors[0]), + ) + selected.append(r) + audit[f"{dataset}:{split}"] = { + "selected": count, + "eligible": sum( + x["exclusion_reason"] is None + for x in selected + if x["dataset"] == dataset and x["split"] == split + ), + } + # E comes from selected evaluation rows; R and U are independent source groups + # from the unused historical pool. D is never used to choose a direction. + edits = [r for r in selected if r["dataset"] == "2wiki" and r["split"] == "evaluation"] + used = {r["group"] for r in selected if r["dataset"] == "2wiki"} + reserves = sorted( + [ + r + for r in source + if r["dataset"] == "2wiki" and r["split"] == "evaluation" and r["group"] not in used + ], + key=lambda r: order("keep:" + r["id"]), + ) + lc = cfg["local_learning"] + learning = { + "E": edits[: lc["episodes"]], + "R": reserves[: lc["keep_R"]], + "U": reserves[lc["keep_R"] : lc["keep_R"] + lc["unseen_U"]], + } + assert len(learning["U"]) == lc["unseen_U"] + write(DATA / "cases.json", selected) + write(DATA / "learning.json", learning) + write( + ART / "data-lock.json", + { + "config": cfg, + "config_sha256": digest(CONFIG), + "source_sha256": digest(source_path), + "cases_sha256": digest(DATA / "cases.json"), + "learning_sha256": digest(DATA / "learning.json"), + "audit": audit, + "selection": ( + "Fixed hash before outputs; excluded cases are retained without replacement." + ), + }, + ) + return audit + + +def cache_fields(cache, layer): + obj = cache.layers[layer] + if hasattr(obj, "recurrent_states"): + return [("conv_states", 0), ("recurrent_states", 0)] + return [("keys", None), ("values", None)] + + +def field_get(obj, name, index): + value = getattr(obj, name) + return value if index is None else value[index] + + +def field_set(obj, name, index, value): + if index is None: + setattr(obj, name, value) + else: + getattr(obj, name)[index] = value + + +def matched_random(delta, seed): + generator = torch.Generator(device=delta.device).manual_seed(seed) + random = torch.randn(delta.shape, device=delta.device, dtype=delta.dtype, generator=generator) + return random * (delta.norm() / random.norm().clamp_min(torch.finfo(delta.dtype).tiny)) + + +def change_cache(target, donor, layer, random_seed=None): + # Keep recipient metadata and update only equal-shaped tensors. Prefix length + # and token positions are identical across donors in the frozen selection. + stats = {} + for i, (name, index) in enumerate(cache_fields(target, layer)): + a = field_get(target.layers[layer], name, index) + b = field_get(donor.layers[layer], name, index) + if a.shape != b.shape: + raise ValueError(f"Unequal cache shapes for {name}: {a.shape} != {b.shape}") + delta = b - a + if random_seed is not None: + delta = matched_random(delta, random_seed + i) + stats[name + "_delta_norm"] = float(delta.norm()) + field_set( + target.layers[layer], name, index, b.clone() if random_seed is None else a + delta + ) + return stats + + +class Engine: + def __init__(self, key, device=None): + from transformers import ( + AutoTokenizer, + PreTrainedTokenizerFast, + Qwen3_5ForCausalLM, + Qwen3ForCausalLM, + ) + + self.cfg = read(CONFIG) + self.key, self.mc = key, self.cfg["models"][key] + self.device = torch.device(device or self.cfg["device"]) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + if self.device.type == "cuda": + torch.cuda.set_per_process_memory_fraction(self.cfg["gpu_memory_fraction"], self.device) + cls = Qwen3ForCausalLM if key == "qwen3" else Qwen3_5ForCausalLM + # In transformers 5.17 Qwen2Tokenizer rebuilds Qwen3.5's regex and drops + # Unicode combining marks. Load the official tokenizer.json unchanged. + tokenizer_cls = AutoTokenizer if key == "qwen3" else PreTrainedTokenizerFast + self.tok = tokenizer_cls.from_pretrained(ROOT / self.mc["path"], local_files_only=True) + self.model = ( + cls.from_pretrained( + ROOT / self.mc["path"], + local_files_only=True, + dtype=torch.float32, + attn_implementation="eager", + ) + .to(self.device) + .eval() + .requires_grad_(False) + ) + self.layers = self.model.model.layers + self.stats = Counter() + self.eos = self.tok.eos_token_id + + def ids(self, text): + return torch.tensor([self.tok.encode(text, add_special_tokens=False)], device=self.device) + + def forward(self, ids, cache=None, total=None): + total = ids.shape[1] if total is None else total + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += ids.numel() + return self.model( + input_ids=ids, + attention_mask=torch.ones((1, total), device=self.device, dtype=torch.long), + past_key_values=cache, + use_cache=True, + logits_to_keep=1, + ) + + @contextlib.contextmanager + def mlp_hook(self, layer, replacement=None, capture=None): + def hook(module, args, output): + if capture is not None: + capture[layer] = output[0, -1].detach().clone() + if replacement is None: + return None + modified = output.clone() + modified[0, -1] = replacement + return modified + + handle = self.layers[layer].mlp.register_forward_hook(hook) + try: + yield + finally: + handle.remove() + + @torch.no_grad() + def prefill(self, text, layer=None, replacement=None): + ids, captured = self.ids(text), {} + if ids.shape[1] > self.cfg["max_prefix_tokens"]: + raise ValueError("Prefix exceeds budget; truncation is forbidden") + with contextlib.ExitStack() as stack: + for li in self.mc["layers"]: + stack.enter_context( + self.mlp_hook(li, replacement if li == layer else None, captured) + ) + out = self.forward(ids) + return out.past_key_values, captured, ids.shape[1] + + @torch.no_grad() + def continuation_score(self, logits, cache, total, answer): + targets = self.tok.encode(" " + answer, add_special_tokens=False) + [self.eos] + values = [] + for index, token in enumerate(targets): + values.append(float(logits[0, -1].log_softmax(-1)[token])) + if index + 1 < len(targets): + total += 1 + out = self.forward(torch.tensor([[token]], device=self.device), cache, total) + logits, cache = out.logits, out.past_key_values + return {"sum_logp": sum(values), "mean_logp": float(np.mean(values)), "tokens": targets} + + @torch.no_grad() + def finish(self, cache, n_prefix, row, suffix=None): + suffix_ids = self.ids(self.cfg["suffix"] if suffix is None else suffix) + total = n_prefix + suffix_ids.shape[1] + out = self.forward(suffix_ids, cache, total) + logits, cache = out.logits, out.past_key_values + scores = {} + for name, answer in [("correct", row["answer"]), ("competitor", row["competitor"])]: + scores[name] = self.continuation_score(logits, copy.deepcopy(cache), total, answer) + scores["margin"] = scores["correct"]["mean_logp"] - scores["competitor"]["mean_logp"] + tokens = [] + for _ in range(self.cfg["generation_tokens"]): + token = int(logits[0, -1].argmax()) + tokens.append(token) + if token == self.eos: + break + total += 1 + out = self.forward(torch.tensor([[token]], device=self.device), cache, total) + logits, cache = out.logits, out.past_key_values + text = self.tok.decode(tokens, skip_special_tokens=True) + self.stats["generated_tokens"] += len(tokens) + return { + "text": text, + "tokens": tokens, + "ended_eos": tokens[-1] == self.eos, + **grade(text, row["answer"], row.get("unambiguous_aliases", row.get("aliases", []))), + "scores": scores, + } + + def direct(self, row, question=None, answer=None): + qrow = dict(row) + if answer is not None: + qrow.update(answer=answer, aliases=[], unambiguous_aliases=[]) + cache, _, length = self.prefill(base_prompt(row, question)) + return self.finish(cache, length, qrow) + + @torch.no_grad() + def case(self, row): + started = time.monotonic() + before_stats = self.stats.copy() + result = { + "id": row["id"], + "dataset": row["dataset"], + "split": row["split"], + "group": row["group"], + "exclusion_reason": row["exclusion_reason"], + "unassisted": self.direct(row), + "first_hop": self.direct(row, row["q1"], row["bridge"]), + "second_hop": self.direct(row, row["q2"]), + "interventions": [], + } + if row["exclusion_reason"]: + result["seconds"] = time.monotonic() - started + result["resources"] = dict(self.stats - before_stats) + return result + caches, activations, lengths = {}, {}, {} + for name, bridge in [ + ("correct", row["bridge"]), + ("corrupt", row["corrupted_bridge"]), + ("wrong", row["control_bridge"]), + ]: + caches[name], activations[name], lengths[name] = self.prefill(prefix(row, bridge)) + if len(set(lengths.values())) != 1: + raise AssertionError("Token-length matching contract broken") + n = lengths["corrupt"] + if n != row["prefix_tokens"][self.key]: + raise AssertionError("Tokenizer revision changed the frozen prefix length") + result["oracle_input"] = self.finish(copy.deepcopy(caches["correct"]), n, row) + for layer in self.mc["layers"]: + baseline = None + for condition in self.cfg["conditions"]: + donor = "wrong" if condition.endswith("wrong") else "correct" + seed = int(order(row["id"] + str(layer))[:8], 16) + use_mlp = condition.startswith(("mlp_", "joint_")) + use_state = condition.startswith(("state_", "joint_")) + stats = {} + if use_mlp: + delta = activations[donor][layer] - activations["corrupt"][layer] + if condition.endswith("random"): + delta = matched_random(delta, seed) + replacement = ( + activations["corrupt"][layer] + delta + if condition.endswith("random") + else activations[donor][layer] + ) + stats["mlp_delta_norm"] = float(delta.norm()) + cache, _, _ = self.prefill( + prefix(row, row["corrupted_bridge"]), layer, replacement + ) + else: + cache = copy.deepcopy(caches["corrupt"]) + if use_state or condition == "identity": + source = caches["corrupt"] if condition == "identity" else caches[donor] + stats.update( + change_cache( + cache, source, layer, seed + 1 if condition.endswith("random") else None + ) + ) + prediction = self.finish(cache, n, row) + if condition == "baseline": + baseline = prediction + if condition == "identity": + if prediction["tokens"] != baseline["tokens"]: + raise AssertionError("Identity cache changed generated tokens") + if abs(prediction["scores"]["margin"] - baseline["scores"]["margin"]) > 1e-5: + raise AssertionError("Identity cache changed scores") + result["interventions"].append( + { + "layer": layer, + "condition": condition, + "cache_kind": self.mc["kind"], + **stats, + **prediction, + } + ) + result["seconds"] = time.monotonic() - started + result["resources"] = dict(self.stats - before_stats) + return result + + def prompt_suffix_ids(self, prompt): + # Match prefill(prompt) followed by finish(suffix), including BPE boundaries. + return torch.cat([self.ids(prompt), self.ids(self.cfg["suffix"])], dim=1) + + def next_logits(self, prompt): + ids = self.prompt_suffix_ids(prompt) + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += ids.numel() + if torch.is_grad_enabled(): + self.stats["backward_input_tokens"] += ids.numel() + return self.model(input_ids=ids, use_cache=False, logits_to_keep=1).logits[0, -1] + + def target_loss(self, row): + x = self.prompt_suffix_ids(base_prompt(row, row["q1"])) + target = self.tok.encode(" " + row["bridge"], add_special_tokens=False) + [self.eos] + y = torch.tensor([target], device=self.device) + inputs = torch.cat([x, y[:, :-1]], dim=1) + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += inputs.numel() + self.stats["backward_input_tokens"] += inputs.numel() + self.stats["supervised_tokens"] += y.numel() + logits = self.model(input_ids=inputs, use_cache=False, logits_to_keep=len(target)).logits + return torch.nn.functional.cross_entropy(logits.flatten(0, 1), y.flatten()) + + def learning(self, episode, output_dir): + before_stats = self.stats.copy() + lc = self.cfg["local_learning"] + pools = read(DATA / "learning.json") + target = pools["E"][episode] + parameter = self.layers[lc["layer"]].mlp.down_proj.weight + original = parameter.detach().clone() + teacher = {} + for role in ["R", "U"]: + with torch.no_grad(): + teacher[role] = [ + self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1).detach() + for r in pools[role] + ] + result = {"episode": episode, "target_id": target["id"], "nodes": [], "training": []} + started = time.monotonic() + try: + parameter.requires_grad_(True) + optimizer = torch.optim.SGD([parameter], lr=lc["lr"]) + for step in range(lc["steps"] + 1): + if step in lc["nodes"]: + node = { + "step": step, + "E": self.direct(target, target["q1"], target["bridge"]), + "D": self.direct(target), + "R": [], + "U": [], + "parameter_delta_norm": float((parameter.detach() - original).norm()), + } + for role in ["R", "U"]: + for r, old_lp in zip(pools[role], teacher[role], strict=True): + r = dict(r, competitor=target["bridge"]) + with torch.no_grad(): + lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) + kl = float((old_lp.exp() * (old_lp - lp)).sum()) + node[role].append( + { + "id": r["id"], + "kl": kl, + **self.direct(r, r["q1"], r["bridge"]), + } + ) + result["nodes"].append(node) + write(output_dir / "progress.json", result) + if step == lc["steps"]: + break + optimizer.zero_grad(set_to_none=True) + loss = self.target_loss(target) + target_value = float(loss.detach()) + loss.backward() + replay_value = 0.0 + for r, old_lp in zip(pools["R"], teacher["R"], strict=True): + lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) + kl = (old_lp.exp() * (old_lp - lp)).sum() + replay_value += float(kl.detach()) / len(pools["R"]) + (lc["replay_KL_weight"] * kl / len(pools["R"])).backward() + norm = float(torch.nn.utils.clip_grad_norm_([parameter], lc["gradient_clip"])) + if not np.isfinite(target_value + replay_value + norm): + raise FloatingPointError("Nonfinite local learning response") + optimizer.step() + result["training"].append( + { + "step": step + 1, + "target_ce": target_value, + "R_kl": replay_value, + "gradient_norm": norm, + } + ) + torch.save( + { + "down_weight": parameter.detach().cpu(), + "target_id": target["id"], + "layer": lc["layer"], + "steps": lc["steps"], + }, + output_dir / "endpoint.pt", + ) + finally: + with torch.no_grad(): + parameter.copy_(original) + parameter.requires_grad_(False) + if not torch.equal(parameter, original): + raise AssertionError("Episode failed to restore original weight") + result["seconds"] = time.monotonic() - started + result["restored_original"] = True + result["resources"] = dict(self.stats - before_stats) + return result diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/architecture_bridge_toy.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/architecture_bridge_toy.py new file mode 100644 index 0000000000000000000000000000000000000000..a406337c9f1b455c1c07183ec90de18541f7d03b --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/architecture_bridge_toy.py @@ -0,0 +1,410 @@ +"""A frozen small GQA / gated-delta mechanism experiment. + +Both models use RMSNorm, SwiGLU and tied token embeddings. The hybrid is a +deliberately small mechanism model, NOT an implementation of any Qwen release. +Its delta mixer has a genuine recurrent matrix, causal q/k/v convolution, +normalized q/k, input-dependent decay/write gates, and a headwise output gate. +""" + +from __future__ import annotations + +import hashlib +import math +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from llm_memory_editability.twohop_depth import BOS, ENTITY, EOS + + +class RMSNorm(nn.Module): + def __init__(self, width, eps): + super().__init__() + self.weight = nn.Parameter(torch.ones(width)) + self.eps = eps + + def forward(self, x): + return x * torch.rsqrt(x.square().mean(-1, keepdim=True) + self.eps) * self.weight + + +def rope(x, offset): + """Full rotary position embedding; head width is even.""" + width = x.shape[-1] + positions = torch.arange(offset, offset + x.shape[-2], device=x.device, dtype=x.dtype) + inverse = 10000.0 ** (-torch.arange(0, width, 2, device=x.device, dtype=x.dtype) / width) + phase = positions[:, None] * inverse[None, :] + even, odd = x[..., 0::2], x[..., 1::2] + return torch.stack( + (even * phase.cos() - odd * phase.sin(), even * phase.sin() + odd * phase.cos()), + dim=-1, + ).flatten(-2) + + +class GQA(nn.Module): + def __init__(self, cfg): + super().__init__() + width, self.heads, self.kv_heads = cfg["width"], cfg["heads"], cfg["kv_heads"] + self.dim = width // self.heads + self.q = nn.Linear(width, width, bias=False) + self.k = nn.Linear(width, self.kv_heads * self.dim, bias=False) + self.v = nn.Linear(width, self.kv_heads * self.dim, bias=False) + self.out = nn.Linear(width, width, bias=False) + self.q_norm = RMSNorm(self.dim, cfg["norm_eps"]) + self.k_norm = RMSNorm(self.dim, cfg["norm_eps"]) + + def forward(self, x, cache=None): + batch, length, width = x.shape + offset = 0 if cache is None else cache["k"].shape[2] + q = self.q(x).view(batch, length, self.heads, self.dim).transpose(1, 2) + k = self.k(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) + v = self.v(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) + q, k = rope(self.q_norm(q), offset), rope(self.k_norm(k), offset) + if cache is not None: + k, v = torch.cat((cache["k"], k), 2), torch.cat((cache["v"], v), 2) + new_cache = {"k": k, "v": v} + repeat = self.heads // self.kv_heads + keys, values = k.repeat_interleave(repeat, 1), v.repeat_interleave(repeat, 1) + scores = (q @ keys.transpose(-2, -1)) / math.sqrt(self.dim) + allowed = ( + torch.arange(k.shape[2], device=x.device)[None, :] + <= torch.arange(offset, offset + length, device=x.device)[:, None] + ) + scores = scores.masked_fill(~allowed, float("-inf")) + out = (scores.softmax(-1) @ values).transpose(1, 2).reshape(batch, length, width) + return self.out(out), new_cache + + +class GatedDelta(nn.Module): + def __init__(self, cfg): + super().__init__() + width, self.heads = cfg["width"], cfg["heads"] + self.dim, self.kernel = width // self.heads, cfg["conv_kernel"] + self.qkv = nn.Linear(width, 3 * width, bias=False) + self.conv_weight = nn.Parameter(torch.empty(self.kernel, 3 * width)) + self.decay = nn.Linear(width, self.heads, bias=True) + self.write = nn.Linear(width, self.heads, bias=True) + self.gate = nn.Linear(width, self.heads, bias=True) + self.out_norm = RMSNorm(self.dim, cfg["norm_eps"]) + self.out = nn.Linear(width, width, bias=False) + + def forward(self, x, cache=None): + batch, length, width = x.shape + raw = self.qkv(x) + if cache is None: + history = raw.new_zeros(batch, self.kernel - 1, 3 * width) + state = raw.new_zeros(batch, self.heads, self.dim, self.dim) + else: + history, state = cache["conv"], cache["state"] + full = torch.cat((history, raw), 1) + convolved = sum(full[:, j : j + length] * self.conv_weight[j] for j in range(self.kernel)) + q, k, v = F.silu(convolved).chunk(3, -1) + q = F.normalize(q.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) + k = F.normalize(k.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) + v = v.view(batch, length, self.heads, self.dim) + alpha = torch.exp(-F.softplus(self.decay(x))) + beta, gate = self.write(x).sigmoid(), self.gate(x).sigmoid() + outputs = [] + for t in range(length): + # S_t = alpha S_(t-1)(I-beta kk^T) + beta vk^T. + state = alpha[:, t, :, None, None] * state + read_at_key = (state * k[:, t, :, None, :]).sum(-1) + error = v[:, t] - read_at_key + state = state + beta[:, t, :, None, None] * (error[..., :, None] * k[:, t, :, None, :]) + outputs.append((state * q[:, t, :, None, :]).sum(-1)) + out = self.out_norm(torch.stack(outputs, 1)) * gate[..., None] + new_cache = {"conv": full[:, -(self.kernel - 1) :], "state": state} + return self.out(out.reshape(batch, length, width)), new_cache + + +class SwiGLU(nn.Module): + def __init__(self, cfg): + super().__init__() + self.up = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) + self.gate = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) + self.down = nn.Linear(cfg["mlp_hidden"], cfg["width"], bias=False) + + def forward(self, x): + return self.down(self.up(x) * F.silu(self.gate(x))) + + +class Block(nn.Module): + def __init__(self, kind, cfg): + super().__init__() + self.norm_mixer = RMSNorm(cfg["width"], cfg["norm_eps"]) + self.mixer = GQA(cfg) if kind == "gqa" else GatedDelta(cfg) + self.norm_mlp = RMSNorm(cfg["width"], cfg["norm_eps"]) + self.mlp = SwiGLU(cfg) + + +def apply_patch(output, patch): + if patch is None: + return output + result = output.clone() + result[:, patch["positions"]] = patch["value"].to(output) + return result + + +class ToyLM(nn.Module): + def __init__(self, architecture, cfg): + super().__init__() + self.config = cfg + self.architecture = architecture + self.token = nn.Embedding(ENTITY + cfg["entities"] + cfg["relations"], cfg["width"]) + self.blocks = nn.ModuleList(Block(kind, cfg) for kind in architecture["mixers"]) + self.norm_final = RMSNorm(cfg["width"], cfg["norm_eps"]) + + def forward( + self, tokens, positions=None, *, cache=None, patches=None, capture=False, return_cache=False + ): + h, states, trace = self.token(tokens), [], {} + patches = {} if patches is None else patches + for layer, block in enumerate(self.blocks): + past = None if cache is None else cache[layer] + mixer, state = block.mixer(block.norm_mixer(h), past) + mixer = apply_patch(mixer, patches.get(("mixer", layer))) + h = h + mixer + mlp = apply_patch(block.mlp(block.norm_mlp(h)), patches.get(("mlp", layer))) + h = h + mlp + states.append(state) + if capture: + trace[("mixer", layer)], trace[("mlp", layer)] = mixer, mlp + h = self.norm_final(h) + if positions is not None: + h = h[torch.arange(len(h), device=h.device)[:, None], positions] + logits = F.linear(h, self.token.weight) + return (logits, states, trace) if capture or return_cache else logits + + +def initialize(model, seed): + """Pair every common named and shaped parameter without RNG-order effects.""" + with torch.no_grad(): + for name, parameter in model.named_parameters(): + if name.endswith(".bias"): + parameter.zero_() + elif "norm" in name and name.endswith(".weight"): + parameter.fill_(1) + else: + key = hashlib.sha256(f"{seed}:{name}".encode()).digest() + generator = torch.Generator().manual_seed(int.from_bytes(key[:8], "little")) + std = 0.02 + if name.endswith("mixer.out.weight") or name.endswith("mlp.down.weight"): + std /= math.sqrt(2 * len(model.blocks)) + parameter.copy_(torch.randn(parameter.shape, generator=generator) * std) + + +def parameter_digest(model): + h = hashlib.sha256() + for name, parameter in model.named_parameters(): + h.update(name.encode()) + h.update(parameter.detach().cpu().contiguous().numpy().tobytes()) + return h.hexdigest() + + +def exposure(cfg, steps): + count = cfg["batch_per_kind"] * steps + return { + "steps": steps, + "atomic_examples": count, + "training_composite_examples": count, + "valid_input_tokens": count * 11, + "processed_tokens_including_padding": count * 12, + "supervised_answer_eos_tokens": count * 4, + } + + +def flops_estimate(model, cfg, steps): + """Conventional 6*N*T estimate plus transparent small mixer correction.""" + params = sum(p.numel() for p in model.parameters()) + tokens = exposure(cfg, steps)["processed_tokens_including_padding"] + n_gqa = model.architecture["mixers"].count("gqa") + n_delta = model.architecture["mixers"].count("delta") + length, width, heads = 6, cfg["width"], cfg["heads"] + dim = width // heads + mixing = tokens * (n_gqa * 12 * length * width + n_delta * 24 * heads * dim * dim) + return { + "parameter_count": params, + "conventional_6_parameter_token_flops": 6 * params * tokens, + "additional_mixing_flops_approx": mixing, + "total_approx": 6 * params * tokens + mixing, + "limitation": ( + "Rough training estimate, not profiler measurements; 6NT includes embeddings " + "and excludes detailed normalization/activation costs." + ), + } + + +@torch.no_grad() +def generate(model, x, y, device, batch=128, patches=None): + result = {key: [] for key in ("pred", "eos", "logp", "logits")} + for start in range(0, len(x), batch): + tokens = torch.as_tensor(x[start : start + batch], device=device) + target = torch.as_tensor(y[start : start + batch], device=device) + part = None + if patches is not None: + part = { + key: { + "positions": value["positions"], + "value": value["value"][start : start + batch], + } + for key, value in patches.items() + } + logits = model(tokens, patches=part)[:, -1] + prediction = logits.argmax(-1) + stop = model(torch.cat((tokens, prediction[:, None]), 1), patches=part)[:, -1].argmax(-1) + result["pred"].append(prediction.cpu().numpy()) + result["eos"].append(stop.cpu().numpy()) + result["logp"].append(logits.log_softmax(-1).gather(1, target[:, None]).cpu().numpy()[:, 0]) + result["logits"].append(logits.cpu().numpy()) + return {key: np.concatenate(value) for key, value in result.items()} + + +@torch.no_grad() +def evaluate(model, world, cfg, device): + model.eval() + arrays, metrics = {}, {} + for name, key, mask in ( + ("atomic", "atomic", slice(None)), + ("train", "composite", world["train_mask"]), + ("test", "composite", ~world["train_mask"]), + ): + x, y = world[key + "_x"][mask], world[key + "_y"][mask] + output = generate(model, x, y, device, cfg["eval_batch"]) + for field, value in output.items(): + arrays[f"{name}_{field}"] = value + correct = (output["pred"] == y) & (output["eos"] == EOS) + metrics[name] = { + "n": len(y), + "answer_accuracy": float(np.mean(output["pred"] == y)), + "exact_answer_eos": float(correct.mean()), + "answer_nll": float(-output["logp"].mean()), + } + indices = np.flatnonzero(~world["train_mask"]) + a, r1, r2 = world["comps"][indices].T + bridge = arrays["atomic_pred"][a * cfg["relations"] + r1] + bridge_eos = arrays["atomic_eos"][a * cfg["relations"] + r1] + second = np.c_[np.full(len(a), BOS), bridge, ENTITY + cfg["entities"] + r2] + y = world["composite_y"][indices] + output = generate(model, second, y, device, cfg["eval_batch"]) + arrays.update({f"two_call_{field}": value for field, value in output.items()}) + arrays["two_call_bridge"], arrays["two_call_bridge_eos"] = bridge, bridge_eos + correct = (output["pred"] == y) & (output["eos"] == EOS) & (bridge_eos == EOS) + metrics["two_call"] = {"n": len(y), "exact_answer_eos": float(correct.mean())} + atom_ok = (arrays["atomic_pred"] == world["atomic_y"]) & (arrays["atomic_eos"] == EOS) + gold_bridge = world["maps"][r1, a] + both = atom_ok[a * cfg["relations"] + r1] & atom_ok[gold_bridge * cfg["relations"] + r2] + direct_ok = (arrays["test_pred"] == y) & (arrays["test_eos"] == EOS) + arrays["test_both_atoms_correct"] = both + metrics["test_given_both_atoms"] = { + "n": int(both.sum()), + "coverage": float(both.mean()), + "exact_answer_eos": float(direct_ok[both].mean()) if both.any() else None, + } + return metrics, arrays + + +def intervention_conditions(traces, cfg, device): + """Same orthogonal transform for both donor norms; no fitted direction.""" + rng = np.random.default_rng(cfg["random_control_seed"]) + perm = torch.as_tensor(rng.permutation(cfg["width"]), device=device) + signs = torch.as_tensor(rng.choice([-1.0, 1.0], cfg["width"]), device=device) + sites = { + "mlp": (cfg["mlp_layer"], cfg["mlp_position"]), + "mixer": (cfg["mixer_layer"], cfg["mixer_position"]), + } + conditions, norms = {}, {} + for target in cfg["patch_targets"]: + kinds = ("mlp", "mixer") if target == "joint" else (target,) + for donor in cfg["patch_donors"]: + patches, measurements = {}, {} + for kind in kinds: + layer, position = sites[kind] + base = traces["identity"][(kind, layer)][:, [position]] + source = donor.replace("random_", "") + delta = traces[source][(kind, layer)][:, [position]] - base + if donor.startswith("random_"): + delta = delta[..., perm] * signs.to(delta) + patches[(kind, layer)] = {"positions": [position], "value": base + delta} + measurements[kind] = delta.flatten(1).norm(dim=-1).cpu().numpy() + key = f"{target}_{donor}" + conditions[key], norms[key] = patches, measurements + return conditions, norms + + +@torch.no_grad() +def diagnostics(model, world, cfg, device): + model.eval() + cases = world["cases"] + query = world["composite_x"][cases[:, 0]] + correct = np.c_[ + np.full(len(cases), BOS), + ENTITY + cases[:, 9], + ENTITY + cfg["entities"] + cases[:, 10], + ENTITY + cfg["entities"] + cases[:, 3], + ] + wrong = np.c_[ + np.full(len(cases), BOS), + ENTITY + cases[:, 6], + ENTITY + cfg["entities"] + cases[:, 2], + ENTITY + cfg["entities"] + cases[:, 3], + ] + traces = {} + for key, x in (("identity", query), ("correct", correct), ("wrong", wrong)): + _, _, traces[key] = model(torch.as_tensor(x, device=device), capture=True) + conditions, norms = intervention_conditions(traces, cfg, device) + target, competitor = ENTITY + cases[:, 5], ENTITY + cases[:, 8] + arrays = { + "case_ids": cases[:, 0], + "target": target, + "wrong_target": competitor, + "query": query, + "correct_donor": correct, + "wrong_donor": wrong, + } + baseline = generate(model, query, target, device, cfg["eval_batch"]) + base_ok = (baseline["pred"] == target) & (baseline["eos"] == EOS) + metrics = {} + for name, patches in {"baseline": None, **conditions}.items(): + output = ( + baseline + if patches is None + else generate(model, query, target, device, cfg["eval_batch"], patches) + ) + for field, value in output.items(): + arrays[f"{name}_{field}"] = value + row = np.arange(len(target)) + margin = output["logits"][row, target] - output["logits"][row, competitor] + arrays[f"{name}_margin"] = margin + exact = (output["pred"] == target) & (output["eos"] == EOS) + wrong_ok = (output["pred"] == competitor) & (output["eos"] == EOS) + metrics[name] = { + "n": len(target), + "correct_exact": float(exact.mean()), + "wrong_exact": float(wrong_ok.mean()), + "rescued": int((exact & ~base_ok).sum()), + "damaged": int((~exact & base_ok).sum()), + "baseline_correct_n": int(base_ok.sum()), + "baseline_incorrect_n": int((~base_ok).sum()), + "mean_correct_minus_wrong_margin": float(margin.mean()), + "max_logit_change": float(np.max(np.abs(output["logits"] - baseline["logits"]))), + } + for kind, value in norms.get(name, {}).items(): + arrays[f"{name}_{kind}_norm"] = value + # Functional interaction in the 2x2 channel intervention, not an attribution percentage. + for donor in ("correct", "wrong", "random_correct", "random_wrong"): + interaction = ( + arrays[f"joint_{donor}_margin"] + - arrays[f"mlp_{donor}_margin"] + - arrays[f"mixer_{donor}_margin"] + + arrays["baseline_margin"] + ) + arrays[f"interaction_{donor}"] = interaction + return metrics, arrays + + +def save_npz(path, arrays): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed(path, **arrays) diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_analysis.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae07fb7fccdec9430d5e69bc1b304a9fcebe914 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_analysis.py @@ -0,0 +1,399 @@ +"""Audit saved edit predictions and describe failures without selecting successes.""" + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from .bios_data import N_BASE, RELATIONS, load_world, write_json + +RETENTION_GROUPS = ("0", "1", "2", "3", "2_base", "2_derived") + + +def read(path): + return json.loads(path.read_text()) + + +def failure_flags(point, accuracy=0.95, damage=0.01): + rates = [point["U_heldout_destruction"][g]["rate"] for g in RETENTION_GROUPS] + return { + "E": point["E_root"] < 1 or point["E_member"] < accuracy, + "D": point["D"] < accuracy, + "U": any(r is not None and r > damage for r in rates), + "unevaluable": any(r is None for r in rates), + } + + +def failure_signature(flags): + if flags["unevaluable"]: + return "unevaluable" + return "+".join(k for k in ("E", "D", "U") if flags[k]) or "pass" + + +def propagation_errors(world, sets, prediction): + ids = sets["D"] + value, ended = prediction["prediction"][ids], prediction["ended"][ids] + target = sets["target"][ids] + actual = sets["target"][2112 + world.person[ids]] + correct = (value == target) & ended + remaining = ~correct + counts = {"correct": int(correct.sum())} + for name, mask in ( + ("nontermination", ~ended), + ("old_default", value == world.answers[ids]), + ("personal_city_instead_of_company_default", value == actual), + ): + counts[name] = int((remaining & mask).sum()) + remaining &= ~mask + counts["other_wrong_value"] = int(remaining.sum()) + assert sum(counts.values()) == len(ids) + strata = {} + old_exception = world.exceptions[world.person[ids]] + for name, mask in ( + ("old_exception", old_exception), + ("updated_personal_equals_default", ~old_exception & (actual == target)), + ("updated_personal_differs_from_default", ~old_exception & (actual != target)), + ): + strata[name] = {"n": int(mask.sum()), "correct": int(correct[mask].sum())} + return {"counts": counts, "strata": strata} + + +def retention_masks(sets, old_correct, view="heldout"): + eligible = old_correct.copy() + if view != "full": + selected = np.zeros(len(eligible), dtype=bool) + selected[sets[view]] = True + eligible &= selected + masks = {str(g): eligible & (sets["strata"] == g) for g in range(4)} + masks["2_base"] = masks["2"] & (np.arange(len(eligible)) < N_BASE) + masks["2_derived"] = masks["2"] & (np.arange(len(eligible)) >= N_BASE) + return masks + + +def retention_counts(sets, correct, old_correct, view="heldout"): + return { + group: { + "known": int(mask.sum()), + "broken": int((mask & ~correct).sum()), + "rate": float((~correct[mask]).mean()) if mask.any() else None, + } + for group, mask in retention_masks(sets, old_correct, view).items() + } + + +def dump_csv(path, rows): + if not rows: + return + with path.open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def summarize_group(cases): + n = len(cases) + result = {"n": n} + for field in ("E", "E_root", "E_member", "D", "U_accuracy", "E_target_value_nll"): + result[f"mean_{field}"] = float(np.mean([c["final"][field] for c in cases])) + result.update( + final_pass=sum(c["final"]["joint_pass"] is True for c in cases), + ever_pass=sum(c["first_observed_joint_step"] is not None for c in cases), + regressed=sum( + c["first_observed_joint_step"] is not None and not c["final"]["joint_pass"] + for c in cases + ), + signatures=dict(Counter(c["failure_signature"] for c in cases)), + **{f"fail_{k}": sum(c["failure_flags"][k] for c in cases) for k in ("E", "D", "U")}, + ) + for g in RETENTION_GROUPS: + rates = [c["final"]["U_heldout_destruction"][g]["rate"] for c in cases] + result[f"fail_U{g}"] = sum(r is not None and r > 0.01 for r in rates) + result[f"mean_U{g}_damage"] = float(np.mean([r for r in rates if r is not None])) + result["D_error_counts"] = dict( + sum((Counter(c["propagation"]["counts"]) for c in cases), Counter()) + ) + result["mean_initial_new_answer_nll"] = float(np.mean([c["initial_nll"] for c in cases])) + return result + + +def run(args): + root, out = Path(args.root), Path(args.output) + out.mkdir(parents=True, exist_ok=True) + worlds = {i: load_world(f"data/bios-work-v1/world-{i}") for i in (0, 1)} + cases, audit, timelines = [], [], [] + lookup = {} + for run_dir in sorted(root.glob("world-*-seed-*-*")): + config = read(run_dir / "config.json") + world = worlds[config["world_seed"]] + for dirname, window in (("edits", 3), ("edits-window0", 0)): + completed = read(run_dir / dirname / "complete.json") + assert completed["status"] == "complete" and len(completed["cases"]) == 16 + for path in sorted((run_dir / dirname).glob("*/complete.json")): + c = read(path) + assert c["status"] == "complete" and c["final"]["step"] == 512 + assert c["window_zero_based"] == list(range(window, window + 3)) + sets = dict(np.load(path.parent / "sets.npz")) + pred = dict(np.load(path.parent / "predictions-512.npz")) + correct = (pred["prediction"] == sets["target"]) & pred["ended"] + np.testing.assert_array_equal(correct, pred["correct"]) + retention = retention_counts(sets, correct, sets["old_correct"]) + assert retention == c["final"]["U_heldout_destruction"] + for name, ids in ( + ("E", sets["E"]), + ("D", sets["D"]), + ("E_root", sets["E"][world.relation[sets["E"]] == 1]), + ("E_member", sets["E"][world.relation[sets["E"]] == 2]), + ): + assert float(correct[ids].mean()) == c["final"][name] + trajectory = read(path.parent / "trajectory.json") + for point in trajectory: + flags = failure_flags(point) + expected = None if flags["unevaluable"] else not any(flags.values()) + assert point["joint_pass"] == expected + flags = failure_flags(c["final"]) + damaged_by_relation = {} + for group, mask in retention_masks(sets, sets["old_correct"]).items(): + broken = mask & ~correct + damaged_by_relation[group] = { + name: int((broken & (world.relation == relation)).sum()) + for relation, name in enumerate((*RELATIONS, "derived_default_city")) + } + assert sum(damaged_by_relation[group].values()) == int(broken.sum()) + method = f"FT-{c['scope'].upper()}" + if c["branch"]: + method += f"+{c['branch']}" + meta = { + "run": run_dir.name, + "world": world.seed, + "seed": config["seed"], + "order": config["order"], + "window": window, + "method": method, + "kind": c["kind"], + "support": c["support"], + } + c.update( + meta, + directory=str(path.parent), + failure_flags=flags, + failure_signature=failure_signature(flags), + heldout_damage_by_relation=damaged_by_relation, + propagation=propagation_errors(world, sets, pred), + replay_retention=retention_counts(sets, correct, sets["old_correct"], "replay"), + initial_nll=trajectory[0]["E_target_value_nll"], + ever_E=any(not failure_flags(p)["E"] for p in trajectory), + ever_D=any(not failure_flags(p)["D"] for p in trajectory), + ever_U=any(not failure_flags(p)["U"] for p in trajectory), + last_failure_free_E_step=max( + (p["step"] for p in trajectory if not failure_flags(p)["E"]), default=None + ), + down_calibration=c["final"].get("down_calibration"), + ) + cases.append(c) + lookup[(run_dir.name, window, method, c["kind"], c["support"])] = (c, sets, pred) + audit.append( + {"path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()} + ) + timelines.extend( + {**meta, **p, "failure_flags": failure_flags(p)} for p in trajectory + ) + assert len(cases) == 256 + groups = defaultdict(list) + for c in cases: + groups[(c["window"], c["method"], c["order"], c["kind"])].append(c) + aggregates = [ + {"window": w, "method": m, "order": o, "kind": k, **summarize_group(cs)} + for (w, m, o, k), cs in sorted(groups.items()) + ] + common, duplicates, branch_pairs = [], [], [] + for (run_name, window, method, kind, support), (case, sets, pred) in lookup.items(): + if case["order"] == "SA": + other, other_sets, other_pred = lookup[ + (run_name[:-2] + "AS", window, method, kind, support) + ] + for field in ( + "E", + "D", + "target", + "heldout", + "replay", + "strata", + "edit_sampling", + "replay_sampling", + ): + np.testing.assert_array_equal(sets[field], other_sets[field]) + known = sets["old_correct"] & other_sets["old_correct"] + sa = retention_counts(sets, pred["correct"], known) + ass = retention_counts(sets, other_pred["correct"], known) + common.append( + { + "world": case["world"], + "seed": case["seed"], + "window": window, + "method": method, + "kind": kind, + "support": support, + "SA": sa, + "AS": ass, + } + ) + if method == "FT-ALL" and window == 3: + _, _, duplicate = lookup[(run_name, 0, method, kind, support)] + duplicates.append( + { + "run": run_name, + "kind": kind, + "support": support, + "identical_final_predictions": bool( + all(np.array_equal(pred[k], duplicate[k]) for k in pred) + ), + } + ) + if case["branch"]: + baseline, _, baseline_pred = lookup[(run_name, window, "FT-MLP", kind, support)] + branch_pairs.append( + { + "run": run_name, + "window": window, + "method": method, + "kind": kind, + "support": support, + **{f"delta_{k}": case["final"][k] - baseline["final"][k] for k in ("E", "D")}, + "baseline_joint": baseline["final"]["joint_pass"], + "branch_joint": case["final"]["joint_pass"], + "changed_predictions_vs_baseline": int( + (pred["prediction"] != baseline_pred["prediction"]).sum() + ), + "max_value_nll_difference_vs_baseline": float( + np.max(np.abs(pred["value_nll"] - baseline_pred["value_nll"])) + ), + } + ) + sensitivity = [] + for (window, method, order, kind), cs in sorted(groups.items()): + for accuracy in (0.90, 0.95, 0.99): + for damage in (0.0, 0.01, 0.02, 0.05): + sensitivity.append( + { + "window": window, + "method": method, + "order": order, + "kind": kind, + "accuracy_threshold": accuracy, + "damage_threshold": damage, + "n": len(cs), + "final_pass": sum( + not any(failure_flags(c["final"], accuracy, damage).values()) + for c in cs + ), + } + ) + quality = [] + for world in (0, 1): + for seed in (0, 1): + sa, ass = [ + read(root / f"world-{world}-seed-{seed}-{order}" / "complete.json")["final"] + for order in ("SA", "AS") + ] + quality.append( + { + "world": world, + "seed": seed, + "base_difference_pp": 100 * (sa["base_accuracy"] - ass["base_accuracy"]), + "derived_difference_pp": 100 + * (sa["derived_accuracy"] - ass["derived_accuracy"]), + "passed": bool( + min( + sa["base_accuracy"], + ass["base_accuracy"], + sa["derived_accuracy"], + ass["derived_accuracy"], + ) + >= 0.99 + and abs(sa["base_accuracy"] - ass["base_accuracy"]) <= 0.005 + and abs(sa["derived_accuracy"] - ass["derived_accuracy"]) <= 0.005 + and abs(sa["value_nll"] - ass["value_nll"]) <= 0.1 + ), + } + ) + quality_keys = {(q["world"], q["seed"]) for q in quality if q["passed"]} + quality_aggregates = [] + for (w, m, o, k), cs in sorted(groups.items()): + subset = [c for c in cs if (c["world"], c["seed"]) in quality_keys] + quality_aggregates.append( + {"window": w, "method": m, "order": o, "kind": k, **summarize_group(subset)} + ) + report = { + "phase": "symbolic development; descriptive; not independent edit replicates", + "cases": cases, + "groups": aggregates, + "common_known_retention": common, + "branch_paired_support0": branch_pairs, + "ft_all_window_duplicates": duplicates, + "quality_pairs": quality, + "quality_subset_groups": quality_aggregates, + "sensitivity": sensitivity, + "source_audit": audit, + "expected_cases": 256, + "audited_cases": len(cases), + } + write_json(out / "failure-analysis.json", report) + write_json(out / "edit-trajectories.json", timelines) + dump_csv( + out / "failure-summary.csv", + [{k: v for k, v in row.items() if not isinstance(v, dict)} for row in aggregates], + ) + dump_csv(out / "threshold-sensitivity.csv", sensitivity) + dump_csv(out / "branch-paired-support0.csv", branch_pairs) + dump_csv( + out / "case-failures.csv", + [ + { + **{ + k: c[k] + for k in ( + "run", + "world", + "seed", + "order", + "window", + "method", + "kind", + "support", + "failure_signature", + "first_observed_joint_step", + "initial_nll", + ) + }, + **{k: c["final"][k] for k in ("E", "E_root", "E_member", "D", "joint_pass")}, + } + for c in cases + ], + ) + print( + json.dumps( + { + "audited_cases": len(cases), + "groups": len(aggregates), + "quality_pairs_passed": len(quality_keys), + "FT_ALL_identical_duplicate_cases": sum( + d["identical_final_predictions"] for d in duplicates + ), + } + ) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", default="results/bios-dev-v1") + parser.add_argument("--output", default="results/bios-dev-v1/failure-analysis-20260926") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_branch.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c6ebef8f0f501ac43d2d94de8f4f59b954208b --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_branch.py @@ -0,0 +1,127 @@ +"""Equal-parameter residual branches from old-world activation directions.""" + +import time + +import numpy as np +import torch +from torch import nn + +from .bios_data import ANS +from .bios_train import precision + + +class ResidualBranch(nn.Module): + def __init__(self, q, mean, scale, width=32, seed=73): + super().__init__() + self.register_buffer("q", q) + self.register_buffer("mean", mean) + self.register_buffer("scale", scale) + # Explicit local RNG: same A in all arms without changing training RNG state. + generator = torch.Generator(device=q.device).manual_seed(seed) + self.a = nn.Parameter( + torch.randn(width, q.shape[1], generator=generator, device=q.device) / q.shape[1] ** 0.5 + ) + self.b = nn.Parameter(torch.zeros(q.shape[0], width, device=q.device)) + + def forward(self, v): + s = (v.float() @ self.q - self.mean) / self.scale + return (torch.nn.functional.gelu(s @ self.a.T) @ self.b.T).to(v.dtype) + + +@torch.no_grad() +def build_bases(model, world, data, layer=4, rank=32): + device = data["tokens"].device + values = [] + + def capture(_module, _inputs, output): + values.append(output[:, 3].float()) + + handle = model.blocks[layer].register_forward_hook(capture) + started = time.perf_counter() + try: + with precision(device): + for begin in range(2112, 4160, 256): + model( + data["prompts"][begin : begin + 256], + data["lengths"][begin : begin + 256, None] - 1, + ) + finally: + handle.remove() + v = torch.cat(values) + group_means = torch.stack( + [v[torch.as_tensor(world.employers == c, device=device)].mean(0) for c in range(64)] + ) + centered_means = group_means - v.mean(0) + _, shared_s, shared_vh = torch.linalg.svd(centered_means, full_matrices=False) + q_shared = shared_vh[:rank].T.contiguous() + residual = v - group_means[torch.as_tensor(world.employers, device=device)] + residual = residual - (residual @ q_shared) @ q_shared.T + _, independent_s, independent_vh = torch.linalg.svd(residual, full_matrices=False) + q_independent = independent_vh[:rank].T.contiguous() + valid = bool( + shared_s[rank - 1] > shared_s[0] * 1e-6 + and independent_s[rank - 1] > independent_s[0] * 1e-6 + ) + if not valid: + return None, {"available": False, "reason": "fewer than 32 nondegenerate directions"} + generator = torch.Generator(device=device).manual_seed(74) + q_random = torch.linalg.qr(torch.randn(v.shape[1], rank, generator=generator, device=device)).Q + bases, checks = {}, {} + for kind, q in (("shared", q_shared), ("independent", q_independent), ("random", q_random)): + projected = v @ q + mean, std = projected.mean(0), projected.std(0, correction=0) + std = std.clamp_min(0.01 * std.square().mean().sqrt()) + normalized = (projected - mean) / std + # Equal total variance across all branches (one, not dependent on their rank). + scale = std * normalized.square().sum(-1).mean().sqrt() + bases[kind] = (q, mean, scale) + normalized = (projected - mean) / scale + within = [] + for c in range(64): + mask = (world.employers == c) & ~world.exceptions + z = normalized[torch.as_tensor(mask, device=device)] + within.append((z - z.mean(0)).square().sum(-1).mean().item()) + checks[kind] = { + "same_company_relation_old_answer_identity_variance": float(np.mean(within)), + "total_variance": normalized.square().sum(-1).mean().item(), + } + if device.type == "cuda": + torch.cuda.synchronize(device) + return bases, { + "available": True, + "construction_seconds": time.perf_counter() - started, + "rank": rank, + "shared_32nd_relative_singular_value": (shared_s[rank - 1] / shared_s[0]).item(), + "independent_32nd_relative_singular_value": ( + independent_s[rank - 1] / independent_s[0] + ).item(), + "checks": checks, + } + + +def attach_branch(model, basis, layer=4, width=32): + branch = ResidualBranch(*basis, width=width) + model.add_module("edit_branch", branch) + + def save_position(_module, args): + branch.positions = args[0].eq(ANS).long().argmax(-1) + + def add(_module, _inputs, output): + rows = torch.arange(len(output), device=output.device) + result = output.clone() + result[rows, branch.positions] = result[rows, branch.positions] + branch( + output[rows, branch.positions] + ) + return result + + handles = [ + model.register_forward_pre_hook(save_position), + model.blocks[layer].register_forward_hook(add), + ] + return branch, handles + + +def remove_branch(model, handles): + for handle in handles: + handle.remove() + delattr(model, "edit_branch") diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_capacity.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_capacity.py new file mode 100644 index 0000000000000000000000000000000000000000..d07d84eb1c19bc5055e15255b0de00799b8713c5 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_capacity.py @@ -0,0 +1,48 @@ +"""Predeclared splits and query-level capacity diagnostics.""" + +import numpy as np + +from .bios_data import N_BASE, N_QUERIES, rng_for + + +def qa_split(world, mode): + if mode == "all": + return np.arange(N_BASE, N_QUERIES), np.array([], dtype=np.int64) + if mode != "half": + raise ValueError("Unknown QA split") + rng = rng_for(world.seed, 910) + train, heldout = [], [] + for company in np.unique(world.employers): + for exception in (False, True): + people = np.flatnonzero((world.employers == company) & (world.exceptions == exception)) + people = rng.permutation(people) + train.extend((N_BASE + people[: len(people) // 2]).tolist()) + heldout.extend((N_BASE + people[len(people) // 2 :]).tolist()) + return np.sort(train), np.sort(heldout) + + +def split_metrics(world, arrays, train_ids, heldout_ids): + correct, nll = arrays["correct"], arrays["value_nll"] + # The derivation needs the person's employer and that employer's default city. + # Build by semantic IDs rather than assuming a base-fact row layout. + employer = {int(world.person[i]): i for i in np.flatnonzero(world.relation == 0)} + defaults = {int(world.company[i]): i for i in np.flatnonzero(world.relation == 1)} + result = {} + for name, ids in (("trained", train_ids), ("heldout", heldout_ids)): + result[f"derived_{name}_count"] = len(ids) + result[f"derived_{name}_accuracy"] = float(correct[ids].mean()) if len(ids) else None + result[f"derived_{name}_nll"] = float(nll[ids].mean()) if len(ids) else None + eligible = np.array( + [ + i + for i in ids + if correct[employer[int(world.person[i])]] + and correct[defaults[int(world.company[i])]] + ], + dtype=np.int64, + ) + result[f"derived_{name}_known_components_count"] = len(eligible) + result[f"derived_{name}_known_components_accuracy"] = ( + float(correct[eligible].mean()) if len(eligible) else None + ) + return result diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_causal_paths.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_causal_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2d8963ce2c5db80362fdd38cc80e83c8415b53 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_causal_paths.py @@ -0,0 +1,455 @@ +"""Offline donor-state interventions on frozen crossover models. + +Truth is used to match donor/recipient pairs and score outputs, never supplied as +an answer or bridge to the model. This is a causal diagnostic, not an editor. +""" + +import csv +import json +from pathlib import Path + +import numpy as np + +from .bios_cross import CHAINS, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_path_diagnostics import ( + INDISTINGUISHABLE, + classify_answers, + file_sha256, + free_generate_values, +) + +PAIR_TYPES = ( + "same_group_different_actual", + "different_group_same_actual_different_default", + "same_group_same_actual_different_person", + "different_group_different_actual_different_default", +) +POSITIONS = (2, 3, 4) +ANSWER_ROLES = ("recipient_default", "recipient_actual", "donor_default", "donor_actual") + + +def make_donor_plan(world, chain, per_population=64): + """Select using truth and train/heldout membership only, with fixed RNG. + + A missing donor stays -1. No prediction- or success-based replacement occurs. + The same world yields identical pairs across sizes, conditions and model seeds. + """ + heldout = world.person[world.heldout_ids[chain]] + train = world.person[world.train_ids[chain]] + rng = rng_for(world.seed, 971, chain) + recipients = [] + for exceptional in (False, True): + pool = heldout[world.exceptions[chain, heldout] == exceptional] + if len(pool) < per_population: + raise ValueError("Not enough heldout recipients for predeclared sample") + recipients.extend(rng.choice(pool, per_population, replace=False)) + recipients = np.asarray(recipients, dtype=np.int64) + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + recipient_rows, donor_rows, type_rows, candidate_counts = [], [], [], [] + for recipient in recipients: + same_group = group[train] == group[recipient] + same_actual = actual[train] == actual[recipient] + same_default = default[train] == default[recipient] + masks = ( + same_group & ~same_actual, + ~same_group & same_actual & ~same_default, + same_group & same_actual & (train != recipient), + ~same_group & ~same_actual & ~same_default, + ) + for pair_type, mask in enumerate(masks): + candidates = train[mask] + recipient_rows.append(recipient) + donor_rows.append(rng.choice(candidates) if len(candidates) else -1) + type_rows.append(pair_type) + candidate_counts.append(len(candidates)) + donor_rows = np.asarray(donor_rows, dtype=np.int64) + complete = (donor_rows.reshape(-1, len(PAIR_TYPES)) >= 0).all(axis=1) + return { + "case_id": np.arange(len(donor_rows), dtype=np.int64), + "recipient": np.asarray(recipient_rows, dtype=np.int64), + "donor": donor_rows, + "pair_type": np.asarray(type_rows, dtype=np.int8), + "candidate_count": np.asarray(candidate_counts, dtype=np.int32), + "common_recipient": np.repeat(complete, len(PAIR_TYPES)), + "recipient_old_exception": world.exceptions[chain, recipient_rows], + } + + +def intervention_state(recipient_state, donor_state, intervention, seed): + """Random control matches the donor-minus-recipient perturbation norm per row.""" + if recipient_state.shape != donor_state.shape: + raise ValueError("Activation shapes do not match") + delta = donor_state.astype(np.float64) - recipient_state.astype(np.float64) + norms = np.linalg.norm(delta, axis=-1) + if intervention == "donor": + patched = donor_state.copy() + elif intervention == "sham": + patched = recipient_state.copy() + elif intervention == "matched_random": + noise = np.random.default_rng(seed).standard_normal(delta.shape) + noise /= np.maximum(np.linalg.norm(noise, axis=-1, keepdims=True), 1e-30) + patched = (recipient_state + noise * norms[:, None]).astype(recipient_state.dtype) + else: + raise ValueError("Unknown intervention") + actual_norms = np.linalg.norm(patched.astype(np.float64) - recipient_state, axis=-1) + return patched, norms, actual_norms + + +def cache_clean_states(model, prompts, lengths, device, batch_size=256): + """Capture post-block residuals at fixed positions for clean prompt passes.""" + import torch + + from .bios_train import precision + + states = [[] for _ in model.blocks] + hooks = [] + for layer, block in enumerate(model.blocks): + + def capture(module, inputs, output, layer=layer): + states[layer].append(output[:, POSITIONS, :].detach().float().cpu().numpy()) + + hooks.append(block.register_forward_hook(capture)) + model.eval() + try: + with torch.no_grad(): + for start in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[start : start + batch_size], device=device) + n = torch.as_tensor(lengths[start : start + batch_size], device=device) + with precision(device): + model(p, (n - 1)[:, None]) + finally: + for hook in hooks: + hook.remove() + return np.stack([np.concatenate(layer_states) for layer_states in states]) + + +def generate_with_state_patch( + model, prompts, lengths, replacements, layer, position, device, batch_size=256 +): + """Apply the same pre-answer state patch in value and EOS generation passes. + + Positions <= 4 cannot depend on the generated token at position 5 under the + causal mask, so the clean prompt cache contains no teacher-forced answer. + """ + import torch + + from .bios_train import precision + + if position not in POSITIONS or np.any(lengths != 5): + raise ValueError("This diagnostic is restricted to five-token derived queries") + predictions, ended = [], [] + model.eval() + with torch.no_grad(): + for start in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[start : start + batch_size], device=device) + n = torch.as_tensor(lengths[start : start + batch_size], device=device) + replacement = torch.as_tensor(replacements[start : start + batch_size], device=device) + + def patch(module, inputs, output, replacement=replacement): + changed = output.clone() + changed[:, position] = replacement.to(output.dtype) + return changed + + hook = model.blocks[layer].register_forward_hook(patch) + try: + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), device=device, dtype=torch.long) + continuation[:, :5] = p + continuation[:, 5] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + finally: + hook.remove() + return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)} + + +def _candidate_values(world, chain, recipients, donors): + default = world.answers[world.root_ids[chain, world.memberships[chain]]] + actual = world.answers[world.actual_ids[chain]] + return np.column_stack( + [default[recipients], actual[recipients], default[donors], actual[donors]] + ) + + +def _node_rows(arrays, identity): + rows = [] + for pair_type, label in enumerate(PAIR_TYPES): + for population in ("all", "ordinary", "old_exception"): + for common_only in (False, True): + selected = arrays["pair_type"] == pair_type + if population != "all": + selected &= arrays["recipient_old_exception"] == (population == "old_exception") + if common_only: + selected &= arrays["common_recipient"] + n = int(selected.sum()) + before = arrays["baseline_correct"][selected] + after = arrays["correct"][selected] + row = { + **identity, + "pair_type": label, + "population": population, + "common_recipients_only": common_only, + "n": n, + "baseline_correct": int(before.sum()), + "correct": int(after.sum()), + "known_became_wrong": int((before & ~after).sum()), + "wrong_became_correct": int((~before & after).sum()), + "termination_error": int((~arrays["ended"][selected]).sum()), + "prediction_changed": int( + ( + arrays["prediction"][selected] + != arrays["baseline_prediction"][selected] + ).sum() + ), + "indistinguishable": int( + (arrays["class_code"][selected] == INDISTINGUISHABLE).sum() + ), + "mean_perturbation_norm": float(arrays["perturbation_norm"][selected].mean()) + if n + else None, + } + for i, role in enumerate(ANSWER_ROLES): + row[f"matches_{role}"] = int( + ( + ((arrays["matched_role_bits"][selected] & (1 << i)) != 0) + & arrays["ended"][selected] + ).sum() + ) + rows.append(row) + return rows + + +def diagnose_causal_run(run, output, step=15360, device="cuda", batch_size=256, per_population=64): + """One model, both relations, all layers/positions with fixed donor controls.""" + import torch + + from .bios_model import CausalLM, ModelConfig + from .bios_organization_train import atomic_numpy_save + + repository = Path(__file__).resolve().parents[2] + run, output = Path(run).resolve(), Path(output).resolve() + if output == run or run in output.parents: + raise ValueError("Never write causal diagnostics inside frozen training runs") + output.mkdir(parents=True, exist_ok=True) + config = json.loads((run / "config.json").read_text()) + if config["world"] not in (0, 1) or config["model"]["width"] not in (256, 768): + raise ValueError("This development diagnostic is frozen to worlds 0/1, widths 256/768") + checkpoint = run / f"model-{step}.pt" + device = torch.device(device) + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if array_hash(world.answers) != config["truth_sha256"]: + raise ValueError("World truth mismatch") + identity = { + "run": str(run), + "checkpoint": str(checkpoint), + "step": step, + "checkpoint_sha256": file_sha256(checkpoint), + "config_sha256": file_sha256(run / "config.json"), + "diagnostic_source_sha256": file_sha256(__file__), + "generation_helper_sha256": file_sha256( + repository / "src/llm_memory_editability/bios_path_diagnostics.py" + ), + "world": config["world"], + "seed": config["seed"], + "condition": config["condition"], + "width": config["model"]["width"], + "per_population": per_population, + "positions": list(POSITIONS), + "device_type": device.type, + "batch_size": batch_size, + "torch": torch.__version__, + "offline_truth_matching": True, + "role": "candidate_localization" if config["world"] == 0 else "development_replication", + } + config_path = output / "config.json" + if config_path.exists(): + if json.loads(config_path.read_text()) != identity: + raise ValueError("Causal diagnostic identity changed") + else: + write_json(config_path, identity) + if (output / "complete.json").exists(): + return + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + rows, plan_rows = [], [] + source_output_hashes = {} + for chain, name in enumerate(CHAINS): + dest = output / name + dest.mkdir(exist_ok=True) + plan = make_donor_plan(world, chain, per_population) + plan_path = dest / "plan.npz" + if plan_path.exists(): + with np.load(plan_path) as existing: + if any(not np.array_equal(existing[k], v) for k, v in plan.items()): + raise ValueError("Saved donor plan differs") + else: + atomic_numpy_save(plan_path, **plan) + source_output_hashes[str(plan_path.relative_to(output))] = file_sha256(plan_path) + valid = plan["donor"] >= 0 + selected = {k: v[valid] for k, v in plan.items()} + recipients, donors = selected["recipient"], selected["donor"] + for pair_type, label in enumerate(PAIR_TYPES): + for exceptional in (False, True): + matching = (plan["pair_type"] == pair_type) & ( + plan["recipient_old_exception"] == exceptional + ) + plan_rows.append( + { + "chain": name, + "pair_type": label, + "population": "old_exception" if exceptional else "ordinary", + "requested": int(matching.sum()), + "valid": int((matching & valid).sum()), + "missing": int((matching & ~valid).sum()), + } + ) + people = np.unique(np.concatenate([recipients, donors])) + ids = world.derived_ids[chain, people] + cache_path = dest / "clean-cache.npz" + if cache_path.exists(): + with np.load(cache_path) as cache: + states = cache["states"] + baseline = {k: cache[k] for k in ("prediction", "ended")} + if not np.array_equal(cache["people"], people): + raise ValueError("Clean cache people mismatch") + else: + states = cache_clean_states( + model, world.prompts[ids], world.lengths[ids], device, batch_size + ) + baseline = free_generate_values( + model, world.prompts[ids], world.lengths[ids], device, batch_size + ) + atomic_numpy_save(cache_path, people=people, states=states, **baseline) + source_output_hashes[str(cache_path.relative_to(output))] = file_sha256(cache_path) + ri, di = np.searchsorted(people, recipients), np.searchsorted(people, donors) + recipient_queries = world.derived_ids[chain, recipients] + candidates = _candidate_values(world, chain, recipients, donors) + base = { + **selected, + "recipient_query": recipient_queries, + "donor_query": world.derived_ids[chain, donors], + "candidate_tokens": candidates, + "baseline_prediction": baseline["prediction"][ri], + "baseline_ended": baseline["ended"][ri], + "baseline_correct": (baseline["prediction"][ri] == candidates[:, 0]) + & baseline["ended"][ri], + } + for layer in range(len(model.blocks)): + for position_index, position in enumerate(POSITIONS): + receiver_states = states[layer, ri, position_index] + donor_states = states[layer, di, position_index] + seed = [world.seed, 972, chain, layer, position] + for intervention in ("donor", "matched_random", "sham"): + node = dest / f"layer-{layer}-position-{position}-{intervention}.npz" + if node.exists(): + with np.load(node) as existing: + arrays = dict(existing) + if not np.array_equal(arrays["case_id"], selected["case_id"]): + raise ValueError("Saved node case mismatch") + else: + replacement, donor_norm, actual_norm = intervention_state( + receiver_states, donor_states, intervention, seed + ) + generated = generate_with_state_patch( + model, + world.prompts[recipient_queries], + world.lengths[recipient_queries], + replacement, + layer, + position, + device, + batch_size, + ) + classes, bits = classify_answers( + generated["prediction"], generated["ended"], candidates + ) + arrays = { + **base, + **generated, + "class_code": classes, + "matched_role_bits": bits, + "correct": (generated["prediction"] == candidates[:, 0]) + & generated["ended"], + "donor_delta_norm": donor_norm, + "perturbation_norm": actual_norm, + } + atomic_numpy_save(node, **arrays) + source_output_hashes[str(node.relative_to(output))] = file_sha256(node) + node_identity = { + "world": world.seed, + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "chain": name, + "layer": layer, + "position": position, + "intervention": intervention, + "terminal_control": layer == len(model.blocks) - 1, + } + rows.extend(_node_rows(arrays, node_identity)) + print( + json.dumps( + { + "event": "causal_node_complete", + "run": str(run), + "chain": name, + "layer": layer, + "position": position, + } + ), + flush=True, + ) + for filename, contents in (("summary.csv", rows), ("pair-coverage.csv", plan_rows)): + with (output / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + output / "schema.json", + { + "pair_types": PAIR_TYPES, + "answer_roles": ANSWER_ROLES, + "state": "post-transformer-block residual stream", + "positions": { + "2": "membership relation", + "3": "default relation", + "4": "answer marker", + }, + "world_roles": { + "0": "candidate localization", + "1": "development replication, not confirmation", + }, + "random_control": "Random vector matched per case to ||donor_state-recipient_state||_2", + "matching": "True group/actual/default answers select pairs offline; prompts contain " + "no true answer or true bridge entity.", + "missing": "No donor replacement across types; no prediction-based recipient selection", + "common_recipients": "Auxiliary rows require all four donor types; truth-selected", + "last_layer_controls": "Positions 2/3 cannot affect other tokens after final block; " + "position 4 directly changes value readout and is not routing evidence.", + "causal_scope": "Single-state replacement establishes an intervention effect, not a " + "unique mechanism or strict necessity. Same-point restoration equals sham.", + "eos": "Value and EOS are independently generated with identical intervention; " + "non-terminated values are failures even if an answer candidate matches.", + "overlap": "All matched roles retained; multiple roles remain indistinguishable", + }, + ) + write_json(output / "artifacts.json", source_output_hashes) + write_json( + output / "complete.json", + { + "complete": True, + "identity": identity, + "node_files": 2 * len(model.blocks) * len(POSITIONS) * 3, + "plan_rows": plan_rows, + "artifacts_sha256": file_sha256(output / "artifacts.json"), + }, + ) diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_confirmation_stats.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_confirmation_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..27d0d82cc96b250b88771946b569218a090bee50 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_confirmation_stats.py @@ -0,0 +1,280 @@ +"""Locked world-level inference for the narrower shortcut confirmation. + +This module consumes independently audited endpoint counts, never query outcomes +for selecting hypotheses. Nested seeds, organizations, chains and supports are +averaged within a world before any inferential calculation. +""" + +import itertools +import math + +DEFAULT_STATISTICS = { + "revision": "shortcut-confirmation-statistics-v1", + "scope": "training-correlation behavioral confirmation, not organization-path mediation", + "worlds": list(range(100, 108)), + "seeds": [0, 1], + "conditions": ["company", "project", "neither"], + "chains": ["company", "project"], + "prevalences": ["low", "high"], + "supports": [0, 1], + "kinds": ["coherent", "exception"], + "width": 256, + "learning_step": 15360, + "editing_step": 512, + "learning_denominator": 64, + "editing_denominator": 9, + "primary_endpoint": "editing_exception_fixed9", + "confirmatory_family": [ + "editing_exception_fixed9", + "learning_original_exception", + "editing_coherent_fixed9", + ], + "contrast": "high-minus-low", + "unit": "world; all nested pairs equally weighted within each world", + "test": "two-sided one-sample t on eight world-level paired differences, df=7", + "assumption": "independent generated worlds; approximately normal world-level differences", + "multiplicity": "Holm across the three confirmatory endpoints, family alpha=0.05", + "intervals": ["95% marginal t", "98.33333333333333% Bonferroni simultaneous t"], + "sensitivity": "all 256 world sign flips; valid under null sign symmetry, not an " + "unconditional randomized-treatment test", + "zero_sd": "all-zero differences: t=0,p=1,CI=[0,0], degenerate/no equivalence; " + "constant nonzero differences: t/p/CI=null, Holm input=1, adjusted p=1", + "stopping": "fixed eight worlds; no interim outcome inspection or optional extension", + "publication": "all three endpoints, signs, all E/U/global-D/base checks published " + "regardless of significance; no automatic natural-language or editor-method trigger", +} + + +def _beta_fraction(a, b, x): + tiny, tolerance = 1e-300, 3e-14 + qab, qap, qam = a + b, a + 1, a - 1 + c, d = 1.0, 1.0 - qab * x / qap + d = 1 / (d if abs(d) >= tiny else tiny) + h = d + for m in range(1, 401): + double = 2 * m + aa = m * (b - m) * x / ((qam + double) * (a + double)) + d, c = 1 + aa * d, 1 + aa / c + d = 1 / (d if abs(d) >= tiny else tiny) + c = c if abs(c) >= tiny else tiny + h *= d * c + aa = -(a + m) * (qab + m) * x / ((a + double) * (qap + double)) + d, c = 1 + aa * d, 1 + aa / c + d = 1 / (d if abs(d) >= tiny else tiny) + c = c if abs(c) >= tiny else tiny + factor = d * c + h *= factor + if abs(factor - 1) <= tolerance: + return h + raise ArithmeticError("Incomplete beta continued fraction did not converge") + + +def regularized_beta(x, a, b): + if not (0 <= x <= 1 and a > 0 and b > 0): + raise ValueError("Invalid beta arguments") + if x in (0, 1): + return float(x) + scale = math.exp( + math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x) + ) + if x < (a + 1) / (a + b + 2): + result = scale * _beta_fraction(a, b, x) / a + else: + result = 1 - scale * _beta_fraction(b, a, 1 - x) / b + return min(1.0, max(0.0, result)) + + +def t_two_sided_p(statistic, degrees): + if degrees <= 0 or not math.isfinite(statistic): + raise ValueError("Finite t and positive degrees of freedom required") + return regularized_beta(degrees / (degrees + statistic**2), degrees / 2, 0.5) + + +def t_critical(alpha, degrees): + if not (0 < alpha < 1 and degrees > 0): + raise ValueError("Invalid t quantile arguments") + lower, upper = 0.0, 1.0 + while t_two_sided_p(upper, degrees) > alpha: + upper *= 2 + for _ in range(100): + middle = (lower + upper) / 2 + if t_two_sided_p(middle, degrees) > alpha: + lower = middle + else: + upper = middle + return (lower + upper) / 2 + + +def holm(p_values): + """Unavailable p-values conservatively occupy a place in the family as 1.""" + values = [1.0 if p is None else float(p) for p in p_values] + if any(not math.isfinite(p) or not 0 <= p <= 1 for p in values): + raise ValueError("p-values must be finite and in [0,1], or None") + order = sorted(range(len(values)), key=lambda i: (values[i], i)) + result, previous = [None] * len(values), 0.0 + for rank, index in enumerate(order): + previous = max(previous, min(1.0, (len(values) - rank) * values[index])) + result[index] = previous + return result + + +def sign_flip_sensitivity(values): + if len(values) != 8 or not all(math.isfinite(x) for x in values): + raise ValueError("Exactly eight finite world differences required") + observed = abs(math.fsum(values)) + tolerance = 1e-12 * max(1.0, math.fsum(abs(x) for x in values)) + extreme = sum( + abs(math.fsum(s * x for s, x in zip(signs, values, strict=True))) >= observed - tolerance + for signs in itertools.product((-1, 1), repeat=8) + ) + return {"p": extreme / 256, "extreme": extreme, "enumerated": 256} + + +def world_t_statistics(values): + values = [float(x) for x in values] + if len(values) != 8 or not all(math.isfinite(x) for x in values): + raise ValueError("Exactly eight finite world differences required") + mean = math.fsum(values) / 8 + variance = math.fsum((value - mean) ** 2 for value in values) / 7 + sd = math.sqrt(variance) + result = { + "worlds": 8, + "df": 7, + "mean": mean, + "sd": sd, + "sign_flip_sensitivity": sign_flip_sensitivity(values), + } + if max(values) == min(values): + zero = values[0] == 0 + result.update( + status="degenerate_zero" if zero else "degenerate_nonzero", + t=0.0 if zero else None, + p=1.0 if zero else None, + ci95=[0.0, 0.0] if zero else None, + ci_bonferroni=[0.0, 0.0] if zero else None, + ) + return result + standard_error = sd / math.sqrt(8) + statistic = mean / standard_error + result.update(status="estimable", t=statistic, p=t_two_sided_p(statistic, 7)) + for key, alpha in [("ci95", 0.05), ("ci_bonferroni", 0.05 / 3)]: + half = t_critical(alpha, 7) * standard_error + result[key] = [mean - half, mean + half] + return result + + +def _integer(value, label): + if isinstance(value, bool): + raise ValueError(f"Boolean integer for {label}") + parsed = int(value) + if isinstance(value, str) and str(parsed) != value: + raise ValueError(f"Noncanonical integer for {label}: {value!r}") + if not isinstance(value, str) and parsed != value: + raise ValueError(f"Noninteger value for {label}: {value!r}") + return parsed + + +def validate_endpoints(rows, editing=False): + keys = ["world", "seed", "condition", "chain", "prevalence"] + if editing: + keys += ["support", "kind"] + indexed = {} + for raw in rows: + row = dict(raw) + if not editing and "support" in row: + raise ValueError("Learning endpoints must not be repeated or labeled by support") + for name in ["world", "seed", "step", "n", "correct"] + (["support"] if editing else []): + row[name] = _integer(row[name], name) + if "width" in row and _integer(row["width"], "width") != 256: + raise ValueError("Unexpected model width") + if row["step"] != (512 if editing else 15360): + raise ValueError("Endpoint step differs from the fixed budget") + if row["n"] != (9 if editing else 64) or not 0 <= row["correct"] <= row["n"]: + raise ValueError("Fixed cohort count is invalid") + if not editing and (row["cohort"] != "original_exception" or row["split"] != "heldout"): + raise ValueError("Wrong learning cohort or split") + key = tuple(row[k] for k in keys) + if key in indexed: + raise ValueError(f"Duplicate endpoint: {key}") + indexed[key] = row + dimensions = [ + range(100, 108), + (0, 1), + ("company", "project", "neither"), + ("company", "project"), + ("low", "high"), + ] + if editing: + dimensions += [(0, 1), ("coherent", "exception")] + expected = set(itertools.product(*dimensions)) + if set(indexed) != expected: + raise ValueError( + f"Endpoint matrix mismatch: missing {len(expected - set(indexed))}, " + f"unexpected {len(set(indexed) - expected)}" + ) + return indexed + + +def analyze_endpoints(learning, editing): + learning = validate_endpoints(learning) + editing = validate_endpoints(editing, editing=True) + world_rows, case_rows = [], [] + for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: + kind = None if endpoint == "learning_original_exception" else endpoint.split("_")[1] + source, denominator = (learning, 64) if kind is None else (editing, 9) + for world in range(100, 108): + pairs = [] + for seed, condition, chain in itertools.product( + (0, 1), ("company", "project", "neither"), ("company", "project") + ): + for support in [None] if kind is None else (0, 1): + base = (world, seed, condition, chain) + suffix = () if kind is None else (support, kind) + low = source[(*base, "low", *suffix)] + high = source[(*base, "high", *suffix)] + row = { + "endpoint": endpoint, + "world": world, + "seed": seed, + "condition": condition, + "chain": chain, + "support": support, + "kind": kind, + "n": denominator, + "low_correct": low["correct"], + "high_correct": high["correct"], + "correct_difference": high["correct"] - low["correct"], + } + row["accuracy_difference"] = row["correct_difference"] / denominator + pairs.append(row) + case_rows.append(row) + n = len(pairs) * denominator + world_rows.append( + { + "endpoint": endpoint, + "world": world, + "paired_cases": len(pairs), + "nested_query_count_descriptive": n, + "low_accuracy": sum(r["low_correct"] for r in pairs) / n, + "high_accuracy": sum(r["high_correct"] for r in pairs) / n, + "difference": sum(r["correct_difference"] for r in pairs) / n, + } + ) + results = [] + for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: + values = [row["difference"] for row in world_rows if row["endpoint"] == endpoint] + results.append({"endpoint": endpoint, **world_t_statistics(values)}) + adjusted = holm([result["p"] for result in results]) + for result, value in zip(results, adjusted, strict=True): + result.update( + holm_input=1.0 if result["p"] is None else result["p"], + holm_adjusted_p=value, + reject_two_sided_family_05=result["p"] is not None and value <= 0.05, + ) + return { + "contract": DEFAULT_STATISTICS, + "results": results, + "world_effects": world_rows, + "paired_cases": case_rows, + "input_rows": {"learning": len(learning), "editing": len(editing)}, + } diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_context_control.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_context_control.py new file mode 100644 index 0000000000000000000000000000000000000000..26c20f349951ff08ba251e2e61c158ad8f4c0f85 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_context_control.py @@ -0,0 +1,250 @@ +"""Conditional P3 control: block cross-fact document attention during training. + +The frozen document tensors, absolute positions, loss masks, optimizer, QA stream, +and inference path are unchanged. Only document attention edges are removed. +This module is prepared for conditional execution; importing it does not train. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import time +from contextlib import contextmanager +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import bios_cross_train as frozen_trainer +from .bios_cross import CHAINS, CONDITIONS, audit, documents, make_cross_world, qa_schedule +from .bios_data import array_hash, write_json +from .bios_model import Attention, CausalLM +from .bios_organization_train import atomic_numpy_save +from .bios_path_diagnostics import autonomous_two_step + +RECORD_LENGTH = 6 +DOCUMENT_LENGTH = 60 +CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360) + + +def fact_causal_mask(length=DOCUMENT_LENGTH, record_length=RECORD_LENGTH, device=None): + """SDPA Boolean True means an allowed edge: same record and causal order.""" + if length <= 0 or record_length <= 0 or length % record_length: + raise ValueError("Document length must contain complete fact records") + position = torch.arange(length, device=device) + return (position[:, None] // record_length == position[None, :] // record_length) & ( + position[None, :] <= position[:, None] + ) + + +class FactIsolatedAttention(Attention): + """An existing Attention object's parameters are retained without reinitializing.""" + + def forward(self, x): + if not self.document_attention_isolated: + return super().forward(x) + batch, length, width = x.shape + if length != DOCUMENT_LENGTH: + raise ValueError("Document-only attention entered with a non-document tensor") + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=self.fact_mask, + is_causal=False, + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +class FactIsolatedCausalLM(CausalLM): + """Use the original initializer, forward, position IDs, and state-dict schema. + + In the frozen trainer the only 60-token training input is a document; QA + training inputs contain six tokens. Evaluation always uses the original + attention path, including an unusually long inference input. No dropout, + extra trainable parameter, random draw, or reset of position IDs is added. + """ + + def __init__(self, config): + super().__init__(config) + mask = fact_causal_mask() + for block in self.blocks: + attention = block.attention + attention.__class__ = FactIsolatedAttention + attention.document_attention_isolated = False + attention.register_buffer("fact_mask", mask, persistent=False) + + def forward(self, tokens, positions=None): + isolate = self.training and tokens.shape[1] == DOCUMENT_LENGTH + if self.training and tokens.shape[1] not in (RECORD_LENGTH, DOCUMENT_LENGTH): + raise ValueError("Unexpected training input length; document/QA dispatch is unsafe") + if isolate: + if positions is None or positions.shape[1] != 20: + raise ValueError("Document training must preserve all twenty supervised positions") + expected = torch.arange(DOCUMENT_LENGTH, device=tokens.device).view(10, 6)[:, 3:5] + if not torch.equal(positions, expected.reshape(1, 20).expand(len(tokens), -1)): + raise ValueError("Document supervision positions changed") + for block in self.blocks: + block.attention.document_attention_isolated = isolate + try: + return super().forward(tokens, positions) + finally: + for block in self.blocks: + block.attention.document_attention_isolated = False + + +@contextmanager +def isolated_model_factory(): + """Patch only this worker's factory while retaining the frozen trainer body.""" + original = frozen_trainer.CausalLM + if original is not CausalLM: + raise RuntimeError("The frozen trainer already has a modified model factory") + frozen_trainer.CausalLM = FactIsolatedCausalLM + try: + yield + finally: + frozen_trainer.CausalLM = original + + +def context_sources(): + directory = Path(__file__).parent + return { + **frozen_trainer.source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ("bios_context_control.py", "bios_path_diagnostics.py") + }, + } + + +def validate_study(study): + expected = { + "width": 256, + "layers": 8, + "heads": 4, + "steps": 15360, + "checkpoints": list(CHECKPOINTS), + "lr": 0.0001, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "learning_runs": 12, + "edit_cases": 0, + } + for key, value in expected.items(): + if study.get(key) != value: + raise ValueError(f"Context control changed its frozen study setting: {key}") + + +def run(args): + study = json.loads(Path(args.config).read_text()) + validate_study(study) + if args.world not in study["worlds"] or args.seed not in study["seeds"]: + raise ValueError("Context control is restricted to the development matrix") + output = Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + world = make_cross_world(args.world) + world_audit = audit(world) + docs, schedule = documents(world, args.condition), qa_schedule(world, study["steps"]) + contract = { + "protocol": "v2.8-p3-context-control", + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "study": study, + "sources": context_sources(), + "intervention": { + "training_document_attention": "causal within each six-token fact only", + "absolute_positions": "unchanged 0 through 59; never reset within facts", + "document_tokens_batches_and_supervision": "unchanged", + "QA_training_attention": "original causal attention", + "all_inference_attention": "original causal attention", + "mask_sha256": array_hash(fact_causal_mask().numpy()), + }, + "data": { + "truth_sha256": world_audit["truth_sha256"], + "prompts_sha256": world_audit["prompts_sha256"], + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + }, + "environment": { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + } + path = output / "launch-contract.json" + if path.exists(): + old = json.loads(path.read_text()) + for key in contract.keys() - {"environment"}: + if old[key] != contract[key]: + raise ValueError(f"Context control contract changed: {key}") + else: + write_json(path, contract) + if (output / "complete.json").exists(): + return + torch.set_num_threads(args.threads) + device = torch.device(args.device) + controlled_study = { + **study, + "context_contract": contract["sources"], + "context_intervention": contract["intervention"], + } + try: + with isolated_model_factory(): + model, _ = frozen_trainer.learning(args, world, output, controlled_study, device) + # Inference must be the original unrestricted forward path. + model.eval() + with np.load(output / f"predictions-{study['steps']}.npz") as saved: + direct = {key: saved[key] for key in ("prediction", "ended", "correct")} + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) + atomic_numpy_save(output / f"two-step-{name}.npz", **arrays) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": "P3-context-control-learning-only", + "learning_steps": study["steps"], + "edit_cases": 0, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + { + "type": type(error).__name__, + "message": str(error), + "time": time.time(), + }, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True, type=int) + parser.add_argument("--seed", required=True, type=int) + parser.add_argument("--condition", required=True, choices=CONDITIONS) + parser.add_argument("--config", default="configs/bios-context-control-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_context_gradient.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_context_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..89f78f244a71569026fd75d76ac6b10b702fed9d --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_context_gradient.py @@ -0,0 +1,669 @@ +"""Prospectively frozen context-statistic prediction of common-state gradients. + +The predictor contracts supervised target/context co-occurrences with fixed +embeddings and first-layer value weights. It uses neither real gradients nor +contextual activations, and has no fitted scale. It is a new residual-path +approximation, not a theorem for the project's Transformer or AdamW updates. +""" + +import argparse +import hashlib +import itertools +import json +import platform +import time +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path +from types import MethodType + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CONDITIONS, + documents, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_cross_train import tensor_queries +from .bios_data import array_hash, write_json +from .bios_model import CausalLM, ModelConfig + +TARGET = "blocks.0.attention.proj.weight" +CONTRASTS = (("company", "neither"), ("project", "neither"), ("company", "project")) + + +def sha(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def stamp(): + return datetime.now(timezone.utc).isoformat() + + +def allowed_mask(length, isolated, device=None): + pos = torch.arange(length, device=device) + mask = pos[None, :] <= pos[:, None] + if isolated: + mask &= pos[None, :] // 6 == pos[:, None] // 6 + return mask + + +def _isolated_forward(self, x): + batch, length, width = x.shape + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=allowed_mask(length, True, x.device), + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +@contextmanager +def attention_mode(model, isolated): + originals = [] + if isolated: + for block in model.blocks: + attention = block.attention + originals.append((attention, attention.forward)) + attention.forward = MethodType(_isolated_forward, attention) + try: + yield + finally: + for attention, forward in originals: + attention.forward = forward + + +def ln_vjp(x, upstream, layer): + """Exact input VJP of LayerNorm, without reading a real model gradient.""" + centered = x - x.mean(-1, keepdim=True) + inverse = torch.rsqrt(centered.square().mean(-1, keepdim=True) + layer.eps) + normalized = centered * inverse + affine = upstream * layer.weight + return inverse * ( + affine + - affine.mean(-1, keepdim=True) + - normalized * (affine * normalized).mean(-1, keepdim=True) + ) + + +@torch.no_grad() +def statistic_predictors(model, tokens, positions, labels, shuffled, isolated): + """Gradients of a zero-residual baseline plus one infinitesimal OV branch. + + x_j = E[token_j] + P[j] (or E[token_j] for the token-only control). + m_t = average_{j allowed at t} (Wv LN1(x_j) + bv). + epsilon_t = J_LNfinal(x_t)^T E^T (softmax(E LNfinal(x_t)) - onehot(y_t)). + Ghat = mean_t epsilon_t m_t^T. This is a contraction of position/mask + weighted token-target counts; all other residual branches are omitted. + The answer and EOS means returned here are separately normalized. + """ + width = model.config.width + result = {} + for position_aware in (True, False): + x = model.token(tokens) + if position_aware: + x = x + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + value = F.linear( + model.blocks[0].ln1(x), + model.blocks[0].attention.qkv.weight[2 * width :], + model.blocks[0].attention.qkv.bias[2 * width :], + ) + mask = allowed_mask(tokens.shape[1], isolated, tokens.device).to(x.dtype) + mask /= mask.sum(-1, keepdim=True) + mean_value = (mask @ value)[:, positions] + query = x[:, positions] + probability = F.linear(model.ln_final(query), model.token.weight).softmax(-1) + expected = probability @ model.token.weight + variants = ( + (("position", labels), ("shuffled", shuffled)) + if position_aware + else (("token", labels),) + ) + for name, targets in variants: + epsilon = ln_vjp(query, expected - model.token(targets), model.ln_final) + for offset, kind in enumerate(("answer", "eos")): + left, right = epsilon[:, offset::2], mean_value[:, offset::2] + result[f"{name}/{kind}"] = torch.einsum("btd,bte->de", left, right) / ( + left.shape[0] * left.shape[1] + ) + return result + + +def vector_metrics(actual, predicted): + actual = np.asarray(actual, dtype=np.float64).ravel() + predicted = np.asarray(predicted, dtype=np.float64).ravel() + an, pn = np.linalg.norm(actual), np.linalg.norm(predicted) + return { + "actual_norm": float(an), + "predicted_norm": float(pn), + "cosine": float(np.dot(actual, predicted) / (an * pn)) if an and pn else None, + "relative_error": float(np.linalg.norm(actual - predicted) / an) if an else None, + "norm_ratio": float(pn / an) if an else None, + } + + +def module_name(name): + if name.startswith("blocks."): + parts = name.split(".") + if parts[2] == "attention" and parts[3] == "qkv": + return ".".join(parts[:4]) + return ".".join(parts[:3]) + return name.split(".")[0] + + +def module_differences(first, second): + sums = {} + for name in first: + # The concatenated qkv parameter is additionally split by role. + pieces = [(module_name(name), first[name], second[name])] + if ".attention.qkv." in name: + pieces = [ + (name.split(".qkv.")[0] + "." + role, a, b) + for role, a, b in zip( + ("query", "key", "value"), + np.split(first[name], 3), + np.split(second[name], 3), + strict=True, + ) + ] + for group, left, right in pieces: + values = sums.setdefault(group, np.zeros(3, dtype=np.float64)) + left, right = left.astype(np.float64), right.astype(np.float64) + values += (np.sum((left - right) ** 2), np.sum(left**2), np.sum(right**2)) + return { + group: { + "difference_norm": float(np.sqrt(value[0])), + "relative_to_mean_arm_norm": float( + np.sqrt(value[0]) / ((np.sqrt(value[1]) + np.sqrt(value[2])) / 2) + ) + if value[1] + value[2] + else None, + } + for group, value in sums.items() + } + + +def source_files(root, config): + names = [ + "bios_context_gradient.py", + "bios_cross.py", + "bios_cross_train.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_organization.py", + ] + paths = [root / "src/llm_memory_editability" / name for name in names] + paths += [ + root / "scripts/run_bios_context_gradient.py", + root / "tests/test_bios_context_gradient.py", + ] + paths += [root / "configs/bios-context-gradient-v1.json"] + for world in config["worlds"]: + paths += [ + root / config["source_world_root"] / f"world-{world}" / name + for name in ("world.npz", "metadata.json", "audit.json") + ] + return paths + + +def freeze(root, config): + out = root / config["artifacts"] + lockpath = out / "preregistration-lock.json" + if lockpath.exists(): + raise FileExistsError("An existing prospective lock must not be replaced") + protocol = (root / "docs/experimental-protocol.md").read_text().split("## 16. ", 1)[1] + out.mkdir(parents=True, exist_ok=True) + (out / "preregistration.md").write_text("## 16. " + protocol) + sources = {} + for path in source_files(root, config): + relative = path.relative_to(root) + sources[str(relative)] = sha(path) + # Data stay in their original location, hash-bound by the lock. + if relative.parts[0] != "data": + copy = out / "frozen-files" / relative + copy.parent.mkdir(parents=True, exist_ok=True) + copy.write_bytes(path.read_bytes()) + write_json( + lockpath, + { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(out / "preregistration.md"), + "torch": torch.__version__, + "numpy": np.__version__, + "python": platform.python_version(), + }, + ) + return {"lock": str(lockpath), "sha256": sha(lockpath)} + + +def verify_lock(root, config): + lockpath = root / config["artifacts"] / "preregistration-lock.json" + lock = json.loads(lockpath.read_text()) + if lock["config"] != config: + raise ValueError("Configuration differs from prospective lock") + for path, expected in lock["sources"].items(): + if sha(root / path) != expected: + raise ValueError("Frozen source changed: " + path) + if sha(root / config["artifacts"] / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Prospective protocol changed") + return sha(lockpath) + + +def context_audit(world, config): + """Exact exposure/bigram audit plus a centered city-by-person Phi subblock.""" + people = [i for i, label in enumerate(world.token_labels) if label.startswith("person:")] + cities = np.unique(world.city_tokens) + pi, ci = np.full(world.vocab_size, -1), np.full(world.vocab_size, -1) + pi[people], ci[cities] = np.arange(len(people)), np.arange(len(cities)) + histograms, contexts, receipts = {}, {}, {} + for condition in CONDITIONS: + docs = documents(world, condition) + receipts[condition] = {"documents_sha256": array_hash(docs)} + counts = np.bincount(docs.ravel(), minlength=world.n_base) + receipts[condition]["exposure_sha256"] = array_hash(counts) + for isolated in (False, True): + joint = np.zeros((len(cities), len(people))) + marginal = np.zeros(len(people)) + bigrams = np.zeros((2, world.vocab_size), dtype=np.int64) + for epoch in range(config["rotations"]): + batch = render(world, epoch_documents(docs, world.seed, epoch)) + for col, pos in enumerate(batch["positions"][0]): + targets = batch["labels"][:, col] + # All answer predictors use ANS; EOS predictors use answer tokens. + values = targets if col % 2 == 0 else batch["tokens"][:, pos] + bigrams[col % 2] += np.bincount(values, minlength=world.vocab_size) + left = int(pos) // 6 * 6 if isolated else 0 + weight = 1 / (int(pos) - left + 1) + rows = ci[targets] + for prefix in range(left, int(pos) + 1): + columns = pi[batch["tokens"][:, prefix]] + valid = columns >= 0 + np.add.at(marginal, columns[valid], weight) + valid &= rows >= 0 + np.add.at(joint, (rows[valid], columns[valid]), weight) + contexts[condition, isolated] = (joint - marginal[None] / world.vocab_size) / ( + config["rotations"] * len(docs) * 20 + ) + histograms[condition] = bigrams + result = {"receipts": receipts, "comparisons": []} + for a, b in CONTRASTS: + equal = np.array_equal(histograms[a], histograms[b]) + if not equal or receipts[a]["exposure_sha256"] != receipts[b]["exposure_sha256"]: + raise ValueError("Organization exposure or supervised bigrams differ") + for isolated in (False, True): + first, second = contexts[a, isolated], contexts[b, isolated] + difference = np.max(np.abs(first - second)) + if isolated and difference > 1e-14: + raise ValueError("Isolated context statistics differ") + result["comparisons"].append( + { + "first": a, + "second": b, + "isolated": isolated, + "supervised_bigram_equal": equal, + "context_max_abs_difference": float(difference), + "context_relative_difference": float( + np.linalg.norm(first - second) / np.linalg.norm(second) + ), + } + ) + result["bigram_sha256"] = array_hash(histograms["neither"]) + result["qa_ids_sha256"] = array_hash(world.train_ids) + return result + + +def numpy_gradients(accumulators): + return {name: value.cpu().numpy().astype(np.float32) for name, value in accumulators.items()} + + +def measure_arm(model, world, condition, isolated, config, device, out): + docs = documents(world, condition) + named = dict(model.named_parameters()) + params = tuple(named.values()) + accumulators = { + kind: {name: torch.zeros_like(value, dtype=torch.float64) for name, value in named.items()} + for kind in ("answer", "eos") + } + predictions = { + f"{predictor}/{kind}": torch.zeros( + (model.config.width, model.config.width), dtype=torch.float64, device=device + ) + for predictor in config["predictors"] + for kind in ("answer", "eos") + } + losses = {"answer": 0.0, "eos": 0.0} + total_documents = len(docs) * config["rotations"] + started = time.perf_counter() + model.eval() + with attention_mode(model, isolated): + for epoch in range(config["rotations"]): + batch = render(world, epoch_documents(docs, world.seed, epoch)) + shuffled = batch["labels"].copy() + rng = np.random.default_rng( + np.random.SeedSequence([config["shuffle_seed"], world.seed, epoch]) + ) + # Each column is one relation at one absolute position. Marginals + # are exactly preserved, with the same permutations in every arm. + for col in range(shuffled.shape[1]): + shuffled[:, col] = shuffled[rng.permutation(len(docs)), col] + for begin in range(0, len(docs), config["measurement_batch"]): + end = min(begin + config["measurement_batch"], len(docs)) + tokens = torch.as_tensor(batch["tokens"][begin:end], device=device) + labels = torch.as_tensor(batch["labels"][begin:end], device=device) + positions = torch.as_tensor(batch["positions"][0], device=device) + shuffled_batch = torch.as_tensor(shuffled[begin:end], device=device) + weight = config["document_weight"] * 0.5 * (end - begin) / total_documents + predictors = statistic_predictors( + model, tokens, positions, labels, shuffled_batch, isolated + ) + for name, prediction in predictors.items(): + predictions[name].add_(prediction.double(), alpha=weight) + logits = model(tokens, positions[None].expand(len(tokens), -1)) + for offset, kind in enumerate(("answer", "eos")): + loss = F.cross_entropy( + logits[:, offset::2].flatten(0, 1), labels[:, offset::2].flatten() + ) + gradients = torch.autograd.grad(loss, params, retain_graph=offset == 0) + for name, gradient in zip(named, gradients, strict=True): + accumulators[kind][name].add_(gradient.double(), alpha=weight) + losses[kind] += float(loss.detach()) * (end - begin) / total_documents + print( + json.dumps({"event": "rotation", "arm": out.name, "rotation": epoch + 1}), + flush=True, + ) + result = {kind: numpy_gradients(accumulators[kind]) for kind in accumulators} + result["predictions"] = numpy_gradients(predictions) + out.mkdir(parents=True, exist_ok=False) + np.savez(out / "answer.npz", **result["answer"]) + np.savez(out / "eos.npz", **result["eos"]) + np.savez(out / "predictions.npz", **result["predictions"]) + metadata = { + "condition": condition, + "isolated": isolated, + "documents": total_documents, + "supervised_tokens": total_documents * 20, + "losses": losses, + "seconds": time.perf_counter() - started, + "files": {name: sha(out / name) for name in ("answer.npz", "eos.npz", "predictions.npz")}, + } + if any(not np.isfinite(value).all() for part in result.values() for value in part.values()): + raise FloatingPointError("Nonfinite gradients or predictions") + write_json(out / "receipt.json", metadata) + return result + + +def arm_data(path): + return { + kind: dict(np.load(path / f"{filename}.npz")) + for kind, filename in (("answer", "answer"), ("eos", "eos"), ("predictions", "predictions")) + } + + +def common_training_step(model, optimizer, world, config, step, device, schedule, data): + epoch, offset = divmod(step, 128) + arranged = epoch_documents(documents(world, "neither"), world.seed, epoch) + batch = render(world, arranged[offset * 16 : (offset + 1) * 16]) + tokens = torch.as_tensor(batch["tokens"], device=device) + positions = torch.as_tensor(batch["positions"], device=device) + labels = torch.as_tensor(batch["labels"], device=device) + qa = torch.as_tensor(schedule[step], device=device) + model.train() + optimizer.zero_grad(set_to_none=True) + for group in optimizer.param_groups: + group["lr"] = config["lr"] * min((epoch + 1) / config["warmup_epochs"], 1) + loss = F.cross_entropy(model(tokens, positions).flatten(0, 1), labels.flatten()) + (config["document_weight"] * loss).backward() + qa_loss = F.cross_entropy( + model(data["tokens"][qa], data["positions"][qa]).flatten(0, 1), data["labels"][qa].flatten() + ) + (config["qa_weight"] * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config["clip_norm"]) + if not torch.isfinite(loss + qa_loss + norm): + raise FloatingPointError("Nonfinite common training step") + optimizer.step() + return { + "step": step + 1, + "document_loss": float(loss.detach()), + "qa_loss": float(qa_loss.detach()), + } + + +def run(root, config, world_seed, seed, device): + lock_hash = verify_lock(root, config) + if world_seed not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("World/initialization is outside the frozen matrix") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.manual_seed(seed) + world = make_cross_world(world_seed, root / config["source_world_root"]) + out = root / config["output"] / f"world-{world_seed}-seed-{seed}" + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + raise FileExistsError("Completed run cannot be overwritten") + audit_path = out / "data-audit.json" + if not audit_path.exists(): + write_json(audit_path, context_audit(world, config)) + model = CausalLM( + ModelConfig( + world.vocab_size, config["width"], config["layers"], config["heads"], config["context"] + ) + ).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), + lr=config["lr"], + weight_decay=config["weight_decay"], + fused=device.type == "cuda", + ) + schedule = qa_schedule(world, max(config["states"])) + data = tensor_queries(world, device) + trajectory = [] + write_json( + out / "identity.json", + { + "world": world_seed, + "seed": seed, + "lock_sha256": lock_hash, + "created_at": stamp(), + "model": model.config_dict(), + "parameters": sum(p.numel() for p in model.parameters()), + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "torch": torch.__version__, + "numpy": np.__version__, + "qa_schedule_sha256": array_hash(schedule), + }, + ) + for step in range(max(config["states"]) + 1): + if step in config["states"]: + state_path = out / f"state-{step}.pt" + if state_path.exists(): + # Resumption reconstructs the exact common trajectory and verifies + # weights before using any existing diagnostic artifacts. + saved = torch.load(state_path, map_location=device, weights_only=False) + if any( + not torch.equal(v, saved["model"][k]) for k, v in model.state_dict().items() + ): + raise ValueError("Reconstructed reference weights differ") + else: + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "config": model.config_dict(), + }, + state_path, + ) + for mask in config["masks"]: + for condition in config["conditions"]: + path = out / f"step-{step}-{mask}-{condition}" + if (path / "receipt.json").exists(): + receipt = json.loads((path / "receipt.json").read_text()) + if any( + sha(path / name) != digest for name, digest in receipt["files"].items() + ): + raise ValueError("Existing gradient artifact hash mismatch") + continue + if path.exists(): + raise FileExistsError("Incomplete output must be retained and audited") + print( + json.dumps( + { + "event": "arm_start", + "world": world_seed, + "seed": seed, + "step": step, + "mask": mask, + "condition": condition, + } + ), + flush=True, + ) + measure_arm(model, world, condition, mask == "isolated", config, device, path) + write_json(out / "trajectory.json", trajectory) + if step < max(config["states"]): + trajectory.append( + common_training_step(model, optimizer, world, config, step, device, schedule, data) + ) + verify_lock(root, config) + files = {str(path.relative_to(out)): sha(path) for path in out.rglob("*") if path.is_file()} + write_json( + out / "complete.json", {"completed_at": stamp(), "lock_sha256": lock_hash, "files": files} + ) + + +def summarize(root, config): + verify_lock(root, config) + rows, modules, checks = [], [], [] + for world_seed, seed in itertools.product(config["worlds"], config["seeds"]): + runpath = root / config["output"] / f"world-{world_seed}-seed-{seed}" + completion = json.loads((runpath / "complete.json").read_text()) + for name, digest in completion["files"].items(): + if sha(runpath / name) != digest: + raise ValueError("Completed run artifact changed: " + name) + for step, mask in itertools.product(config["states"], config["masks"]): + arms = {c: arm_data(runpath / f"step-{step}-{mask}-{c}") for c in CONDITIONS} + for a, b in CONTRASTS: + identity = { + "world": world_seed, + "seed": seed, + "step": step, + "mask": mask, + "first": a, + "second": b, + } + for kind in ("answer", "eos", "combined"): + kinds = ("answer", "eos") if kind == "combined" else (kind,) + ga = {n: sum(arms[a][k][n] for k in kinds) for n in arms[a]["answer"]} + gb = {n: sum(arms[b][k][n] for k in kinds) for n in arms[b]["answer"]} + modules.append( + {**identity, "kind": kind, "modules": module_differences(ga, gb)} + ) + for predictor in config["predictors"]: + pred = sum( + arms[a]["predictions"][f"{predictor}/{k}"] + - arms[b]["predictions"][f"{predictor}/{k}"] + for k in kinds + ) + row = { + **identity, + "kind": kind, + "predictor": predictor, + **vector_metrics(ga[TARGET] - gb[TARGET], pred), + } + # Near-zero isolated contrasts are cancellation controls; + # cosine between rounding residues has no scientific meaning. + if mask == "isolated": + row["cosine"] = None + rows.append(row) + norm = np.linalg.norm(ga[TARGET] - gb[TARGET]) + reference = (np.linalg.norm(ga[TARGET]) + np.linalg.norm(gb[TARGET])) / 2 + if mask == "isolated": + checks.append( + { + **identity, + "kind": kind, + "relative_cancellation_residue": float(norm / reference), + } + ) + if any(c["relative_cancellation_residue"] > 1e-4 for c in checks): + raise ValueError("Isolated common-state gradient cancellation failed") + out = root / config["artifacts"] + write_json(out / "metrics.json", rows) + write_json(out / "module-metrics.json", modules) + write_json( + out / "audit.json", + {"passed": True, "runs": 4, "arms": 72, "isolated_checks": checks, "completed_at": stamp()}, + ) + primary = [ + r + for r in rows + if r["step"] == 0 + and r["mask"] == "open" + and r["kind"] == "answer" + and r["second"] == "neither" + ] + lines = [ + "# Context statistics and common-state gradients", + "", + "Descriptive development experiment; no fitted scale or significance tests.", + "", + "| World | Seed | Contrast | Predictor | Cosine | Relative error | Norm ratio |", + "| --- | --- | --- | --- | ---: | ---: | ---: |", + ] + for row in primary: + lines.append( + f"| {row['world']} | {row['seed']} | {row['first']}−{row['second']} | " + f"{row['predictor']} | {row['cosine']:.6f} | {row['relative_error']:.6f} | " + f"{row['norm_ratio']:.6f} |" + ) + (out / "report.md").write_text("\n".join(lines) + "\n") + print( + json.dumps( + { + "report": str(out / "report.md"), + "rows": len(rows), + "max_isolated_residue": max(c["relative_cancellation_residue"] for c in checks), + } + ) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=("freeze", "run", "summarize")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument( + "--config", type=Path, default=Path("configs/bios-context-gradient-v1.json") + ) + args = parser.parse_args() + root = Path(__file__).resolve().parents[2] + config = json.loads((root / args.config).read_text()) + if args.mode == "freeze": + print(json.dumps(freeze(root, config))) + elif args.mode == "run": + run(root, config, args.world, args.seed, torch.device(args.device)) + else: + summarize(root, config) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_cross.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..960ef7e03dd29b834df68149d8aca7cbcd077a10 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_cross.py @@ -0,0 +1,330 @@ +"""Two-chain organization crossover: shared facts, symmetric relational tasks. + +This is a new development world, not an alteration of the archived A/B/C runs. +Company and project each have 64 groups of 32 people and two old exceptions. +""" + +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +from .bios_data import ANS, BOS, EOS, N_BASE, N_PEOPLE, array_hash, load_world, rng_for, write_json + +CONDITIONS = ("company", "project", "neither") +CHAINS = ("company", "project") +SLOTS = 10 + + +@dataclass +class CrossWorld: + seed: int + prompts: np.ndarray + lengths: np.ndarray + answers: np.ndarray + relation: np.ndarray + person: np.ndarray + memberships: np.ndarray + defaults: np.ndarray + exceptions: np.ndarray + membership_ids: np.ndarray + root_ids: np.ndarray + actual_ids: np.ndarray + derived_ids: np.ndarray + train_ids: np.ndarray + heldout_ids: np.ndarray + city_tokens: np.ndarray + token_labels: list + n_base: int + + @property + def vocab_size(self): + return len(self.token_labels) + + +def make_cross_world(seed, source_root="data/bios-organization-v1"): + old = load_world(Path(source_root) / f"world-{seed}") + labels = ( + old.token_labels + + [f"project:{i}" for i in range(64)] + + ["relation:project", "relation:project_default", "relation:project_actual"] + ) + token = {name: i for i, name in enumerate(labels)} + rng = rng_for(seed, 901) + memberships = np.stack([old.employers, rng.permutation(np.repeat(np.arange(64), 32))]) + defaults = np.stack([old.defaults, rng.permutation(old.defaults)]) + exceptions = np.stack([old.exceptions, np.zeros(N_PEOPLE, dtype=bool)]) + actual = defaults[1, memberships[1]].copy() + for group in range(64): + people = rng.choice(np.flatnonzero(memberships[1] == group), 2, replace=False) + exceptions[1, people] = True + choices = np.unique(defaults[1][defaults[1] != defaults[1, group]]) + actual[people] = rng.choice(choices, 2) + n_base = N_BASE + 2 * N_PEOPLE + 64 + size = n_base + 2 * N_PEOPLE + prompts = np.zeros((size, 5), dtype=np.int64) + answers = np.zeros(size, dtype=np.int64) + lengths = np.full(size, 4, dtype=np.int64) + relation = np.zeros(size, dtype=np.int64) + person = np.full(size, -1, dtype=np.int64) + prompts[:N_BASE], answers[:N_BASE] = old.prompts[:N_BASE], old.answers[:N_BASE] + relation[:N_BASE], person[:N_BASE] = old.relation[:N_BASE], old.person[:N_BASE] + membership_ids = np.stack([np.arange(N_PEOPLE), N_BASE + np.arange(N_PEOPLE)]) + root_ids = np.stack([N_PEOPLE + np.arange(64), N_BASE + N_PEOPLE + np.arange(64)]) + actual_ids = np.stack( + [N_PEOPLE + 64 + np.arange(N_PEOPLE), N_BASE + N_PEOPLE + 64 + np.arange(N_PEOPLE)] + ) + person_tokens = np.array([token[f"person:{i}"] for i in range(N_PEOPLE)]) + new_values = [ + np.array([token[f"project:{i}"] for i in memberships[1]]), + old.city_tokens[defaults[1]], + old.city_tokens[actual], + ] + for rel, ids, values in zip( + (7, 8, 9), (membership_ids[1], root_ids[1], actual_ids[1]), new_values, strict=True + ): + subjects = ( + np.array([token[f"project:{i}"] for i in range(64)]) if rel == 8 else person_tokens + ) + rtoken = token[ + ("relation:project", "relation:project_default", "relation:project_actual")[rel - 7] + ] + prompts[ids, :4] = np.column_stack( + [np.full(len(ids), BOS), subjects, np.full(len(ids), rtoken), np.full(len(ids), ANS)] + ) + answers[ids], relation[ids] = values, rel + if rel != 8: + person[ids] = np.arange(N_PEOPLE) + derived_ids = n_base + np.arange(2 * N_PEOPLE).reshape(2, N_PEOPLE) + trained, heldout = [], [] + for chain in range(2): + ids = derived_ids[chain] + prompts[ids] = np.column_stack( + [ + np.full(N_PEOPLE, BOS), + person_tokens, + np.full(N_PEOPLE, token["relation:employer" if chain == 0 else "relation:project"]), + np.full( + N_PEOPLE, + token["relation:default_city" if chain == 0 else "relation:project_default"], + ), + np.full(N_PEOPLE, ANS), + ] + ) + answers[ids] = old.city_tokens[defaults[chain, memberships[chain]]] + lengths[ids], relation[ids], person[ids] = 5, 10 + chain, np.arange(N_PEOPLE) + split_rng = rng_for(seed, 902, chain) + included = [] + for group in range(64): + for exception in (False, True): + candidates = np.flatnonzero( + (memberships[chain] == group) & (exceptions[chain] == exception) + ) + included.extend(split_rng.permutation(candidates)[: len(candidates) // 2]) + trained.append(np.sort(ids[included])) + heldout.append(np.setdiff1d(ids, trained[-1])) + # Randomize the complete vocabulary, so appended token numbers carry no task order. + permutation = np.arange(len(labels)) + permutation[4:] = rng_for(seed, 903).permutation(permutation[4:]) + new_labels = [""] * len(labels) + for index, label in enumerate(labels): + new_labels[permutation[index]] = label + return CrossWorld( + seed, + permutation[prompts], + lengths, + permutation[answers], + relation, + person, + memberships, + defaults, + exceptions, + membership_ids, + root_ids, + actual_ids, + derived_ids, + np.stack(trained), + np.stack(heldout), + permutation[old.city_tokens], + new_labels, + n_base, + ) + + +def documents(world, condition): + if condition not in CONDITIONS: + raise ValueError("Unknown crossover condition") + docs = np.empty((N_PEOPLE, SLOTS), dtype=np.int64) + for rel in range(SLOTS): + if rel in (1, 8): + continue + ids = np.flatnonzero(world.relation[: world.n_base] == rel) + docs[world.person[ids], rel] = ids + for chain, slot in enumerate((1, 8)): + membership = world.memberships[chain] + group = membership.copy() + if condition != CHAINS[chain]: + rng = rng_for(world.seed, 904, chain) + members = np.stack( + [rng.permutation(np.flatnonzero(membership == g)) for g in range(64)] + ) + for lane in range(32): + cycle = rng.permutation(64) + group[members[cycle, lane]] = np.roll(cycle, -1) + docs[:, slot] = world.root_ids[chain, group] + return docs + + +def epoch_documents(docs, seed, epoch): + rows = rng_for(seed, 905, epoch).permutation(N_PEOPLE) + return np.roll(docs[rows], epoch % SLOTS, axis=1) + + +def render(world, ids): + tokens = np.empty((*ids.shape, 6), dtype=np.int64) + tokens[:, :, :4] = world.prompts[ids, :4] + tokens[:, :, 4], tokens[:, :, 5] = world.answers[ids], EOS + positions = (np.arange(SLOTS)[:, None] * 6 + np.array([3, 4])).ravel() + labels = np.stack([world.answers[ids], np.full_like(ids, EOS)], axis=-1) + return { + "tokens": tokens.reshape(len(ids), SLOTS * 6), + "positions": np.broadcast_to(positions, (len(ids), SLOTS * 2)).copy(), + "labels": labels.reshape(len(ids), SLOTS * 2), + } + + +def qa_schedule(world, steps): + streams = [] + for chain in range(2): + rng = rng_for(world.seed, 906, chain) + pool = world.train_ids[chain] + streams.append( + np.concatenate( + [rng.permutation(pool) for _ in range((steps * 20 + len(pool) - 1) // len(pool))] + )[: steps * 20].reshape(steps, 20) + ) + return np.concatenate(streams, axis=1) + + +def audit(world): + expected = np.ones(world.n_base, dtype=np.int64) + expected[world.root_ids.ravel()] = 32 + report = {} + for condition in CONDITIONS: + docs = documents(world, condition) + if not np.array_equal(np.bincount(docs.ravel(), minlength=world.n_base), expected): + raise ValueError("Unequal fact exposure") + personal = world.person[docs[:, [0, 2, 3, 4, 5, 6, 7, 9]]] + if not np.all(personal == np.arange(N_PEOPLE)[:, None]): + raise ValueError("Person grouping changed") + for chain, slot in enumerate((1, 8)): + linked = docs[:, slot] == world.root_ids[chain, world.memberships[chain]] + if not np.all(linked == (condition == CHAINS[chain])): + raise ValueError("Incorrect linked/unlinked manipulation") + slots = np.zeros((world.n_base, SLOTS), dtype=np.int64) + for epoch in range(SLOTS): + arranged = epoch_documents(docs, world.seed, epoch) + np.add.at(slots, (arranged, np.arange(SLOTS)[None, :]), 1) + if not np.array_equal(slots, np.repeat(expected[:, None], SLOTS, axis=1)): + raise ValueError("Unequal position exposure") + report[condition] = { + "documents_sha256": array_hash(docs), + "exposure_sha256": array_hash(expected), + } + for chain in range(2): + if not np.array_equal(np.bincount(world.memberships[chain]), np.full(64, 32)): + raise ValueError("Unequal group sizes") + for group in range(64): + members = world.memberships[chain] == group + if world.exceptions[chain, members].sum() != 2: + raise ValueError("Unequal exceptions") + if len(np.intersect1d(world.train_ids[chain], world.heldout_ids[chain])): + raise ValueError("QA leakage") + truth = world.city_tokens[world.defaults[chain, world.memberships[chain]]] + np.testing.assert_array_equal(world.answers[world.derived_ids[chain]], truth) + np.testing.assert_array_equal(np.sort(world.defaults[0]), np.sort(world.defaults[1])) + return { + "passed": True, + "world": world.seed, + "conditions": report, + "base_facts": world.n_base, + "queries": len(world.answers), + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "QA_train_per_chain": 1024, + "QA_heldout_per_chain": 1024, + } + + +def save_world(world, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + directory / "world.npz", + **{key: value for key, value in vars(world).items() if isinstance(value, np.ndarray)}, + ) + write_json( + directory / "metadata.json", + {"seed": world.seed, "n_base": world.n_base, "token_labels": world.token_labels}, + ) + write_json(directory / "audit.json", audit(world)) + + +def edit_pair(world, chain, support=0): + rng = rng_for(world.seed, 907, chain * 100 + support) + while True: + groups = rng.choice(64, 3, replace=False) + if len(set(world.defaults[chain, groups])) == 3: + break + coherent, exception = world.answers.copy(), world.answers.copy() + conflict_people = [] + for j, group in enumerate(groups): + new, alt = world.city_tokens[world.defaults[chain, groups[[(j + 1) % 3, (j + 2) % 3]]]] + root = world.root_ids[chain, group] + coherent[root] = exception[root] = new + members = rng.permutation( + np.flatnonzero((world.memberships[chain] == group) & ~world.exceptions[chain]) + ) + ids = world.actual_ids[chain, members] + coherent[ids] = new + exception[ids[:15]], exception[ids[15:]] = new, alt + conflict_people.extend(members[15:]) + derived = world.derived_ids[chain, world.memberships[chain] == group] + coherent[derived] = exception[derived] = new + changed = coherent != world.answers + np.testing.assert_array_equal(changed, exception != world.answers) + e, d = np.flatnonzero(changed[: world.n_base]), np.flatnonzero(changed & (world.relation >= 10)) + assert len(e) == 93 and len(d) == 96 + np.testing.assert_array_equal(np.sort(coherent[e]), np.sort(exception[e])) + # Disjoint retention strata: old exceptions, other facts of affected people, + # remaining task-chain facts, and remaining independent/cross-chain facts. + selected_people = np.isin(world.memberships[chain], groups) + selected_facts = (world.person >= 0) & selected_people[np.maximum(world.person, 0)] + old_exceptions = np.zeros(len(world.answers), dtype=bool) + old_exceptions[world.actual_ids[chain, selected_people & world.exceptions[chain]]] = True + relevant = np.isin(world.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(world.answers), -1, dtype=np.int64) + strata[~changed & old_exceptions] = 0 + strata[~changed & selected_facts & ~old_exceptions] = 1 + strata[~changed & ~selected_facts & relevant] = 2 + strata[~changed & ~selected_facts & ~relevant] = 3 + assert np.array_equal(strata >= 0, ~changed) + heldout, replay_pool = [], [] + for g in range(4): + ids = rng.permutation(np.flatnonzero((strata == g) & (world.relation < 10))) + n = max(1, int(np.ceil(0.2 * len(ids)))) + heldout.extend(ids[:n]) + replay_pool.extend(ids[n:]) + heldout.extend(np.flatnonzero((strata >= 0) & (world.relation >= 10))) + replay = rng.choice(replay_pool, min(4096, len(replay_pool)), replace=False) + return { + "coherent": coherent, + "exception": exception, + "E": e, + "D": d, + "conflict_D": world.derived_ids[chain, conflict_people], + "strata": strata, + "heldout": np.array(sorted(heldout)), + "replay": replay, + "groups": groups, + } diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_cross_continue.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_cross_continue.py new file mode 100644 index 0000000000000000000000000000000000000000..df0a21278c640164306e05b7465e24cc0e6d0df8 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_cross_continue.py @@ -0,0 +1,627 @@ +"""Protocol v2.8 P2: audited continuation of frozen crossover checkpoints.""" + +import argparse +import copy +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CHAINS, + audit, + documents, + edit_pair, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_cross_train import edit_metrics as original_edit_metrics +from .bios_cross_train import evaluate, learning_metrics, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +PARENT_STEP = 15360 +FINAL_STEP = 30720 +CHECKPOINTS = (15360, 20480, 25600, 30720) +EDIT_CHECKPOINTS = (0, 32, 128, 512) + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def continuation_sources(): + return {**source_hashes(), Path(__file__).name: file_hash(__file__)} + + +def tree_hash(value): + """Stable audit hash for nested optimizer/RNG states, without pickle metadata.""" + digest = hashlib.sha256() + + def visit(item): + if isinstance(item, torch.Tensor): + item = item.detach().cpu().contiguous() + digest.update(f"tensor:{item.dtype}:{tuple(item.shape)}:".encode()) + digest.update(item.reshape(-1).view(torch.uint8).numpy().tobytes()) + elif isinstance(item, np.ndarray): + digest.update(f"numpy:{item.dtype}:{item.shape}:".encode()) + digest.update(np.ascontiguousarray(item).tobytes()) + elif isinstance(item, dict): + digest.update(b"dict[") + for key in sorted(item, key=lambda key: (type(key).__name__, str(key))): + visit(key) + visit(item[key]) + digest.update(b"]") + elif isinstance(item, (list, tuple)): + digest.update(type(item).__name__.encode() + b"[") + for child in item: + visit(child) + digest.update(b"]") + else: + digest.update(f"{type(item).__name__}:{item!r};".encode()) + + visit(value) + return digest.hexdigest() + + +def continuation_lr(base_lr, absolute_step): + """Use the original absolute epoch; never restart warmup at a branch point.""" + return base_lr * min((absolute_step // 128 + 1) / 16, 1) + + +def validate_optimizer(optimizer_state, step, learning_rate): + states = optimizer_state["state"] + groups = optimizer_state["param_groups"] + if not states or sum(len(group["params"]) for group in groups) != len(states): + raise ValueError("Missing parent optimizer moments") + for state in states.values(): + if not {"step", "exp_avg", "exp_avg_sq"} <= state.keys(): + raise ValueError("Incomplete AdamW state") + if int(state["step"]) != step: + raise ValueError("Optimizer update count differs from checkpoint step") + for group in groups: + if group["lr"] != learning_rate or group["weight_decay"] != 0.1: + raise ValueError("Parent optimizer learning rate or decay changed") + + +def expected_exposure(world, docs, schedule, step, base_lr): + """Reconstruct original full-epoch exposure, positions, and LR-weighted exposure.""" + epochs, remainder = divmod(step, 128) + if remainder: + raise ValueError("Parent must end on a complete document epoch") + occurrence = np.bincount(docs.ravel(), minlength=world.n_base) + counts = np.bincount(schedule[:step].ravel(), minlength=len(world.answers)) + counts[: world.n_base] += epochs * occurrence + slots = np.repeat((occurrence * (epochs // 10))[:, None], 10, axis=1) + for epoch in range(epochs % 10): + arranged = np.roll(docs, epoch, axis=1) + np.add.at(slots, (arranged, np.arange(10)[None, :]), 1) + weighted = np.zeros(len(world.answers), dtype=np.float64) + weighted[: world.n_base] = occurrence * sum( + continuation_lr(base_lr, epoch * 128) for epoch in range(epochs) + ) + rates = np.repeat([continuation_lr(base_lr, i) for i in range(step)], 40) + np.add.at(weighted, schedule[:step].ravel(), rates) + return counts, slots, weighted + + +def validate_parent(parent, world, new_lr): + """Verify immutable parent provenance and the longer stream before any updates.""" + parent = Path(parent).resolve() + config = json.loads((parent / "config.json").read_text()) + study = config["study"] + if study["width"] not in (128, 256) or config["world"] not in (0, 1): + raise ValueError("P2 includes only the two declared sizes and development worlds") + if config["seed"] not in (0, 1) or config["condition"] not in ("company", "project", "neither"): + raise ValueError("Unexpected P2 initialization or organization") + if new_lr not in (0.0001, 0.0003) or (new_lr == 0.0003 and config["seed"] != 0): + raise ValueError("The sensitivity branch contains only initialization zero") + if study["steps"] != PARENT_STEP or study["lr"] != 0.0001: + raise ValueError("P2 must fork the original 15360-step, 1e-4 trajectory") + if config["sources"] != source_hashes(): + raise ValueError("Frozen parent training sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent Torch/NumPy versions differ from continuation") + if config["world"] != world.seed or config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent world/truth mismatch") + if config["prompts_sha256"] != array_hash(world.prompts): + raise ValueError("Parent query prompts changed") + for name, expected in { + "layers": 8, + "heads": study["width"] // 64, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "edit_steps": 512, + "edit_lr": 0.00003, + "retention_kl": 1.0, + }.items(): + if study[name] != expected: + raise ValueError(f"Unexpected frozen parent setting: {name}") + docs, schedule = documents(world, config["condition"]), qa_schedule(world, FINAL_STEP) + with np.load(parent / "schedule.npz") as old: + np.testing.assert_array_equal(docs, old["documents"]) + np.testing.assert_array_equal(schedule[:PARENT_STEP], old["qa"]) + if array_hash(docs) != config["documents_sha256"]: + raise ValueError("Parent document hash mismatch") + if array_hash(schedule[:PARENT_STEP]) != config["qa_sha256"]: + raise ValueError("Extended QA stream does not preserve the original prefix") + resume = torch.load(parent / "resume.pt", map_location="cpu", weights_only=False) + if resume["step"] != PARENT_STEP or resume["config_sha256"] != file_hash( + parent / "config.json" + ): + raise ValueError("Parent resume step/config mismatch") + validate_optimizer(resume["optimizer"], PARENT_STEP, study["lr"]) + saved_model = torch.load( + parent / f"model-{PARENT_STEP}.pt", map_location="cpu", weights_only=False + ) + completed = json.loads((parent / "learning-complete.json").read_text()) + model_hash = state_hash(resume["model"]) + if ( + model_hash != state_hash(saved_model["model"]) + or model_hash != completed["model_sha256"] + or saved_model["step"] != PARENT_STEP + or saved_model["config"] != config["model"] + ): + raise ValueError("Parent final model and resume state disagree") + expected = expected_exposure(world, docs, schedule, PARENT_STEP, study["lr"]) + with np.load(parent / f"predictions-{PARENT_STEP}.npz") as predictions: + for key, wanted in zip(("counts", "slots", "weighted"), expected, strict=True): + if key == "weighted": + np.testing.assert_allclose(resume[key], wanted, rtol=0, atol=1e-10) + else: + np.testing.assert_array_equal(resume[key], wanted) + stored_key = "exposure" if key == "counts" else key + np.testing.assert_array_equal(resume[key], predictions[stored_key]) + if resume["timeline"][-1]["step"] != PARENT_STEP: + raise ValueError("Parent learning history lacks the final checkpoint") + if not isinstance(resume["torch_rng"], torch.Tensor): + raise ValueError("Parent torch RNG is missing") + files = ( + "config.json", + "resume.pt", + f"model-{PARENT_STEP}.pt", + "schedule.npz", + f"predictions-{PARENT_STEP}.npz", + "learning-complete.json", + ) + provenance = { + "directory": str(parent), + "files_sha256": {name: file_hash(parent / name) for name in files}, + "model_sha256": model_hash, + "optimizer_sha256": tree_hash(resume["optimizer"]), + "torch_rng_sha256": tree_hash(resume["torch_rng"]), + "cuda_rng_sha256": tree_hash(resume["cuda_rng"]), + "qa_prefix_verified": True, + "exposure_reconstruction_verified": True, + } + return config, resume, docs, schedule, provenance + + +def restore_state(model, optimizer, saved, device): + model.load_state_dict(saved["model"]) + # load_state_dict may alias CPU tensors; branch updates must not mutate the parent. + optimizer.load_state_dict(copy.deepcopy(saved["optimizer"])) + torch.set_rng_state(saved["torch_rng"].cpu()) + if device.type == "cuda": + if saved["cuda_rng"] is None: + raise ValueError("CUDA parent/resume RNG state is missing") + torch.cuda.set_rng_state(saved["cuda_rng"].cpu(), device) + + +def capture_state(model, optimizer, device, **metadata): + return { + **metadata, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + } + + +def learning_update(model, optimizer, cache, data, qa, start, end, lr, device): + """The original arithmetic/gradient order, with an absolute-step learning rate.""" + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(cache["tokens"][start:end], cache["positions"][start:end]) + doc_loss = F.cross_entropy( + logits.float().flatten(0, 1), cache["labels"][start:end].flatten() + ) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(data["tokens"][qa], data["positions"][qa]) + qa_loss = F.cross_entropy(logits.float().flatten(0, 1), data["labels"][qa].flatten()) + (0.2 * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1) + if not torch.isfinite(doc_loss + qa_loss + norm): + raise FloatingPointError("Nonfinite continuation update") + optimizer.step() + + +def learning(parent, out, world, base_lr, device): + old_config, parent_resume, docs, schedule, provenance = validate_parent(parent, world, base_lr) + study = { + **old_config["study"], + "protocol": "v2.8-development-p2-continuation", + "steps": FINAL_STEP, + "checkpoints": list(CHECKPOINTS), + "lr": base_lr, + "edit_scopes": ["mlp"], + "seeds": [0] if base_lr == 0.0003 else [0, 1], + "learning_runs": 6 if base_lr == 0.0003 else 12, + "edit_cases": 24 if base_lr == 0.0003 else 48, + "edit_cases_per_run": 4, + "parent_step": PARENT_STEP, + "warmup": "original absolute epoch; no restart", + "primary_learning": ( + "heldout full-answer accuracy at 30720 absolute steps; " + "preserve all prespecified earlier checkpoints" + ), + "aggregation": ( + "pair organizations within world/initialization; " + "development worlds are not confirmatory replications" + ), + } + identity = { + "world": old_config["world"], + "seed": old_config["seed"], + "condition": old_config["condition"], + "study": study, + "sources": continuation_sources(), + "parent": provenance, + "model": old_config["model"], + "initial_sha256": old_config["initial_sha256"], + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + "torch": torch.__version__, + "numpy": np.__version__, + "device_type": device.type, + "cuda": torch.version.cuda, + "gpu_type": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + } + config_path = out / "config.json" + if config_path.exists(): + existing = json.loads(config_path.read_text()) + if any(existing.get(key) != value for key, value in identity.items()): + raise ValueError("Continuation identity, parent, software or sources changed") + else: + write_json( + config_path, + { + **identity, + "python": platform.python_version(), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast; FP32 weights and optimizer", + "parameters": old_config["parameters"], + }, + ) + atomic_numpy_save(out / "schedule.npz", documents=docs, qa=schedule) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + model_config = ModelConfig(**old_config["model"]) + model = CausalLM(model_config).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=base_lr, weight_decay=0.1, fused=device.type == "cuda" + ) + if (out / "resume.pt").exists(): + saved = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if saved["config_sha256"] != file_hash(config_path): + raise ValueError("Continuation resume configuration mismatch") + else: + saved = {**parent_resume, "timeline": [], "config_sha256": file_hash(config_path)} + restore_state(model, optimizer, saved, device) + first, seconds = saved["step"], saved["seconds"] + timeline = saved["timeline"] + counts, slots, weighted = saved["counts"], saved["slots"], saved["weighted"] + if not PARENT_STEP <= first <= FINAL_STEP: + raise ValueError("Continuation resume step is outside its frozen interval") + data = tensor_queries(world, device) + + def save_resume(step): + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + counts=counts, + slots=slots, + weighted=weighted, + config_sha256=file_hash(config_path), + ), + out / "resume.pt", + ) + + epoch_cached = -1 + for step in range(first, FINAL_STEP + 1): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + if step == PARENT_STEP: + with np.load(Path(parent) / f"predictions-{PARENT_STEP}.npz") as old: + arrays = { + key: old[key] for key in ("prediction", "ended", "correct", "value_nll") + } + else: + arrays = evaluate(model, data, world.answers) + point = { + "step": step, + **learning_metrics(world, arrays), + "train_seconds": seconds, + "exposure_sha256": array_hash(counts), + "slots_sha256": array_hash(slots), + "weighted_sha256": array_hash(weighted), + "train_matmul_flops_estimate": step + * (matmul_flops(model_config, 16, 60, 20) + matmul_flops(model_config, 40, 6, 2)), + } + timeline.append(point) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slots=slots, + weighted=weighted, + ) + atomic_torch_save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + write_json(out / "learning.json", timeline) + save_resume(step) + print(json.dumps({"event": "checkpoint", **point}), flush=True) + if step == FINAL_STEP: + break + epoch, offset = divmod(step, 128) + if epoch != epoch_cached: + arranged = epoch_documents(docs, world.seed, epoch) + cache = { + key: torch.as_tensor(value, device=device) + for key, value in render(world, arranged).items() + } + epoch_cached = epoch + start, end = offset * 16, (offset + 1) * 16 + qa = torch.as_tensor(schedule[step], device=device) + lr = continuation_lr(base_lr, step) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + learning_update(model, optimizer, cache, data, qa, start, end, lr, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + fact_ids = arranged[start:end] + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, schedule[step], 1) + np.add.at(slots, (fact_ids, np.arange(10)[None, :]), 1) + np.add.at(weighted, fact_ids.ravel(), lr) + np.add.at(weighted, schedule[step], lr) + if (step + 1) % 256 == 0 and step + 1 not in CHECKPOINTS: + save_resume(step + 1) + print( + json.dumps({"event": "progress", "step": step + 1, "seconds": seconds}), flush=True + ) + write_json( + out / "learning-complete.json", + { + "status": "complete", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + return model, data, study + + +def edit_metrics(world, pair, arrays, old_correct): + metrics = original_edit_metrics(world, pair, arrays, old_correct) + heldout = np.intersect1d(pair["conflict_D"], world.heldout_ids.ravel()) + metrics["D_conflict_heldout_n"] = len(heldout) + metrics["D_conflict_heldout"] = ( + float(arrays["correct"][heldout].mean()) if len(heldout) else None + ) + for label, ids in (("default", world.root_ids.ravel()), ("actual", world.actual_ids.ravel())): + subset = np.intersect1d(pair["E"], ids) + metrics[f"E_{label}_n"] = len(subset) + metrics[f"E_{label}"] = float(arrays["correct"][subset].mean()) + return metrics + + +def edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device): + model.train() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce = F.cross_entropy(logits.flatten(0, 1), new_data["labels"][ei].flatten()) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite continuation edit") + optimizer.step() + + +def edits(world, model, data, out, study, device): + baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()} + old_arrays = evaluate(model, data, world.answers) + config_sha = file_hash(out / "config.json") + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + e_choices = rng.integers(len(pair["E"]), size=(512, 128)) + r_choices = rng.integers(len(pair["replay"]), size=(512, 128)) + for kind in ("coherent", "exception"): + dest = out / "edits" / f"{name}-{kind}-mlp" + if (dest / "complete.json").exists(): + continue + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + target = pair[kind] + new_data = tensor_queries(world, device, target) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline, seconds, first = [], 0.0, 0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["config_sha256"] != config_sha or saved["case"] != dest.name: + raise ValueError("Editing resume identity mismatch") + restore_state(model, optimizer, saved, device) + timeline, seconds, first = saved["timeline"], saved["seconds"], saved["step"] + for step in range(first, 513): + if step in EDIT_CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, data, target) + point = { + "step": step, + **edit_metrics(world, pair, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + config_sha256=config_sha, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update( + model, optimizer, selected, data, new_data, references, ei, ri, choices, device + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict()}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "chain": name, + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + }, + ) + print( + json.dumps( + { + "event": "edit_complete", + "case": dest.name, + "E": timeline[-1]["E"], + "D": timeline[-1]["D"], + } + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--lr", type=float, choices=(0.0001, 0.0003), default=0.0001) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + parser.add_argument("--learning-only", action="store_true") + args = parser.parse_args() + parent, out = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == out or parent in out.parents or out in parent.parents: + raise ValueError("Continuation output must be separate from its immutable parent") + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + world = make_cross_world(json.loads((parent / "config.json").read_text())["world"]) + audit(world) + device = torch.device(args.device) + try: + model, data, study = learning(parent, out, world, args.lr, device) + if not args.learning_only: + edits(world, model, data, out, study, device) + write_json( + out / "complete.json", + { + "status": "complete", + "learning_steps": FINAL_STEP, + "edit_cases": 4, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_cross_scale.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_cross_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..af5c92edca554475a9bdf9dee9b46438455b1f96 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_cross_scale.py @@ -0,0 +1,51 @@ +"""Contracts and denominator-aware summaries for the frozen crossover size extension.""" + +from itertools import product + +import numpy as np + + +def validate_size_study(reference, study, width, heads): + expected = {**reference, "width": width, "heads": heads} + if study != expected: + changed = sorted(k for k in set(expected) | set(study) if expected.get(k) != study.get(k)) + raise ValueError(f"Non-size study changes: {changed}") + if width // heads != 64 or study["layers"] != 8: + raise ValueError("Expected eight layers and head dimension 64") + + +def validate_run_grid(configs, study, require_complete): + expected = set(product(study["worlds"], study["seeds"], study["conditions"])) + keys = [(c["world"], c["seed"], c["condition"]) for c in configs] + if len(keys) != len(set(keys)) or set(keys) - expected: + raise ValueError("Duplicate or unexpected experimental units") + if require_complete and set(keys) != expected: + raise ValueError("Missing experimental units") + + +def retention_coverage(pair, old_correct, row): + """Keep unknown facts outside the damage denominator and expose their coverage.""" + result = {} + for pool_name, pool in ( + ("full", np.arange(len(old_correct))), + ("heldout", pair["heldout"]), + ): + totals, knowns, brokens = [], [], [] + for group in range(4): + ids = np.intersect1d(pool, np.flatnonzero(pair["strata"] == group)) + prefix = f"U_{pool_name}_{group}" + total, known, broken = len(ids), int(old_correct[ids].sum()), row[f"{prefix}_broken"] + if known != row[f"{prefix}_known"] or not 0 <= broken <= known: + raise ValueError("Retention denominator or broken count mismatch") + totals.append(total) + knowns.append(known) + brokens.append(broken) + result[f"{prefix}_total"] = total + result[f"{prefix}_coverage"] = known / total if total else None + total, known, broken = sum(totals), sum(knowns), sum(brokens) + result[f"U_{pool_name}_total"] = total + result[f"U_{pool_name}_coverage"] = known / total if total else None + result[f"U_{pool_name}_micro_damage"] = broken / known if known else None + result["E_old_accuracy"] = float(old_correct[pair["E"]].mean()) + result["D_old_accuracy"] = float(old_correct[pair["D"]].mean()) + return result diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_cross_train.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_cross_train.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5f3f45a169e643c408f1044eaa766b79a595fd --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_cross_train.py @@ -0,0 +1,474 @@ +"""Frozen learning and editing runs for the two-relation crossover.""" + +import argparse +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CHAINS, + CONDITIONS, + audit, + documents, + edit_pair, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + + +def tensor_queries(world, device, answers=None): + answers = world.answers if answers is None else answers + prompts = torch.as_tensor(world.prompts, device=device) + lengths = torch.as_tensor(world.lengths, device=device) + targets = torch.as_tensor(answers, device=device) + tokens = torch.zeros((len(answers), 6), device=device, dtype=torch.long) + tokens[:, :5] = prompts + tokens[torch.arange(len(answers), device=device), lengths] = targets + tokens[lengths == 4, 5] = EOS + return { + "prompts": prompts, + "lengths": lengths, + "tokens": tokens, + "positions": torch.stack([lengths - 1, lengths], -1), + "labels": torch.stack([targets, torch.full_like(targets, EOS)], -1), + } + + +@torch.no_grad() +def evaluate(model, data, answers, batch_size=512): + model.eval() + device = data["tokens"].device + predictions, ended, nll = [], [], [] + for begin in range(0, len(answers), batch_size): + end = min(begin + batch_size, len(answers)) + lengths = data["lengths"][begin:end] + with precision(device): + logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float() + first = logits.argmax(-1) + continuation = torch.zeros((end - begin, 6), device=device, dtype=torch.long) + continuation[:, :5] = data["prompts"][begin:end] + continuation[torch.arange(end - begin, device=device), lengths] = first + second = model(continuation, lengths[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + targets = torch.as_tensor(answers[begin:end], device=device) + nll.append(F.cross_entropy(logits, targets, reduction="none").cpu().numpy()) + prediction, ended = np.concatenate(predictions), np.concatenate(ended) + return { + "prediction": prediction, + "ended": ended, + "correct": (prediction == answers) & ended, + "value_nll": np.concatenate(nll), + } + + +def learning_metrics(world, arrays): + correct = arrays["correct"] + result = { + "base_accuracy": float(correct[: world.n_base].mean()), + "base_nll": float(arrays["value_nll"][: world.n_base].mean()), + } + for chain, name in enumerate(CHAINS): + for split, ids in ( + ("trained", world.train_ids[chain]), + ("heldout", world.heldout_ids[chain]), + ): + result[f"{name}_{split}"] = float(correct[ids].mean()) + result[f"{name}_{split}_nll"] = float(arrays["value_nll"][ids].mean()) + for label, ids in ( + ("membership", world.membership_ids[chain]), + ("default", world.root_ids[chain]), + ("actual", world.actual_ids[chain]), + ): + result[f"{name}_{label}"] = float(correct[ids].mean()) + # A conditional diagnostic, never a replacement for the whole test pool. + prerequisites = ( + correct[world.membership_ids[chain]] + & correct[world.root_ids[chain, world.memberships[chain]]] + ) + known_ids = np.intersect1d( + world.heldout_ids[chain], world.derived_ids[chain, prerequisites] + ) + result[f"{name}_known_heldout_n"] = len(known_ids) + result[f"{name}_known_heldout"] = ( + float(correct[known_ids].mean()) if len(known_ids) else None + ) + result["mean_heldout"] = (result["company_heldout"] + result["project_heldout"]) / 2 + return result + + +def source_hashes(): + root = Path(__file__).parent + return { + name: hashlib.sha256((root / name).read_bytes()).hexdigest() + for name in ( + "bios_cross.py", + "bios_cross_train.py", + "bios_model.py", + "bios_data.py", + "bios_train.py", + "bios_organization_train.py", + ) + } + + +def learning(args, world, out, study, device): + torch.manual_seed(args.seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + config = ModelConfig(world.vocab_size, study["width"], study["layers"], study["heads"]) + model = CausalLM(config).to(device) + initial_hash = state_hash(model.state_dict()) + docs, schedule = documents(world, args.condition), qa_schedule(world, study["steps"]) + identity = { + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "study": study, + "sources": source_hashes(), + "model": model.config_dict(), + "initial_sha256": initial_hash, + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + } + config_path = out / "config.json" + if config_path.exists(): + saved = json.loads(config_path.read_text()) + if any(saved[k] != v for k, v in identity.items()): + raise ValueError("Frozen run identity or sources changed") + else: + write_json( + config_path, + { + **identity, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "python": platform.python_version(), + "numpy": np.__version__, + "device": str(device), + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "precision": "BF16 autocast; FP32 weights and optimizer", + "parameters": sum(p.numel() for p in model.parameters()), + }, + ) + atomic_numpy_save(out / "schedule.npz", documents=docs, qa=schedule) + data = tensor_queries(world, device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=study["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline, first, seconds = [], 0, 0.0 + counts = np.zeros(len(world.answers), dtype=np.int64) + slots = np.zeros((world.n_base, 10), dtype=np.int64) + weighted = np.zeros(len(world.answers), dtype=np.float64) + if (out / "resume.pt").exists(): + resume = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if resume["config_sha256"] != hashlib.sha256(config_path.read_bytes()).hexdigest(): + raise ValueError("Resume configuration mismatch") + model.load_state_dict(resume["model"]) + optimizer.load_state_dict(resume["optimizer"]) + first, timeline, seconds = resume["step"], resume["timeline"], resume["seconds"] + counts, slots, weighted = resume["counts"], resume["slots"], resume["weighted"] + torch.set_rng_state(resume["torch_rng"]) + if device.type == "cuda": + torch.cuda.set_rng_state(resume["cuda_rng"], device) + epoch_cached, cache = -1, None + for step in range(first, study["steps"] + 1): + if step in study["checkpoints"] and (not timeline or step != first): + arrays = evaluate(model, data, world.answers) + point = { + "step": step, + **learning_metrics(world, arrays), + "train_seconds": seconds, + "exposure_sha256": array_hash(counts), + "slots_sha256": array_hash(slots), + "weighted_sha256": array_hash(weighted), + "train_matmul_flops_estimate": step + * (matmul_flops(config, 16, 60, 20) + matmul_flops(config, 40, 6, 2)), + } + timeline.append(point) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slots=slots, + weighted=weighted, + ) + atomic_torch_save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + write_json(out / "learning.json", timeline) + atomic_torch_save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "timeline": timeline, + "seconds": seconds, + "counts": counts, + "slots": slots, + "weighted": weighted, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), + }, + out / "resume.pt", + ) + print(json.dumps({"event": "checkpoint", **point}), flush=True) + if step == study["steps"]: + break + epoch, offset = divmod(step, 128) + if epoch != epoch_cached: + arranged = epoch_documents(docs, world.seed, epoch) + cache = { + k: torch.as_tensor(v, device=device) for k, v in render(world, arranged).items() + } + epoch_cached = epoch + start, end = offset * 16, (offset + 1) * 16 + fact_ids = arranged[start:end] + qa = torch.as_tensor(schedule[step], device=device) + lr = study["lr"] * min((epoch + 1) / 16, 1) + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(cache["tokens"][start:end], cache["positions"][start:end]) + doc_loss = F.cross_entropy( + logits.float().flatten(0, 1), cache["labels"][start:end].flatten() + ) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(data["tokens"][qa], data["positions"][qa]) + qa_loss = F.cross_entropy(logits.float().flatten(0, 1), data["labels"][qa].flatten()) + (0.2 * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1) + if not torch.isfinite(doc_loss + qa_loss + norm): + raise FloatingPointError("Nonfinite learning update") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, schedule[step], 1) + np.add.at(slots, (fact_ids, np.arange(10)[None, :]), 1) + np.add.at(weighted, fact_ids.ravel(), lr) + np.add.at(weighted, schedule[step], lr) + if (step + 1) % 256 == 0: + print( + json.dumps({"event": "progress", "step": step + 1, "seconds": seconds}), flush=True + ) + write_json( + out / "learning-complete.json", + { + "status": "complete", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + return model, data + + +def edit_metrics(world, pair, arrays, old_correct): + correct = arrays["correct"] + metrics = { + "E": float(correct[pair["E"]].mean()), + "D": float(correct[pair["D"]].mean()), + "D_conflict": float(correct[pair["conflict_D"]].mean()), + } + for split, ids in ( + ("trained", world.train_ids.ravel()), + ("heldout", world.heldout_ids.ravel()), + ): + subset = np.intersect1d(pair["D"], ids) + metrics[f"D_{split}_n"] = len(subset) + metrics[f"D_{split}"] = float(correct[subset].mean()) if len(subset) else None + for name, pool in (("full", np.arange(len(correct))), ("heldout", pair["heldout"])): + strata = {} + for group in range(4): + ids = np.intersect1d(pool, np.flatnonzero((pair["strata"] == group) & old_correct)) + strata[str(group)] = { + "known": len(ids), + "broken": int((~correct[ids]).sum()), + "rate": float((~correct[ids]).mean()) if len(ids) else None, + } + metrics[f"U_{name}"] = strata + return metrics + + +def edits(args, world, model, data, out, study, device): + baseline = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()} + old_arrays = evaluate(model, data, world.answers) + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + e_choices = rng.integers(len(pair["E"]), size=(study["edit_steps"], 128)) + r_choices = rng.integers(len(pair["replay"]), size=(study["edit_steps"], 128)) + for kind in ("coherent", "exception"): + target = pair[kind] + new_data = tensor_queries(world, device, target) + for scope in ("mlp", "all"): + dest = out / "edits" / f"{name}-{kind}-{scope}" + if (dest / "complete.json").exists(): + continue + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, scope, 3) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append( + model(data["tokens"][ids], data["positions"][ids]).detach() + ) + references = torch.cat(references) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline = [] + seconds = 0.0 + for step in range(study["edit_steps"] + 1): + if step in study["edit_checkpoints"]: + arrays = evaluate(model, data, target) + point = { + "step": step, + **edit_metrics(world, pair, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step == study["edit_steps"]: + break + model.train() + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce = F.cross_entropy(logits.flatten(0, 1), new_data["labels"][ei].flatten()) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + study["retention_kl"] * kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite edit") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict()}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "chain": name, + "kind": kind, + "scope": scope, + "final": timeline[-1], + }, + ) + print( + json.dumps( + { + "event": "edit_complete", + "case": dest.name, + "E": timeline[-1]["E"], + "D": timeline[-1]["D"], + } + ), + flush=True, + ) + del references, optimizer + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--config", default="configs/bios-cross-development-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + args = parser.parse_args() + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + study = json.loads(Path(args.config).read_text()) + torch.set_num_threads(args.threads) + device = torch.device(args.device) + world = make_cross_world(args.world) + audit(world) + try: + model, data = learning(args, world, out, study, device) + edits(args, world, model, data, out, study, device) + write_json( + out / "complete.json", + { + "status": "complete", + "learning_steps": study["steps"], + "edit_cases": 8, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_data.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3acf9b51a11985eb747a2c2565bc551ae803fd9b --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_data.py @@ -0,0 +1,367 @@ +"""bioS-Work-v1 truth, equal-exposure curricula and paired counterfactual worlds. + +Official files remain unmodified in data/bios-source; this is a new adapter. +The symbolic experiment does not imply that the natural-language audit is complete. +""" + +import calendar +import hashlib +import json +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +REVISION = "211b28f2e9d453114ca5a1cbbb2d5a632ac60fcf" +SOURCE_FOLDER = "data-synthetic-pretrain/Capo-bioS-bioR" +RELATIONS = ( + "employer", + "default_city", + "actual_city", + "birth_date", + "birth_city", + "university", + "major", +) +N_PEOPLE, N_COMPANIES, N_BASE, N_QUERIES = 2048, 64, 12352, 14400 +PAD, BOS, ANS, EOS = range(4) + + +def rng_for(seed, purpose, index=0): + return np.random.default_rng(np.random.SeedSequence([seed, purpose, index])) + + +def array_hash(array): + return hashlib.sha256(np.ascontiguousarray(array).tobytes()).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, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temporary.replace(path) + + +@dataclass +class World: + seed: int + prompts: np.ndarray + lengths: np.ndarray + answers: np.ndarray + relation: np.ndarray + person: np.ndarray + company: np.ndarray + employers: np.ndarray + defaults: np.ndarray + actual: np.ndarray + exceptions: np.ndarray + city_tokens: np.ndarray + token_labels: list + names: dict + + @property + def vocab_size(self): + return len(self.token_labels) + + def save(self, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + arrays = {k: v for k, v in vars(self).items() if isinstance(v, np.ndarray)} + np.savez_compressed(directory / "world.npz", **arrays) + write_json( + directory / "metadata.json", + {"seed": self.seed, "token_labels": self.token_labels, "names": self.names}, + ) + write_json(directory / "audit.json", audit_world(self)) + + +def load_world(directory): + directory = Path(directory) + metadata = json.loads((directory / "metadata.json").read_text()) + with np.load(directory / "world.npz", allow_pickle=False) as arrays: + return World(**metadata, **dict(arrays)) + + +def make_world(seed, source_root="data/bios-source"): + source_root = Path(source_root) + manifest = json.loads((source_root / "manifest.json").read_text()) + if manifest["revision"] != REVISION: + raise ValueError("Unexpected official source revision") + for entry in manifest["files"]: + if ( + hashlib.sha256((source_root / entry["path"]).read_bytes()).hexdigest() + != entry["sha256"] + ): + raise ValueError("Source hash mismatch: " + entry["path"]) + + def field(name): + return (source_root / SOURCE_FOLDER / "fields" / (name + ".txt")).read_text().splitlines() + + cities, universities, majors = field("city"), field("university"), field("field") + first, middle, last = field("first_name"), field("middle_name"), field("last_name") + names_rng, group_rng, value_rng = (rng_for(seed, i) for i in (11, 12, 13)) + + def unique_names(count): + result, used = [], set() + while len(result) < count: + value = f"{names_rng.choice(first)} {names_rng.choice(middle)} {names_rng.choice(last)}" + if value.casefold() not in used: + result.append(value) + used.add(value.casefold()) + return result + + person_names = unique_names(2 * N_PEOPLE) + syllables = ("va", "ne", "ri", "lo", "sa", "tu", "mi", "ze", "ka", "po", "da", "fi") + company_names, used = [], set() + while len(company_names) < 2 * N_COMPANIES: + value = "".join(names_rng.choice(syllables, 4)).capitalize() + " Labs" + if value not in used: + used.add(value) + company_names.append(value) + employers = group_rng.permutation(np.repeat(np.arange(N_COMPANIES), 32)) + work_cities = value_rng.choice(len(cities), 32, replace=False) + defaults = value_rng.permutation(np.repeat(work_cities, 2)) + exceptions = np.zeros(N_PEOPLE, dtype=bool) + actual = defaults[employers].copy() + for c in range(N_COMPANIES): + selected = group_rng.choice(np.flatnonzero(employers == c), 2, replace=False) + exceptions[selected] = True + actual[selected] = value_rng.choice(work_cities[work_cities != defaults[c]], 2) + attributes_rng = rng_for(seed, 14) + years = attributes_rng.integers(1900, 2100, N_PEOPLE) + months = attributes_rng.integers(1, 13, N_PEOPLE) + days = attributes_rng.integers(1, 29, N_PEOPLE) + dates = [ + f"{calendar.month_name[m]} {d}, {y}" for y, m, d in zip(years, months, days, strict=True) + ] + birth_cities = attributes_rng.integers(0, len(cities), N_PEOPLE) + university = attributes_rng.integers(0, len(universities), N_PEOPLE) + major = attributes_rng.integers(0, len(majors), N_PEOPLE) + labels = ( + [f"person:{i}" for i in range(N_PEOPLE)] + + [f"company:{i}" for i in range(N_COMPANIES)] + + [f"city:{i}" for i in range(len(cities))] + + [f"date:{d}" for d in sorted(set(dates))] + + [f"university:{i}" for i in range(len(universities))] + + [f"major:{i}" for i in range(len(majors))] + + [f"relation:{r}" for r in RELATIONS] + ) + labels = list(rng_for(seed, 15).permutation(labels)) + token_labels = ["", "", "", ""] + labels + token = {label: i for i, label in enumerate(token_labels)} + city_tokens = np.array([token[f"city:{i}"] for i in range(len(cities))]) + prompts = np.full((N_QUERIES, 5), PAD, dtype=np.int64) + lengths = np.full(N_QUERIES, 4, dtype=np.int64) + answers = np.empty(N_QUERIES, dtype=np.int64) + relation = np.empty(N_QUERIES, dtype=np.int64) + person = np.full(N_QUERIES, -1, dtype=np.int64) + company = np.empty(N_QUERIES, dtype=np.int64) + values = [ + [token[f"company:{c}"] for c in employers], + city_tokens[defaults], + city_tokens[actual], + [token[f"date:{d}"] for d in dates], + city_tokens[birth_cities], + [token[f"university:{u}"] for u in university], + [token[f"major:{m}"] for m in major], + ] + offset = 0 + for rel, rel_values in enumerate(values): + for i, value in enumerate(rel_values): + q = offset + i + is_company = rel == 1 + subject = token[f"company:{i}" if is_company else f"person:{i}"] + prompts[q, :4] = [BOS, subject, token[f"relation:{RELATIONS[rel]}"], ANS] + answers[q], relation[q] = value, rel + company[q] = i if is_company else employers[i] + if not is_company: + person[q] = i + offset += len(rel_values) + for i in range(N_PEOPLE): + q = N_BASE + i + prompts[q] = [ + BOS, + token[f"person:{i}"], + token["relation:employer"], + token["relation:default_city"], + ANS, + ] + answers[q] = city_tokens[defaults[employers[i]]] + lengths[q], relation[q], person[q], company[q] = 5, 7, i, employers[i] + names = { + "people": person_names[:N_PEOPLE], + "people_aliases": person_names[N_PEOPLE:], + "companies": company_names[:N_COMPANIES], + "company_aliases": company_names[N_COMPANIES:], + "company_source_ids": names_rng.choice( + len(field("company")), N_COMPANIES, replace=False + ).tolist(), + "cities": cities, + "universities": universities, + "majors": majors, + "work_city_ids": work_cities.tolist(), + } + world = World( + seed, + prompts, + lengths, + answers, + relation, + person, + company, + employers, + defaults, + actual, + exceptions, + city_tokens, + token_labels, + names, + ) + audit_world(world) + return world + + +def curriculum(world, order, total_steps, batch_size=128): + if order not in {"SA", "AS"} or total_steps < 5280 or batch_size != 128: + raise ValueError("Protocol curriculum requires SA/AS, >=5280 steps and batch 128") + s = np.flatnonzero(np.isin(world.relation[:N_BASE], [0, 1])) + a = np.flatnonzero(~np.isin(world.relation[:N_BASE], [0, 1])) + parts = {} + for name, ids, repeats, purpose in (("S", s, 160, 21), ("A", a, 33, 22)): + rng = rng_for(world.seed, purpose) + parts[name] = np.concatenate([rng.permutation(ids) for _ in range(repeats)]) + assert len(parts[name]) == 337920 + rng = rng_for(world.seed, 23) + n_mix = (total_steps - 5280) * batch_size + # Exact 80:20 across each five-step block; final partial block is recorded. + n_derived = n_mix // 5 + n_atomic = n_mix - n_derived + atomic = np.concatenate([rng.permutation(N_BASE) for _ in range(n_atomic // N_BASE + 1)])[ + :n_atomic + ] + derived = N_BASE + np.tile(rng.permutation(N_PEOPLE), n_derived // N_PEOPLE + 1)[:n_derived] + mixed = np.empty(n_mix, dtype=np.int64) + derived_positions = np.arange(4, n_mix, 5) + mixed[derived_positions] = derived + is_atomic = np.ones(n_mix, dtype=bool) + is_atomic[derived_positions] = False + mixed[is_atomic] = atomic + return np.concatenate([parts[order[0]], parts[order[1]], mixed]).reshape( + total_steps, batch_size + ) + + +def paired_edit(world, support=0, k=1): + if k not in (1, 4, 16): + raise ValueError("Protocol scales are 1, 4 and 16") + rng = rng_for(world.seed, 31, support + 100 * k) + # Draw whole disjoint supports until every triple has three different defaults. + for _ in range(100000): + companies = rng.choice(N_COMPANIES, 3 * k, replace=False).reshape(k, 3) + if all(len(set(world.defaults[t])) == 3 for t in companies): + break + else: + raise RuntimeError("No valid support") + coherent, exception = world.answers.copy(), world.answers.copy() + for triple in companies: + old = world.defaults[triple] + for j, c in enumerate(triple): + next_city, alternate = old[(j + 1) % 3], old[(j + 2) % 3] + root = 2048 + c + coherent[root] = exception[root] = world.city_tokens[next_city] + members = rng.permutation(np.flatnonzero((world.employers == c) & ~world.exceptions)) + rows = 2112 + members + coherent[rows] = world.city_tokens[next_city] + exception[rows[:15]], exception[rows[15:]] = ( + world.city_tokens[next_city], + world.city_tokens[alternate], + ) + derived = N_BASE + np.flatnonzero(world.employers == c) + coherent[derived] = exception[derived] = world.city_tokens[next_city] + edit_mask = coherent != world.answers + assert np.array_equal(edit_mask, exception != world.answers) + e = np.flatnonzero(edit_mask & (np.arange(N_QUERIES) < N_BASE)) + d = np.flatnonzero(edit_mask & (np.arange(N_QUERIES) >= N_BASE)) + u = ~edit_mask + selected = np.isin(world.company, companies.ravel()) + old_exception = (world.relation == 2) & world.exceptions[np.maximum(world.person, 0)] + strata = np.full(N_QUERIES, -1, dtype=np.int64) + strata[u & selected & old_exception] = 0 + strata[u & selected & ~old_exception] = 1 + strata[u & ~selected & np.isin(world.relation, [1, 2, 7])] = 2 + strata[u & ~selected & np.isin(world.relation, [0, 3, 4, 5, 6])] = 3 + assert np.array_equal(strata >= 0, u) + assert len(e) == 93 * k and len(d) == 96 * k + assert np.array_equal( + np.bincount(coherent[e], minlength=world.vocab_size), + np.bincount(exception[e], minlength=world.vocab_size), + ) + split_rng = rng_for(world.seed, 32, support + 100 * k) + replay_pool, heldout = [], [] + for group in range(4): + ids = split_rng.permutation( + np.flatnonzero((strata == group) & (np.arange(N_QUERIES) < N_BASE)) + ) + n_test = max(1, int(np.ceil(0.2 * len(ids)))) + heldout.extend(ids[:n_test]) + replay_pool.extend(ids[n_test:]) + heldout.extend(np.flatnonzero(u & (np.arange(N_QUERIES) >= N_BASE))) + replay = split_rng.choice(replay_pool, min(4096, len(replay_pool)), replace=False) + return { + "companies": companies, + "coherent": coherent, + "exception": exception, + "E": e, + "D": d, + "strata": strata, + "replay": replay, + "heldout": np.array(sorted(heldout)), + "support": support, + "k": k, + "selection": "prespecified_unmatched", + } + + +def audit_world(world): + assert world.prompts.shape == (N_QUERIES, 5) + assert len(set(map(tuple, world.prompts))) == N_QUERIES + assert np.array_equal(np.bincount(world.employers), np.full(N_COMPANIES, 32)) + assert np.array_equal(np.unique(world.defaults, return_counts=True)[1], np.full(32, 2)) + assert world.exceptions.sum() == 128 + assert np.array_equal( + np.bincount(world.employers[world.exceptions], minlength=64), np.full(64, 2) + ) + assert np.array_equal(world.actual != world.defaults[world.employers], world.exceptions) + assert np.array_equal(world.answers[2112:4160], world.city_tokens[world.actual]) + assert np.array_equal( + world.answers[N_BASE:], world.city_tokens[world.defaults[world.employers]] + ) + for key, alias in (("people", "people_aliases"), ("companies", "company_aliases")): + names = world.names[key] + world.names[alias] + assert len(set(n.casefold().strip() for n in names)) == len(names) + baseline = {} + for relation in range(7): + values = world.answers[world.relation == relation] + answer = int(np.bincount(values, minlength=world.vocab_size).argmax()) + baseline[RELATIONS[relation]] = { + "answer_token": answer, + "accuracy": float(np.mean(values == answer)), + } + return { + "version": "bioS-Work-v1", + "world_seed": world.seed, + "source_revision": REVISION, + "base_facts": N_BASE, + "derived_queries": N_PEOPLE, + "people": N_PEOPLE, + "companies": N_COMPANIES, + "old_exceptions": 128, + "vocab_size": world.vocab_size, + "truth_sha256": array_hash(world.answers), + "queries_sha256": array_hash(world.prompts), + "majority_baseline": baseline, + "oracle_default_baseline": {"overall": 0.9375, "old_exception": 0.0, "nonexception": 1.0}, + "symbolic_truth_audit": "passed", + "natural_language_audit": "not_complete; not used in symbolic run", + } diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_direction.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_direction.py new file mode 100644 index 0000000000000000000000000000000000000000..15e8d1db07bd56a73048608a8d9dfb99e5737a7a --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_direction.py @@ -0,0 +1,617 @@ +"""Target-complete direction experiments; batched independent down-only editors. + +The randomized generalized Gauss--Newton sketch is a diagnostic solver, not +AlphaEdit/CrispEdit. Every finite hard-constraint proposal is checked against the +original parent. Training batches contain E/R only; evaluation has no gradients. +""" + +import hashlib +import itertools +import json +import time +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +NODES = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024) +ARMS = tuple( + "-".join(x) for x in itertools.product(("func", "repr"), ("soft", "hard"), ("adam", "gn")) +) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def stable_order(values, *key): + return sorted(values, key=lambda i: hashlib.sha256(f"{key}:{int(i)}".encode()).hexdigest()) + + +def load_parent(path, device): + saved = torch.load(path, map_location=device, weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])).to(device).eval() + model.load_state_dict(saved["model"]) + for parameter in model.parameters(): + parameter.requires_grad_(False) + return model + + +@dataclass +class Task: + name: str + tokens: torch.Tensor + positions: torch.Tensor + labels: torch.Tensor + old_labels: torch.Tensor + sets: dict + metadata: dict + + def manifest(self): + return { + "name": self.name, + "sets": self.sets, + "metadata": self.metadata, + "labels": self.labels.cpu().tolist(), + "old_labels": self.old_labels.cpu().tolist(), + "tokens_sha256": hashlib.sha256(self.tokens.cpu().numpy().tobytes()).hexdigest(), + } + + +def minimal_task(seed, person, kind, device, labels=None): + people = torch.arange(32, device=device).repeat_interleave(3) + relation = torch.arange(3, device=device).repeat(32) + tokens = torch.stack( + (torch.ones_like(people), 3 + people, 35 + relation, torch.full_like(people, 2)), -1 + ) + old = 38 + (people + (relation == 2)) % 3 if labels is None else labels.to(device) + old = old[:, None] + desired = old.clone() + first, second = (0, 1) if seed % 2 == 0 else (1, 0) + i, j, k = 3 * person + first, 3 * person + second, 3 * person + 2 + c = int(old[i, 0]) + assert int(old[j, 0]) == c + a, b = 38 + (c - 38 + 1) % 3, 38 + (c - 38 + 2) % 3 + desired[i] = a if kind == "coherent" else b + e, local = [i], [k] + if kind != "selective": + desired[j] = a + e.append(j) + else: + local.append(j) + remaining = stable_order([x for x in range(32) if x != person], "split", person, 271520) + + def expand(xs): + return [3 * p + r for p in xs for r in range(3)] + + sets = { + "E": e, + "R": local + expand(remaining[:15]), + "V": expand(remaining[15:23]), + "U": expand(remaining[23:]), + "local": local, + } + return Task( + f"seed-{seed}-person-{person}-{kind}", + tokens, + torch.full((96, 1), 3, device=device), + desired, + old, + sets, + {"seed": seed, "person": person, "kind": kind, "a": a, "b": b, "c": c, "pair": [i, j]}, + ) + + +class Suffix: + """Frozen prefix cached for independent weight matrices (batch axis zero).""" + + def __init__(self, model, layer, tokens, positions): + self.model, self.layer, self.positions = model, layer, positions + if tokens.ndim == 2: + tokens = tokens[None] + self.positions = positions[None] + self.n, self.q, self.t = tokens.shape + with torch.no_grad(): + flat = tokens.reshape(-1, self.t) + x = model.token(flat) + model.position(torch.arange(self.t, device=flat.device)) + for block in model.blocks[:layer]: + x = block(x) + block = model.blocks[layer] + x = x + block.attention(block.ln1(x)) + self.base = (x + block.mlp.down.bias).reshape(self.n, self.q, self.t, -1).detach() + self.z = ( + block.mlp.activation(block.mlp.up(block.ln2(x))) + .reshape(self.n, self.q, self.t, -1) + .detach() + ) + self.forward_calls = 0 + + def __call__(self, w): + self.forward_calls += 1 + n = w.shape[0] + x = self.base + torch.einsum("nqtk,ndk->nqtd", self.z.expand(n, -1, -1, -1), w) + x = x.reshape(n * self.q, self.t, -1) + for block in self.model.blocks[self.layer + 1 :]: + x = block(x) + x = self.model.ln_final(x).reshape(n, self.q, self.t, -1) + positions = self.positions.expand(n, -1, -1) + x = x.gather(2, positions[..., None].expand(-1, -1, -1, x.shape[-1])) + return F.linear(x, self.model.token.weight) + + +def candidate_configs(arm): + obj, form, solver = arm.split("-") + rates = (1e-4, 1e-3, 1e-2) if solver == "adam" else (0.1, 0.3, 1.0) + levels = ( + (0.0, 1.0, 10.0, 100.0) + if form == "soft" + else ((0.0, 1e-6, 1e-4, 1e-2) if obj == "repr" else (1e-6, 1e-4, 1e-2, 0.1)) + ) + return [ + dict(lr=lr, level=level, damping=0.01, rank=8, refresh=16, trust_fraction=0.05) + for lr, level in itertools.product(rates, levels) + ] + + +def gaussian_newton_sketch(logits, w, weights, rank, generator): + """E[U^T U] = weighted CE GGN; independent probes per example/logit. + + B = diag(sqrt(p)) - p sqrt(p)^T satisfies BB^T = diag(p)-pp^T. + Frozen probes are differentiated through logits only, never through p. + """ + probability = logits.detach().softmax(-1) + result = [] + for _ in range(rank): + noise = torch.randn(probability.shape, device=w.device, dtype=w.dtype, generator=generator) + raw = probability.sqrt() * noise + probe = raw - probability * raw.sum(-1, keepdim=True) + probe *= weights.sqrt()[..., None] / np.sqrt(rank) + result.append( + torch.autograd.grad(logits, w, probe, retain_graph=True)[0].detach().flatten(1) + ) + return torch.stack(result, 1) + + +def inverse_sketch(v, sketch, damping): + """(damping I + U^T U)^-1 v via an exact rank-r dual solve.""" + shape = v.shape + flat = v.flatten(1) + if sketch is None: + return v / damping + k = sketch @ sketch.transpose(-1, -2) + k.diagonal(dim1=-2, dim2=-1).add_(damping) + coeff = torch.linalg.solve(k.double(), (sketch @ flat[..., None]).double()).to(v.dtype) + return ((flat - (sketch.transpose(-1, -2) @ coeff)[..., 0]) / damping).reshape(shape) + + +def representation_geometry(suffix, rmask, w0): + z = suffix.z + mask = rmask[..., None].expand(-1, -1, z.shape[2]) + # Fixed sequence length; in cross tasks only positions <= last supervised index. + valid = ( + torch.arange(z.shape[2], device=z.device)[None, None, :] + <= suffix.positions.max(-1).values[..., None] + ) + mask = mask * valid + covariance = ( + torch.einsum("nqtk,nqtl,nqt->nkl", z.double(), z.double(), mask.double()) + / mask.sum((1, 2))[:, None, None] + ) + output = torch.einsum("nqtk,dk->nqtd", z, w0) + suffix.model.blocks[suffix.layer].mlp.down.bias + scale = (output.square().sum(-1) * mask).sum((1, 2)) / mask.sum((1, 2)) + covariance = covariance / scale[:, None, None].clamp_min(1e-12) + suffix.repr_factor = ( + z * (mask / (mask.sum((1, 2)) * scale).clamp_min(1e-12)[:, None, None]).sqrt()[..., None] + ) + vals, vecs = torch.linalg.eigh(covariance.double()) + threshold = vals[:, -1:] * 1e-10 + keep = vals > threshold + null = (vecs * (~keep)[:, None, :]) @ vecs.transpose(-1, -2) + return covariance.to(w0.dtype), null.to(w0.dtype), keep.sum(-1), vals + + +def batch_setup(model, layer, tasks, configs): + ids = [t.sets["E"] + t.sets["R"] for t in tasks] + assert len(set(map(len, ids))) == 1 + toks = torch.stack([t.tokens[i] for t, i in zip(tasks, ids, strict=True)]) + positions = torch.stack([t.positions[i] for t, i in zip(tasks, ids, strict=True)]) + labels = torch.stack([t.labels[i] for t, i in zip(tasks, ids, strict=True)]) + suffix = Suffix(model, layer, toks, positions) + n, q, o = labels.shape + ermask = torch.zeros((n, q), device=toks.device) + for row, task in enumerate(tasks): + ermask[row, : len(task.sets["E"])] = 1 + rmask = 1 - ermask + eweight, rweight = ermask / ermask.sum(-1, keepdim=True), rmask / rmask.sum(-1, keepdim=True) + w0 = model.blocks[layer].mlp.down.weight.detach().clone() + with torch.no_grad(): + ref = suffix(w0[None].expand(n, -1, -1)).double().log_softmax(-1) + covariance, null, ranks, spectrum = representation_geometry(suffix, rmask, w0) + return suffix, labels, eweight, rweight, ref, covariance, null, ranks, spectrum, w0 + + +def quantities(logits, w, w0, labels, eweight, rweight, ref, covariance, obj, repr_factor): + logp = logits.double().log_softmax(-1) + ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1) + le, lr = (ce * eweight).sum(-1), (ce * rweight).sum(-1) + if obj == "func": + distance = ((ref.exp() * (ref - logp)).sum(-1).mean(-1) * rweight).sum(-1).clamp_min(0) + else: + delta = w - w0 + change = torch.einsum("nqtk,ndk->nqtd", repr_factor, delta) + distance = change.double().square().sum((1, 2, 3)) + return le, lr, distance + + +@torch.no_grad() +def evaluate_weights(model, layer, tasks, weights): + result = [] + # One run at a time keeps evaluation memory bounded for the 8-layer model. + for task, w in zip(tasks, weights, strict=True): + suffix = Suffix(model, layer, task.tokens, task.positions) + logits = suffix(w[None])[0] + parent_logits = suffix(model.blocks[layer].mlp.down.weight[None])[0] + pred = logits.argmax(-1) + old_pred = parent_logits.argmax(-1) + correct = pred.eq(task.labels).all(-1) + old_correct = old_pred.eq(task.old_labels).all(-1) + if task.labels.shape[1] == 2: + # EOS must be generated after the model's own answer, not the target. + tokens = task.tokens.clone() + lengths = task.positions[:, 0] + 1 + tokens[torch.arange(len(tokens), device=tokens.device), lengths] = pred[:, 0] + generated = Suffix(model, layer, tokens, lengths[:, None])(w[None])[0, :, 0].argmax(-1) + tokens[torch.arange(len(tokens), device=tokens.device), lengths] = old_pred[:, 0] + old_generated = Suffix(model, layer, tokens, lengths[:, None])( + model.blocks[layer].mlp.down.weight[None] + )[0, :, 0].argmax(-1) + correct = pred[:, 0].eq(task.labels[:, 0]) & generated.eq(3) + old_correct = old_pred[:, 0].eq(task.old_labels[:, 0]) & old_generated.eq(3) + nll = -logits.log_softmax(-1).gather(-1, task.labels[..., None])[..., 0].mean(-1) + row = {"sets": {}, "prediction": pred[:, 0].cpu().tolist()} + for key, ids in task.sets.items(): + indices = torch.tensor(ids, device=w.device, dtype=torch.long) + known = old_correct[indices] + row["sets"][key] = { + "n": len(ids), + "correct": int(correct[indices].sum()), + "old_known": int(known.sum()), + "broken": int((known & ~correct[indices]).sum()), + "nll": float(nll[indices].mean()) if ids else None, + } + e, local, u = (row["sets"][x] for x in ("E", "local", "U")) + row["joint"] = e["correct"] == e["n"] and local["broken"] == 0 and u["broken"] == 0 + row["e_joint"] = e["correct"] == e["n"] + pair = task.metadata.get("pair", task.sets["E"][:2]) + a, b, c = (task.metadata[x] for x in ("a", "b", "c")) + row["margins"] = { + "ab": (logits[pair, 0, a] - logits[pair, 0, b]).cpu().tolist(), + "ac": (logits[pair, 0, a] - logits[pair, 0, c]).cpu().tolist(), + "bc": (logits[pair, 0, b] - logits[pair, 0, c]).cpu().tolist(), + } + result.append(row) + return result + + +def edit_batch(model, layer, tasks, arm, configs, steps, directory, evaluate=True): + """Each batch member is an independent run; no cross-run loss/normalization.""" + directory = Path(directory) + if (directory / "complete.json").exists(): + return json.loads((directory / "metrics.json").read_text()) + directory.mkdir(parents=True, exist_ok=True) + obj, form, solver = arm.split("-") + setup = batch_setup(model, layer, tasks, configs) + suffix, labels, ew, rw, ref, cov, null, ranks, spectrum, w0 = setup + device = w0.device + n = len(tasks) + w = w0[None].expand(n, -1, -1).clone().requires_grad_() + m, v = torch.zeros_like(w), torch.zeros_like(w) + lr = torch.tensor([c["lr"] for c in configs], device=device) + level = torch.tensor([c["level"] for c in configs], device=device) + damping = configs[0]["damping"] + rank, refresh = configs[0]["rank"], configs[0]["refresh"] + strict = (level == 0) & (form == "hard") & (obj == "repr") + age = torch.zeros(n, device=device, dtype=torch.long) + failed = torch.zeros_like(age) + active = torch.ones(n, device=device, dtype=torch.bool) + sketch = None + generator = torch.Generator(device=device).manual_seed(271521) + records = [ + dict(task=t.manifest(), config=c, arm=arm, timeline=[]) + for t, c in zip(tasks, configs, strict=True) + ] + traces, checkpoints = [], {} + pair_columns = torch.tensor( + [[(t.sets["E"] + t.sets["R"]).index(i) for i in t.metadata["pair"]] for t in tasks], + device=device, + ) + answers_a = torch.tensor([t.metadata["a"] for t in tasks], device=device) + answers_b = torch.tensor([t.metadata["b"] for t in tasks], device=device) + rows = torch.arange(n, device=device) + counters = dict( + forward_batches=0, + backward_batches=0, + ggn_vjps=0, + line_search_batches=0, + covariance_eigh=1, + train_examples_per_batch=labels.shape[1], + batch_runs=n, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.monotonic() + limit = 11 * steps + 10 + for attempt in range(limit + 1): + if ( + attempt == 0 + or (attempt in NODES and attempt <= steps) + or not active.any() + or attempt == limit + ): + if device.type == "cuda": + torch.cuda.synchronize(device) + metrics = ( + evaluate_weights(model, layer, tasks, w.detach()) + if evaluate + else [dict() for _ in tasks] + ) + for j, metric in enumerate(metrics): + records[j]["timeline"].append( + dict( + attempt=attempt, + accepted=int(age[j]), + seconds=time.monotonic() - start, + **metric, + ) + ) + checkpoints[str(attempt)] = w.detach().cpu().clone() + if attempt and (not active.any() or attempt == limit): + break + if attempt >= steps and torch.all((age >= steps) | ~active): + break + logits = suffix(w) + le, lretain, distance = quantities( + logits, w, w0, labels, ew, rw, ref, cov, obj, suffix.repr_factor + ) + pair_gradients = None + if attempt in NODES: + pair_margin = torch.stack( + [ + logits[rows, pair_columns[:, i], 0, answers_a] + - logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + pair_gradients = torch.stack( + [ + torch.autograd.grad(pair_margin[:, i].sum(), w, retain_graph=True)[0].detach() + for i in range(2) + ], + 1, + ) + counters["backward_batches"] += 2 + data_loss = le + lretain + objective = data_loss + level * distance if form == "soft" else data_loss + if solver == "gn" and (sketch is None or attempt % refresh == 0 or failed.any()): + weights = ((ew + rw) / labels.shape[2])[..., None].expand_as(labels) + if form == "soft" and obj == "func": + weights = ((ew + (1 + level[:, None]) * rw) / labels.shape[2])[..., None].expand_as( + labels + ) + sketch = gaussian_newton_sketch(logits, w, weights, rank, generator) + if strict.any(): + projected = (sketch.reshape(n, rank, *w0.shape) @ null[:, None]).flatten(2) + sketch = torch.where(strict[:, None, None], projected, sketch) + counters["ggn_vjps"] += rank + g = torch.autograd.grad(objective.sum(), w, retain_graph=form == "hard")[0] + counters["backward_batches"] += 1 + if form == "hard": + a = torch.autograd.grad(distance.sum(), w)[0] + counters["backward_batches"] += 1 + else: + a = None + if solver == "adam": + m_new = 0.9 * m + 0.1 * g + v_new = 0.999 * v + 0.001 * g.square() + t = (age + 1).float()[:, None, None] + raw = -(m_new / (1 - 0.9**t)) / ((v_new / (1 - 0.999**t)).sqrt() + 1e-8) + proposal = lr[:, None, None] * raw + else: + if strict.any(): + g = torch.where(strict[:, None, None], g @ null, g) + if obj == "repr" and form == "soft": + # Exact representation Hessian plus damped sketched data GGN, CG. + def hv(x, sketch=sketch): + flat = x.flatten(1) + return ( + damping * x + + (sketch.transpose(-1, -2) @ (sketch @ flat[..., None]))[ + ..., 0 + ].reshape_as(x) + + 2 * level[:, None, None] * (x @ cov) + ) + + direction = torch.zeros_like(g) + residual, search = -g.clone(), -g.clone() + rr = residual.square().sum((-1, -2)) + for _ in range(16): + hp = hv(search) + alpha = rr / (search * hp).sum((-1, -2)).clamp_min(1e-30) + direction += alpha[:, None, None] * search + residual -= alpha[:, None, None] * hp + new_rr = residual.square().sum((-1, -2)) + search = residual + (new_rr / rr.clamp_min(1e-30))[:, None, None] * search + rr = new_rr + proposal = lr[:, None, None] * direction + else: + proposal = -lr[:, None, None] * inverse_sketch(g, sketch, damping) + # Fixed Euclidean trust radius, no hidden per-run gradient scaling. + radius = configs[0]["trust_fraction"] * w0.norm() + proposal *= (radius / proposal.flatten(1).norm(dim=1).clamp_min(1e-12)).clamp(max=1)[ + :, None, None + ] + m_new, v_new = m, v + if form == "hard": + if strict.any(): + proposal = torch.where(strict[:, None, None], proposal @ null, proposal) + metric_a = a if solver == "adam" else inverse_sketch(a, sketch, damping) + # Sequential quadratic subproblem with a linearized ORIGINAL distance. + # Interior restoration avoids accumulating positive second-order drift. + slack = torch.where(distance > 0.8 * level, -0.05 * level, 0.8 * (level - distance)) + excess = (a * proposal).sum((-1, -2)) - slack + correction = excess.clamp_min(0) / (a * metric_a).sum((-1, -2)).clamp_min(1e-20) + adjusted = proposal - correction[:, None, None] * metric_a + proposal = torch.where(strict[:, None, None], proposal, adjusted).to(w.dtype) + proposal = torch.where(active[:, None, None], proposal, torch.zeros_like(proposal)) + accepted = torch.zeros_like(active) + chosen = w.detach().clone() + chosen_logits = logits.detach().clone() + picked_scale = torch.zeros(n, device=device) + actual_d = distance.detach().clone() + for backtrack in range(10): + with torch.no_grad(): + candidate = w.detach() + (0.5**backtrack) * proposal + if strict.any(): + exact = w0 + (candidate - w0) @ null + candidate = torch.where(strict[:, None, None], exact, candidate) + candidate_logits = suffix(candidate) + cle, clr, cd = quantities( + candidate_logits, + candidate, + w0, + labels, + ew, + rw, + ref, + cov, + obj, + suffix.repr_factor, + ) + co = cle + clr + level * cd if form == "soft" else cle + clr + tolerance = torch.where(strict, torch.full_like(level, 1e-10), 1e-8 + 1e-5 * level) + feasible = torch.ones_like(active) if form == "soft" else cd <= level + tolerance + descent = co <= objective.detach() + 1e-7 if solver == "gn" else torch.isfinite(co) + if form == "hard" and solver == "gn": + restoration = ( + (distance.detach() > 0.8 * level) + & (cd < distance.detach() - 1e-4 * level) + & (co <= 1.05 * objective.detach() + 1e-6) + & ~strict + ) + descent = descent | restoration + good = feasible & descent & active & ~accepted & torch.isfinite(co) + chosen[good] = candidate[good] + chosen_logits[good] = candidate_logits[good] + actual_d[good] = cd[good] + picked_scale[good] = 0.5**backtrack + accepted |= good + counters["line_search_batches"] += 1 + if torch.all(accepted | ~active): + break + delta = chosen - w.detach() + if pair_gradients is not None: + predicted = (pair_gradients * delta[:, None]).sum((-1, -2)) + updated_margin = torch.stack( + [ + chosen_logits[rows, pair_columns[:, i], 0, answers_a] + - chosen_logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + observed = updated_margin - pair_margin.detach() + flat = pair_gradients.flatten(2) + kernel = flat @ flat.transpose(-1, -2) + for j in range(n): + records[j]["timeline"][-1]["local_step"] = { + "kernel": kernel[j].cpu().tolist(), + "predicted_margin_change": predicted[j].cpu().tolist(), + "observed_margin_change": observed[j].cpu().tolist(), + "actual_delta_norm": float(delta[j].norm()), + } + + with torch.no_grad(): + w.copy_(chosen) + m.copy_(torch.where(accepted[:, None, None], m_new, m)) + v.copy_(torch.where(accepted[:, None, None], v_new, v)) + age += accepted + failed = torch.where(accepted, torch.zeros_like(failed), failed + 1) + active = (age < steps) & (failed < 10) + traces.append( + torch.stack( + ( + le.detach(), + lretain.detach(), + distance.detach(), + actual_d, + delta.flatten(1).norm(dim=1), + picked_scale, + accepted.float(), + age.float(), + ), + -1, + ).cpu() + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start + counters["forward_batches"] = suffix.forward_calls + counters["elapsed_seconds_including_evaluation"] = elapsed + for j, record in enumerate(records): + record.update( + accepted=int(age[j]), + failed=bool(failed[j] >= 10), + elapsed_batch_seconds=elapsed, + representation_rank=int(ranks[j]), + representation_spectrum=spectrum[j].cpu().tolist(), + ) + write_json(directory / "metrics.json", records) + torch.save( + dict( + weights=w.detach().cpu(), + parent=w0.cpu(), + checkpoints=checkpoints, + m=m.cpu(), + v=v.cpu(), + age=age.cpu(), + sketch=None if sketch is None else sketch.cpu(), + generator_state=generator.get_state(), + arm=arm, + configs=configs, + ), + directory / "state.pt", + ) + np.savez_compressed( + directory / "steps.npz", + values=torch.stack(traces).numpy(), + columns=np.array( + [ + "E_CE", + "R_CE", + "distance_before", + "distance_after", + "delta_norm", + "backtrack_scale", + "accepted", + "accepted_count", + ] + ), + ) + write_json(directory / "cost.json", counters) + write_json( + directory / "complete.json", + dict( + files={ + name: digest(directory / name) + for name in ("metrics.json", "state.pt", "steps.npz", "cost.json") + } + ), + ) + return records diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_direction_cross.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_direction_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..27051c00db64d66676d95dc16a1351dff5d797a6 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_direction_cross.py @@ -0,0 +1,149 @@ +"""Target-complete edits on the original two-chain, eight-layer task.""" + +import numpy as np +import torch + +from .bios_cross import edit_pair, make_cross_world +from .bios_cross_train import tensor_queries +from .bios_direction import ROOT, Task, stable_order + +CROSS_ARMS = ("func-soft-adam", "repr-hard-adam", "func-hard-gn", "func-soft-gn") + + +def cross_tasks(world_id, seed, device): + world = make_cross_world(world_id, ROOT / "data/bios-organization-v1") + tasks = [] + for chain in (0, 1): + edits = edit_pair(world, chain) + for group_index, group in enumerate(edits["groups"]): + members = np.flatnonzero(world.memberships[chain] == group) + eligible = [ + int(p) + for p in members + if not world.exceptions[chain, p] + and world.derived_ids[chain, p] in world.heldout_ids[chain] + ] + person = stable_order(eligible, "focal", world_id, chain, int(group))[0] + root, actual = int(world.root_ids[chain, group]), int(world.actual_ids[chain, person]) + c = int(world.answers[root]) + a = int( + world.city_tokens[world.defaults[chain, edits["groups"][(group_index + 1) % 3]]] + ) + b = int( + world.city_tokens[world.defaults[chain, edits["groups"][(group_index + 2) % 3]]] + ) + assert len({a, b, c}) == 3 and int(world.answers[actual]) == c + e = [root, actual] + d = world.derived_ids[chain, members].tolist() + focal = int(world.derived_ids[chain, person]) + assert focal in world.heldout_ids[chain] + membership = int(world.membership_ids[chain, person]) + local = np.flatnonzero( + (world.person == person) & (np.arange(len(world.answers)) < world.n_base) + ).tolist() + local = [i for i in local if i not in e + [membership]] + # Near facts exclude all direct edits and all affected compositions. + near_pool = list( + set( + world.actual_ids[chain, members].tolist() + + world.membership_ids[chain, members].tolist() + ) + - set(e + [membership] + local) + ) + near = stable_order(near_pool, "near", world_id, chain, int(group))[:48] + reserved = set(e + d + local + near + [membership]) + base_pool = stable_order( + [i for i in range(world.n_base) if i not in reserved], + "base", + world_id, + chain, + int(group), + ) + r = [membership] + base_pool[:47] + v = base_pool[47:95] + far_base = base_pool[95:175] + other_d = stable_order( + [int(i) for i in world.heldout_ids.flatten() if i not in reserved], + "far-d", + world_id, + chain, + int(group), + )[:16] + far = far_base + other_d + u = local + near + far + included = e + r + v + u + d + assert len(included) == len(set(included)) + mapping = {old: new for new, old in enumerate(included)} + sets = { + "E": e, + "R": r, + "V": v, + "U": u, + "local": local, + "U_near": near, + "U_far": far, + "D": d, + "D_heldout": [i for i in d if i in world.heldout_ids[chain]], + "D_focal": [focal], + } + for kind in ("coherent", "independent"): + truth = world.answers.copy() + truth[root], truth[actual], truth[d] = a, a if kind == "coherent" else b, a + assert set(np.flatnonzero(truth != world.answers)) == set(e + d) + data = tensor_queries(world, device, truth) + old = torch.stack( + [ + torch.as_tensor(world.answers[included], device=device), + torch.full((len(included),), 3, device=device), + ], + -1, + ) + tasks.append( + Task( + f"world-{world_id}-seed-{seed}-chain-{chain}-group-{int(group)}-{kind}", + data["tokens"][included], + data["positions"][included], + data["labels"][included], + old, + {k: [mapping[i] for i in ids] for k, ids in sets.items()}, + dict( + world=world_id, + seed=seed, + chain=chain, + group=int(group), + group_index=group_index, + person=person, + kind=kind, + a=a, + b=b, + c=c, + pair=[mapping[actual], mapping[root]], + original_ids=included, + ), + ) + ) + return tasks + + +def bounded_representation_geometry(suffix, rmask, w0): + """Same FP64 covariance as the core; avoid a huge four-axis outer product.""" + z = suffix.z + mask = rmask[..., None].expand(-1, -1, z.shape[2]) + valid = ( + torch.arange(z.shape[2], device=z.device)[None, None, :] + <= suffix.positions.max(-1).values[..., None] + ) + mask = mask * valid + flat = z.double().flatten(1, 2) + covariance = flat.transpose(-1, -2) @ (flat * mask.flatten(1)[..., None]) + covariance = covariance / mask.sum((1, 2))[:, None, None] + output = torch.einsum("nqtk,dk->nqtd", z, w0) + suffix.model.blocks[suffix.layer].mlp.down.bias + scale = (output.square().sum(-1) * mask).sum((1, 2)) / mask.sum((1, 2)) + covariance = covariance / scale[:, None, None].clamp_min(1e-12) + suffix.repr_factor = ( + z * (mask / (mask.sum((1, 2)) * scale).clamp_min(1e-12)[:, None, None]).sqrt()[..., None] + ) + vals, vecs = torch.linalg.eigh(covariance) + keep = vals > vals[:, -1:] * 1e-10 + null = (vecs * (~keep)[:, None, :]) @ vecs.transpose(-1, -2) + return covariance.to(w0.dtype), null.to(w0.dtype), keep.sum(-1), vals diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_direction_formation.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_direction_formation.py new file mode 100644 index 0000000000000000000000000000000000000000..96a3aa141c344b0fea47995c861792eb5d95398a --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_direction_formation.py @@ -0,0 +1,241 @@ +"""Prospective learning-rate interventions and factor measurements on new worlds.""" + +import copy +import json +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_direction import ROOT, digest, edit_batch, minimal_task +from .bios_direction_cross import CROSS_ARMS +from .bios_model import CausalLM, ModelConfig + +TRAIN_NODES = (0, 8, 32, 128, 256, 512, 1024) +TRAIN_ARMS = ("baseline", "qk-0.25", "qk-4", "up-0.25", "up-4", "post-0.25", "post-4") + + +def world_labels(world): + rng = np.random.default_rng(np.random.SeedSequence([271523, world])) + r1 = np.r_[ + np.arange(3), rng.permutation(np.r_[np.repeat(0, 10), np.repeat(1, 10), np.repeat(2, 9)]) + ] + exceptions = np.concatenate( + [ + rng.choice(np.flatnonzero((r1 == v) & (np.arange(32) >= 3)), n, replace=False) + for v, n in enumerate((3, 3, 2)) + ] + ) + r2 = r1.copy() + r2[exceptions] = np.roll(r1[exceptions], -3) + r3 = rng.permutation(np.arange(32) % 3) + labels = np.stack((r1, r2, r3), -1) + assert (r1 == r2).sum() == 24 and np.all(r1[:3] == r2[:3]) + for col in labels.T: + assert np.ptp(np.bincount(col, minlength=3)) <= 1 + return torch.tensor(labels.flatten() + 38, dtype=torch.long) + + +def optimizer_views(model): + """Separate Q/K and V learning rates without changing forward computation. + + Optimizer leaf views share parameter storage; their gradients are assigned + from the original model's autograd gradients. A frozen view gets grad=None, + so its optimizer moments and step count genuinely stop. + """ + groups = {k: [] for k in ("qk", "up", "post", "other")} + mapping = [] + for name, p in model.named_parameters(): + if name.startswith("blocks.0.attention.qkv."): + pieces = [("qk", slice(0, 128)), ("other", slice(128, None))] + else: + group = ( + "up" + if name.startswith("blocks.0.mlp.up.") + else ("post" if name.startswith("blocks.1.") else "other") + ) + pieces = [(group, slice(None))] + for group, region in pieces: + view = nn.Parameter(p.detach()[region]) + groups[group].append(view) + mapping.append((group, p, region, view)) + optimizer = torch.optim.AdamW( + [dict(params=params, lr=0.001, name=name) for name, params in groups.items()], + weight_decay=0.1, + foreach=True, + ) + return optimizer, mapping + + +def multiplier(arm, step): + if arm == "baseline": + return None, 1.0 + group, mode = arm.split("-") + if mode == "freezeearly": + return group, 0.0 if step < 256 else 1.0 + if mode == "freezelate": + return group, 0.0 if step >= 768 else 1.0 + if mode == "freezeall": + return group, 0.0 + return group, float(mode) if step < 256 else 1.0 + + +def factor_measure(model, seed, labels, device): + records = [] + for person in (0, 1, 2): + task = minimal_task(seed, person, "independent", device, labels) + ids = task.metadata["pair"] + captured = {} + + def capture(module, inputs, output, captured=captured): + captured.update(z=inputs[0], h=output) + + handle = model.blocks[0].mlp.down.register_forward_hook(capture) + tokens = task.tokens[ids] + logits = model(tokens)[:, -1] + handle.remove() + a, b, c = (task.metadata[x] for x in ("a", "b", "c")) + margin = logits[:, a] - logits[:, b] + gradients = [] + deltas = [] + for i in range(2): + g, d = torch.autograd.grad( + margin[i], (model.blocks[0].mlp.down.weight, captured["h"]), retain_graph=True + ) + gradients.append(g.detach()) + deltas.append(d[i].detach()) + g = torch.stack(gradients).flatten(1) + kernel = g @ g.T + z = captured["z"].detach() + d = torch.stack(deltas) + rebuilt = torch.einsum("itd,itk->idk", d, z).flatten(1) + error = (rebuilt - g).norm() / g.norm().clamp_min(1e-20) + common = float((kernel[0, 0] + kernel[1, 1] + 2 * kernel[0, 1]) / 2) + difference = float((kernel[0, 0] + kernel[1, 1] - 2 * kernel[0, 1]) / 2) + # Actual GELU slope at the preactivation, not a binary activation mask. + pre = model.blocks[0].mlp.up + activations = {} + + def pre_hook(module, inputs, output, activations=activations): + activations.update(input=inputs[0], pre=output) + + handle = pre.register_forward_hook(pre_hook) + model(tokens) + handle.remove() + y = activations["pre"] + gate = torch.autograd.grad(model.blocks[0].mlp.activation(y).sum(), y)[0].detach() + + def cosine(x): + return float(F.cosine_similarity(x[0].flatten(), x[1].flatten(), dim=0)) + + records.append( + dict( + person=person, + common=common, + difference=difference, + ratio=difference / max(common, 1e-20), + mixing=float((kernel[0, 0] - kernel[1, 1]) / 2), + eigenvalues=torch.linalg.eigvalsh(kernel.double()).tolist(), + feature_cos=cosine(z), + downstream_cos=cosine(d), + gate_cos=cosine(gate), + relation_input_difference=float( + (activations["input"][0] - activations["input"][1]).detach().norm() + ), + feature_difference=float((z[0] - z[1]).norm()), + gate_difference=float((gate[0] - gate[1]).norm()), + reconstruction_error=float(error), + new_target_nll=float(F.cross_entropy(logits, task.labels[ids, 0]).detach()), + margin_ab=margin.detach().tolist(), + kernel=kernel.detach().cpu().tolist(), + ) + ) + return records + + +def train(world, seed, arm, device, out): + out = Path(out) + if (out / "complete.json").exists(): + return + out.mkdir(parents=True, exist_ok=True) + labels = world_labels(world).to(device) + torch.manual_seed(seed) + model = CausalLM(ModelConfig(41, width=64, layers=2, heads=2, context=8)).to(device) + tokens = minimal_task(seed, 0, "independent", device, labels).tokens + opt, mapping = optimizer_views(model) + timeline = [] + for step in range(1025): + if step in TRAIN_NODES: + with torch.no_grad(): + logits = model(tokens)[:, -1] + acc = float(logits.argmax(-1).eq(labels).float().mean()) + loss = float(F.cross_entropy(logits, labels)) + factors = factor_measure(model, seed, labels, device) + timeline.append(dict(step=step, accuracy=acc, loss=loss, factors=factors)) + torch.save( + dict( + model={k: v.detach().cpu() for k, v in model.state_dict().items()}, + config=model.config_dict(), + optimizer=opt.state_dict(), + step=step, + world=world, + seed=seed, + arm=arm, + labels=labels.cpu(), + ), + out / f"model-{step}.pt", + ) + if step == 1024: + break + model.zero_grad(set_to_none=True) + opt.zero_grad(set_to_none=True) + loss = F.cross_entropy(model(tokens)[:, -1], labels) + loss.backward() + selected, factor = multiplier(arm, step) + for group in opt.param_groups: + group["lr"] = 0.001 * (factor if group["name"] == selected else 1.0) + for group, p, region, view in mapping: + view.grad = None if group == selected and factor == 0 else p.grad[region] + opt.step() + write_json(out / "learning.json", timeline) + write_json( + out / "complete.json", + dict( + world=world, + seed=seed, + arm=arm, + files={p.name: digest(p) for p in out.iterdir() if p.suffix in (".json", ".pt")}, + ), + ) + + +def edit_parent(world, seed, train_arm, device, out, edit_arms=CROSS_ARMS, steps=1024): + from .bios_direction import load_parent + + out = Path(out) + saved = torch.load(out / "model-1024.pt", map_location="cpu", weights_only=False) + labels = saved["labels"].to(device) + model = load_parent(out / "model-1024.pt", device) + selected = json.loads( + (ROOT / "docs/development-artifacts/direction-v1/selected.json").read_text() + )["choices"] + tasks = [ + minimal_task(seed, p, k, device, labels) + for p in (0, 1, 2) + for k in ("coherent", "independent") + ] + for task in tasks: + task.metadata.update(world=world, train_arm=train_arm) + for arm in edit_arms: + edit_batch( + model, + 0, + tasks, + arm, + [copy.deepcopy(selected[arm]) for _ in tasks], + steps, + out / "edits" / arm, + ) diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_direction_refresh.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_direction_refresh.py new file mode 100644 index 0000000000000000000000000000000000000000..5f48462e2c66886ef8e483fa7e48986d075ad3fb --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_direction_refresh.py @@ -0,0 +1,355 @@ +"""V1 numerical audit: refresh curvature per trajectory and freeze idle counters. + +This keeps the original randomized batched probe stream, finite objectives, +constraints and solver settings. Unused fresh probe rows are discarded rather +than changing another trajectory's sketch. Frozen v1 artifacts are untouched. +""" + +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_data import write_json +from .bios_direction import ( + NODES, + batch_setup, + digest, + evaluate_weights, + gaussian_newton_sketch, + inverse_sketch, + quantities, +) + + +def refresh_mask(active, failed, attempt, refresh, missing): + due = missing or attempt % refresh == 0 + return active & (torch.full_like(active, due) | (failed > 0)) + + +def update_failure_counts(active, accepted, failed): + return torch.where(active, torch.where(accepted, torch.zeros_like(failed), failed + 1), failed) + + +def edit_batch(model, layer, tasks, arm, configs, steps, directory, evaluate=True): + """Each batch member is an independent run; no cross-run loss/normalization.""" + directory = Path(directory) + if (directory / "complete.json").exists(): + return json.loads((directory / "metrics.json").read_text()) + directory.mkdir(parents=True, exist_ok=True) + obj, form, solver = arm.split("-") + setup = batch_setup(model, layer, tasks, configs) + suffix, labels, ew, rw, ref, cov, null, ranks, spectrum, w0 = setup + device = w0.device + n = len(tasks) + w = w0[None].expand(n, -1, -1).clone().requires_grad_() + m, v = torch.zeros_like(w), torch.zeros_like(w) + lr = torch.tensor([c["lr"] for c in configs], device=device) + level = torch.tensor([c["level"] for c in configs], device=device) + damping = configs[0]["damping"] + rank, refresh = configs[0]["rank"], configs[0]["refresh"] + strict = (level == 0) & (form == "hard") & (obj == "repr") + age = torch.zeros(n, device=device, dtype=torch.long) + failed = torch.zeros_like(age) + active = torch.ones(n, device=device, dtype=torch.bool) + sketch = None + generator = torch.Generator(device=device).manual_seed(271521) + records = [ + dict(task=t.manifest(), config=c, arm=arm, timeline=[]) + for t, c in zip(tasks, configs, strict=True) + ] + traces, checkpoints = [], {} + pair_columns = torch.tensor( + [[(t.sets["E"] + t.sets["R"]).index(i) for i in t.metadata["pair"]] for t in tasks], + device=device, + ) + answers_a = torch.tensor([t.metadata["a"] for t in tasks], device=device) + answers_b = torch.tensor([t.metadata["b"] for t in tasks], device=device) + rows = torch.arange(n, device=device) + counters = dict( + forward_batches=0, + backward_batches=0, + ggn_vjps=0, + line_search_batches=0, + covariance_eigh=1, + train_examples_per_batch=labels.shape[1], + batch_runs=n, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.monotonic() + limit = 11 * steps + 10 + for attempt in range(limit + 1): + if ( + attempt == 0 + or (attempt in NODES and attempt <= steps) + or not active.any() + or attempt == limit + ): + if device.type == "cuda": + torch.cuda.synchronize(device) + metrics = ( + evaluate_weights(model, layer, tasks, w.detach()) + if evaluate + else [dict() for _ in tasks] + ) + for j, metric in enumerate(metrics): + records[j]["timeline"].append( + dict( + attempt=attempt, + accepted=int(age[j]), + seconds=time.monotonic() - start, + **metric, + ) + ) + checkpoints[str(attempt)] = w.detach().cpu().clone() + if attempt and (not active.any() or attempt == limit): + break + if attempt >= steps and torch.all((age >= steps) | ~active): + break + logits = suffix(w) + le, lretain, distance = quantities( + logits, w, w0, labels, ew, rw, ref, cov, obj, suffix.repr_factor + ) + pair_gradients = None + if attempt in NODES: + pair_margin = torch.stack( + [ + logits[rows, pair_columns[:, i], 0, answers_a] + - logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + pair_gradients = torch.stack( + [ + torch.autograd.grad(pair_margin[:, i].sum(), w, retain_graph=True)[0].detach() + for i in range(2) + ], + 1, + ) + counters["backward_batches"] += 2 + data_loss = le + lretain + objective = data_loss + level * distance if form == "soft" else data_loss + refresh_rows = refresh_mask(active, failed, attempt, refresh, sketch is None) + if solver == "gn" and refresh_rows.any(): + weights = ((ew + rw) / labels.shape[2])[..., None].expand_as(labels) + if form == "soft" and obj == "func": + weights = ((ew + (1 + level[:, None]) * rw) / labels.shape[2])[..., None].expand_as( + labels + ) + fresh = gaussian_newton_sketch(logits, w, weights, rank, generator) + if strict.any(): + projected = (fresh.reshape(n, rank, *w0.shape) @ null[:, None]).flatten(2) + fresh = torch.where(strict[:, None, None], projected, fresh) + sketch = ( + fresh if sketch is None else torch.where(refresh_rows[:, None, None], fresh, sketch) + ) + counters["ggn_vjps"] += rank + g = torch.autograd.grad(objective.sum(), w, retain_graph=form == "hard")[0] + counters["backward_batches"] += 1 + if form == "hard": + a = torch.autograd.grad(distance.sum(), w)[0] + counters["backward_batches"] += 1 + else: + a = None + if solver == "adam": + m_new = 0.9 * m + 0.1 * g + v_new = 0.999 * v + 0.001 * g.square() + t = (age + 1).float()[:, None, None] + raw = -(m_new / (1 - 0.9**t)) / ((v_new / (1 - 0.999**t)).sqrt() + 1e-8) + proposal = lr[:, None, None] * raw + else: + if strict.any(): + g = torch.where(strict[:, None, None], g @ null, g) + if obj == "repr" and form == "soft": + # Exact representation Hessian plus damped sketched data GGN, CG. + def hv(x, sketch=sketch): + flat = x.flatten(1) + return ( + damping * x + + (sketch.transpose(-1, -2) @ (sketch @ flat[..., None]))[ + ..., 0 + ].reshape_as(x) + + 2 * level[:, None, None] * (x @ cov) + ) + + direction = torch.zeros_like(g) + residual, search = -g.clone(), -g.clone() + rr = residual.square().sum((-1, -2)) + for _ in range(16): + hp = hv(search) + alpha = rr / (search * hp).sum((-1, -2)).clamp_min(1e-30) + direction += alpha[:, None, None] * search + residual -= alpha[:, None, None] * hp + new_rr = residual.square().sum((-1, -2)) + search = residual + (new_rr / rr.clamp_min(1e-30))[:, None, None] * search + rr = new_rr + proposal = lr[:, None, None] * direction + else: + proposal = -lr[:, None, None] * inverse_sketch(g, sketch, damping) + # Fixed Euclidean trust radius, no hidden per-run gradient scaling. + radius = configs[0]["trust_fraction"] * w0.norm() + proposal *= (radius / proposal.flatten(1).norm(dim=1).clamp_min(1e-12)).clamp(max=1)[ + :, None, None + ] + m_new, v_new = m, v + if form == "hard": + if strict.any(): + proposal = torch.where(strict[:, None, None], proposal @ null, proposal) + metric_a = a if solver == "adam" else inverse_sketch(a, sketch, damping) + # Sequential quadratic subproblem with a linearized ORIGINAL distance. + # Interior restoration avoids accumulating positive second-order drift. + slack = torch.where(distance > 0.8 * level, -0.05 * level, 0.8 * (level - distance)) + excess = (a * proposal).sum((-1, -2)) - slack + correction = excess.clamp_min(0) / (a * metric_a).sum((-1, -2)).clamp_min(1e-20) + adjusted = proposal - correction[:, None, None] * metric_a + proposal = torch.where(strict[:, None, None], proposal, adjusted).to(w.dtype) + proposal = torch.where(active[:, None, None], proposal, torch.zeros_like(proposal)) + accepted = torch.zeros_like(active) + chosen = w.detach().clone() + chosen_logits = logits.detach().clone() + picked_scale = torch.zeros(n, device=device) + actual_d = distance.detach().clone() + for backtrack in range(10): + with torch.no_grad(): + candidate = w.detach() + (0.5**backtrack) * proposal + if strict.any(): + exact = w0 + (candidate - w0) @ null + candidate = torch.where(strict[:, None, None], exact, candidate) + candidate_logits = suffix(candidate) + cle, clr, cd = quantities( + candidate_logits, + candidate, + w0, + labels, + ew, + rw, + ref, + cov, + obj, + suffix.repr_factor, + ) + co = cle + clr + level * cd if form == "soft" else cle + clr + tolerance = torch.where(strict, torch.full_like(level, 1e-10), 1e-8 + 1e-5 * level) + feasible = torch.ones_like(active) if form == "soft" else cd <= level + tolerance + descent = co <= objective.detach() + 1e-7 if solver == "gn" else torch.isfinite(co) + if form == "hard" and solver == "gn": + restoration = ( + (distance.detach() > 0.8 * level) + & (cd < distance.detach() - 1e-4 * level) + & (co <= 1.05 * objective.detach() + 1e-6) + & ~strict + ) + descent = descent | restoration + good = feasible & descent & active & ~accepted & torch.isfinite(co) + chosen[good] = candidate[good] + chosen_logits[good] = candidate_logits[good] + actual_d[good] = cd[good] + picked_scale[good] = 0.5**backtrack + accepted |= good + counters["line_search_batches"] += 1 + if torch.all(accepted | ~active): + break + delta = chosen - w.detach() + if pair_gradients is not None: + predicted = (pair_gradients * delta[:, None]).sum((-1, -2)) + updated_margin = torch.stack( + [ + chosen_logits[rows, pair_columns[:, i], 0, answers_a] + - chosen_logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + observed = updated_margin - pair_margin.detach() + flat = pair_gradients.flatten(2) + kernel = flat @ flat.transpose(-1, -2) + for j in range(n): + records[j]["timeline"][-1]["local_step"] = { + "kernel": kernel[j].cpu().tolist(), + "predicted_margin_change": predicted[j].cpu().tolist(), + "observed_margin_change": observed[j].cpu().tolist(), + "actual_delta_norm": float(delta[j].norm()), + } + + with torch.no_grad(): + w.copy_(chosen) + m.copy_(torch.where(accepted[:, None, None], m_new, m)) + v.copy_(torch.where(accepted[:, None, None], v_new, v)) + age += accepted + failed = update_failure_counts(active, accepted, failed) + active = (age < steps) & (failed < 10) + traces.append( + torch.stack( + ( + le.detach(), + lretain.detach(), + distance.detach(), + actual_d, + delta.flatten(1).norm(dim=1), + picked_scale, + accepted.float(), + age.float(), + ), + -1, + ).cpu() + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start + counters["forward_batches"] = suffix.forward_calls + counters["elapsed_seconds_including_evaluation"] = elapsed + for j, record in enumerate(records): + record.update( + accepted=int(age[j]), + failed=bool(failed[j] >= 10 and age[j] < steps), + elapsed_batch_seconds=elapsed, + representation_rank=int(ranks[j]), + representation_spectrum=spectrum[j].cpu().tolist(), + ) + write_json(directory / "metrics.json", records) + torch.save( + dict( + weights=w.detach().cpu(), + parent=w0.cpu(), + checkpoints=checkpoints, + m=m.cpu(), + v=v.cpu(), + age=age.cpu(), + sketch=None if sketch is None else sketch.cpu(), + generator_state=generator.get_state(), + arm=arm, + configs=configs, + ), + directory / "state.pt", + ) + np.savez_compressed( + directory / "steps.npz", + values=torch.stack(traces).numpy(), + columns=np.array( + [ + "E_CE", + "R_CE", + "distance_before", + "distance_after", + "delta_norm", + "backtrack_scale", + "accepted", + "accepted_count", + ] + ), + ) + write_json(directory / "cost.json", counters) + write_json( + directory / "complete.json", + dict( + files={ + name: digest(directory / name) + for name in ("metrics.json", "state.pt", "steps.npz", "cost.json") + } + ), + ) + return records diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_edit.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..685a33d6157d090f0afdfaa38b5c2d731eda4d0e --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_edit.py @@ -0,0 +1,381 @@ +"""Fixed-budget development edits with held-out retention and full-answer scoring.""" + +import argparse +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_branch import attach_branch, build_bases, remove_branch +from .bios_data import N_BASE, N_QUERIES, load_world, paired_edit, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_train import code_fingerprint, evaluate, precision, tensor_data + +EDIT_CHECKPOINTS = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512) + + +def score_edit(world, pair, target, arrays, old_correct): + correct = arrays["correct"] + e, d = pair["E"], pair["D"] + root = e[world.relation[e] == 1] + members = e[world.relation[e] == 2] + unseen = np.zeros(N_QUERIES, dtype=bool) + unseen[pair["heldout"]] = True + retention, full_retention = {}, {} + for g in range(4): + ids = (pair["strata"] == g) & old_correct + full_retention[str(g)] = { + "known": int(ids.sum()), + "broken": int((ids & ~correct).sum()), + "rate": float((~correct[ids]).mean()) if ids.any() else None, + } + held = ids & unseen + retention[str(g)] = { + "known": int(held.sum()), + "broken": int((held & ~correct).sum()), + "rate": float((~correct[held]).mean()) if held.any() else None, + } + for name, base in (("2_base", True), ("2_derived", False)): + ids = ( + (pair["strata"] == 2) & old_correct & unseen & ((np.arange(N_QUERIES) < N_BASE) == base) + ) + retention[name] = { + "known": int(ids.sum()), + "broken": int((ids & ~correct).sum()), + "rate": float((~correct[ids]).mean()) if ids.any() else None, + } + rates = [v["rate"] for v in retention.values()] + root_acc, member_acc, d_acc = (float(correct[ids].mean()) for ids in (root, members, d)) + joint = ( + None + if any(rate is None for rate in rates) + else bool( + root_acc == 1 + and member_acc >= 0.95 + and d_acc >= 0.95 + and all(rate <= 0.01 for rate in rates) + ) + ) + return { + "E": float(correct[e].mean()), + "E_root": root_acc, + "E_member": member_acc, + "D": d_acc, + "U_accuracy": float(correct[pair["strata"] >= 0].mean()), + "U_heldout_destruction": retention, + "U_full_destruction": full_retention, + "joint_pass": joint, + "E_target_value_nll": float(arrays["value_nll"][e].mean()), + } + + +def reference_logits(model, data, ids, device): + result = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(ids), 256): + subset = torch.as_tensor(ids[begin : begin + 256], device=device) + result.append(model(data["tokens"][subset], data["positions"][subset]).detach()) + return torch.cat(result) + + +@torch.no_grad() +def capture_down(model, tokens, positions, layer): + captured = {} + + def capture(module, inputs, output): + captured.update( + z=inputs[0].float().clone(), + h=output.float().clone(), + weight=module.weight.detach().float().clone(), + ) + + handle = model.blocks[layer].mlp.down.register_forward_hook(capture) + try: + model(tokens, positions) + finally: + handle.remove() + return captured + + +def edit_case( + model, + baseline, + world, + data_old, + pair, + kind, + scope, + args, + old_correct, + branch_kind=None, + basis=None, +): + suffix = "" if branch_kind is None else f"-{branch_kind}-branch" + out = Path(args.output) / f"support-{pair['support']}-{kind}-{scope}{suffix}" + if (out / "complete.json").exists(): + return json.loads((out / "complete.json").read_text()) + out.mkdir(parents=True, exist_ok=True) + device = data_old["tokens"].device + model.load_state_dict(baseline) + selected = select_parameters(model, scope, args.window) + branch, handles, zero_error = None, [], None + if basis is not None: + probe = torch.as_tensor(pair["E"][:32], device=device) + with torch.no_grad(), precision(device): + before = model(data_old["tokens"][probe], data_old["positions"][probe]) + branch, handles = attach_branch(model, basis, layer=args.window + 1) + selected.extend(branch.parameters()) + with torch.no_grad(), precision(device): + after = model(data_old["tokens"][probe], data_old["positions"][probe]) + zero_error = (before - after).abs().max().item() + if zero_error != 0: + raise ValueError("Branch was not function-preserving at initialization") + target = pair[kind] + data_new = tensor_data(world, device, target) + if device.type == "cuda": + torch.cuda.synchronize(device) + setup_start = time.perf_counter() + calibration = None + if scope == "down": + calibration_ids = torch.as_tensor( + np.concatenate([pair["E"][:32], pair["replay"][:32]]), device=device + ) + calibration = capture_down( + model, + data_old["tokens"][calibration_ids], + data_old["positions"][calibration_ids], + args.window + 1, + ) + old_logits = reference_logits(model, data_old, pair["replay"], device) + if device.type == "cuda": + torch.cuda.synchronize(device) + setup_seconds = time.perf_counter() - setup_start + basis_seconds = getattr(args, "branch_preparation_seconds", 0.0) if basis else 0.0 + setup_flops = matmul_flops(model.config, len(pair["replay"]), backward=False) + optimizer = torch.optim.AdamW( + selected, lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + sample_rng = rng_for(world.seed, 41, pair["support"]) + e_choices = sample_rng.integers(0, len(pair["E"]), size=(args.steps, 128)) + r_choices = sample_rng.integers(0, len(pair["replay"]), size=(args.steps, 128)) + timeline, train_seconds = [], 0.0 + case_config = { + "scope": scope, + "branch": branch_kind, + "branch_parameters": sum(p.numel() for p in branch.parameters()) if branch else 0, + "branch_zero_initialization_max_logit_difference": zero_error, + "kind": kind, + "support": pair["support"], + "selection": pair["selection"], + "steps": args.steps, + "lr": args.lr, + "retention_kl_weight": args.retention, + "window_zero_based": list(range(args.window, args.window + 3)), + "trainable_parameters": sum(p.numel() for p in selected), + "setup_seconds": setup_seconds, + "shared_basis_preparation_seconds": basis_seconds, + "preparation_accounting": ( + "Basis construction is executed once per old checkpoint. Standalone cold-start time " + "below charges that entire common construction; do not sum it across reused branches." + ), + "setup_matmul_flops_estimate": setup_flops, + "flops_limitation": ( + "backward dense matmul upper approximation; not exact frozen-scope operation count" + ), + } + write_json(out / "config.json", case_config) + np.savez_compressed( + out / "sets.npz", + E=pair["E"], + D=pair["D"], + strata=pair["strata"], + replay=pair["replay"], + heldout=pair["heldout"], + target=target, + old_correct=old_correct, + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + checkpoints = sorted({s for s in EDIT_CHECKPOINTS if s <= args.steps} | {args.steps}) + for step in range(args.steps + 1): + if step in checkpoints: + eval_start = time.perf_counter() + _, arrays = evaluate(model, data_old, world, answers=target) + metrics = score_edit(world, pair, target, arrays, old_correct) + np.savez_compressed(out / f"predictions-{step}.npz", **arrays) + point = { + "step": step, + **metrics, + "edit_seconds": train_seconds, + "setup_plus_edit_seconds": setup_seconds + train_seconds, + "cold_start_including_basis_seconds": basis_seconds + setup_seconds + train_seconds, + "setup_plus_edit_matmul_flops_estimate": setup_flops + + step * matmul_flops(model.config, 256), + "target_supervised_tokens": step * 256, + "replay_supervised_tokens": step * 256, + "eval_seconds": time.perf_counter() - eval_start, + } + if calibration is not None: + current = capture_down( + model, + data_old["tokens"][calibration_ids], + data_old["positions"][calibration_ids], + args.window + 1, + ) + observed = current["h"] - calibration["h"] + predicted = F.linear(calibration["z"], current["weight"] - calibration["weight"]) + point["down_calibration"] = { + "feature_max_change": (current["z"] - calibration["z"]).abs().max().item(), + "delta_h_max_error": (observed - predicted).abs().max().item(), + "delta_h_rms_error": (observed - predicted).square().mean().sqrt().item(), + "fixed_prefix_tokens": int( + calibration["z"].shape[0] * calibration["z"].shape[1] + ), + } + timeline.append(point) + write_json(out / "trajectory.json", timeline) + print( + json.dumps( + { + "event": "edit", + "case": out.name, + "step": step, + "E": metrics["E"], + "D": metrics["D"], + "joint": metrics["joint_pass"], + } + ), + flush=True, + ) + if step == args.steps: + break + model.train() + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + reference = old_logits[torch.as_tensor(r_choices[step], device=device)].float() + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits_e = model(data_new["tokens"][ei], data_new["positions"][ei]).float() + logits_r = model(data_old["tokens"][ri], data_old["positions"][ri]).float() + ce = F.cross_entropy( + logits_e.reshape(-1, world.vocab_size), data_new["labels"][ei].reshape(-1) + ) + kl = ( + F.kl_div( + F.log_softmax(logits_r, dim=-1), F.softmax(reference, dim=-1), reduction="none" + ) + .sum(-1) + .mean() + ) + loss = ce + args.retention * kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1.0) + if not torch.isfinite(loss) or not torch.isfinite(norm): + write_json(out / "failure.json", {"step": step, "reason": "nonfinite loss or gradient"}) + raise FloatingPointError("Nonfinite edit") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - start + passed = [p for p in timeline if p["joint_pass"] is True] + result = { + **case_config, + "status": "complete", + "final": timeline[-1], + "first_observed_joint_step": passed[0]["step"] if passed else None, + "budget_censored": (not bool(passed) if timeline[-1]["joint_pass"] is not None else None), + "joint_evaluable": timeline[-1]["joint_pass"] is not None, + } + write_json(out / "complete.json", result) + if handles: + remove_branch(model, handles) + return result + + +def run(args): + torch.set_num_threads(args.threads) + torch.manual_seed(0) + device = torch.device(args.device) + world = load_world(args.world) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_data(world, device) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + write_json( + out / "run.json", {**vars(args), "world_step": checkpoint["step"], **code_fingerprint()} + ) + _, old_arrays = evaluate(model, data, world) + bases = None + if args.branches: + bases, operation_checks = build_bases(model, world, data, layer=args.window + 1) + write_json(out / "branch-operation-checks.json", operation_checks) + args.branch_preparation_seconds = operation_checks.get("construction_seconds", 0.0) + results = [] + for support in args.supports: + pair = paired_edit(world, support=support, k=1) + scopes = getattr(args, "scopes", None) + if scopes is None: + scopes = ["mlp", "all"] + (["down"] if support == 0 else []) + for scope in scopes: + for kind in ("coherent", "exception"): + results.append( + edit_case( + model, + checkpoint["model"], + world, + data, + pair, + kind, + scope, + args, + old_arrays["correct"], + ) + ) + if support == 0 and bases is not None: + for branch_kind, basis in bases.items(): + for kind in ("coherent", "exception"): + results.append( + edit_case( + model, + checkpoint["model"], + world, + data, + pair, + kind, + "mlp", + args, + old_arrays["correct"], + branch_kind, + basis, + ) + ) + write_json(out / "complete.json", {"status": "complete", "cases": results}) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--supports", type=int, nargs="+", default=[0, 1]) + parser.add_argument("--scopes", choices=["mlp", "all", "down"], nargs="+") + parser.add_argument("--steps", type=int, default=512) + parser.add_argument("--window", type=int, default=3) + parser.add_argument("--lr", type=float, default=3e-5) + parser.add_argument("--retention", type=float, default=1.0) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--branches", action="store_true") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_followup.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..c90b76331ad0bbd37276b4a9fe14b865360e7a60 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_followup.py @@ -0,0 +1,381 @@ +"""Small, paired follow-ups using frozen editing and gradient implementations. + +Historical source files are left intact. A process-local, scoped adapter supplies +only a new supervised weight vector to the established P1 training loop. +""" + +import argparse +import fcntl +import itertools +import json +import os +import subprocess +import sys +import time +from contextlib import contextmanager +from pathlib import Path +from types import MethodType + +import numpy as np +import torch + +from . import bios_context_gradient as gradient +from . import bios_mechanism_edit as editing +from .bios_cross import make_cross_world +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = "configs/bios-followup-v1.json" +ROOT_MASSES = {"root125": 0.125, "root250": 0.25, "root500": 0.5} +ORIGINAL_MAKE_ARM = editing.make_arm +ORIGINAL_SOURCE_HASHES = editing.source_hashes + + +def mixture_spec(world, chain, arm, pair=None): + if "-root" not in arm: + return ORIGINAL_MAKE_ARM(world, chain, arm, pair) + kind, tag = arm.split("-", 1) + if kind not in ("coherent", "exception") or tag not in ROOT_MASSES: + raise ValueError("Unknown mixture arm") + spec = ORIGINAL_MAKE_ARM(world, chain, kind, pair) + mass = ROOT_MASSES[tag] + mask = spec["S_root_mask"] + spec["S_weights"] = np.where( + mask, mass * len(mask) / mask.sum(), (1 - mass) * len(mask) / (~mask).sum() + ) + return spec + + +def production_hashes(): + return {**ORIGINAL_SOURCE_HASHES(), Path(__file__).name: editing.file_hash(__file__)} + + +@contextmanager +def mixture_adapter(): + old_make, old_hash = editing.make_arm, editing.source_hashes + editing.make_arm, editing.source_hashes = mixture_spec, production_hashes + try: + yield + finally: + editing.make_arm, editing.source_hashes = old_make, old_hash + + +def uniform_forward(self, x): + """First-layer uniform causal attention, with the full value/projection path.""" + width = x.shape[-1] + value = self.qkv(x)[..., 2 * width :] + mask = gradient.allowed_mask(x.shape[1], False, x.device).to(x.dtype) + mask = mask / mask.sum(-1, keepdim=True) + return self.proj(mask @ value) + + +@contextmanager +def uniform_first_layer(model): + attention = model.blocks[0].attention + original = attention.forward + attention.forward = MethodType(uniform_forward, attention) + try: + yield + finally: + attention.forward = original + + +def load_config(): + config = json.loads((ROOT / CONFIG).read_text()) + if config["root_mass"] != {"uniform": 1 / 31, **ROOT_MASSES}: + raise ValueError("The declared mixture weights differ from the implementation") + return config + + +def frozen_paths(config): + paths = [ + ROOT / CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_followup.py", + ROOT / "tests/test_bios_followup.py", + ROOT / "src/llm_memory_editability/bios_context_gradient.py", + ROOT / "src/llm_memory_editability/bios_mechanism_edit.py", + ROOT / "scripts/run_bios_mechanism_edit.py", + ROOT / config["gradient_config"], + ROOT / "docs/development-artifacts/context-gradient-v1/preregistration-lock.json", + ] + paths += [ROOT / "src/llm_memory_editability" / name for name in editing.parent_source_hashes()] + for world, seed, condition in itertools.product( + config["worlds"], config["seeds"], config["conditions"] + ): + name = f"world-{world}-seed-{seed}-{condition}" + paths += [ROOT / config["parent_root"] / name / "config.json"] + paths += [ROOT / config["balanced_root"] / name / "contract.json"] + return sorted(set(paths)) + + +def freeze(config): + artifacts = ROOT / config["artifacts"] + artifacts.mkdir(parents=True, exist_ok=True) + lock = artifacts / "preregistration-lock.json" + if lock.exists(): + raise FileExistsError("Existing prospective lock cannot be replaced") + protocol = (ROOT / "docs/experimental-protocol.md").read_text().split("## 17. ", 1)[1] + (artifacts / "preregistration.md").write_text("## 17. " + protocol) + sources = {} + for path in frozen_paths(config): + relative = path.relative_to(ROOT) + sources[str(relative)] = editing.file_hash(path) + if relative.parts[0] not in ("results", "data"): + destination = artifacts / "frozen-files" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(path.read_bytes()) + write_json( + lock, + { + "created_at": gradient.stamp(), + "config": config, + "sources": sources, + "protocol_sha256": editing.file_hash(artifacts / "preregistration.md"), + "torch": torch.__version__, + "numpy": np.__version__, + }, + ) + return {"lock": str(lock), "sha256": editing.file_hash(lock)} + + +def verify_lock(config): + artifacts = ROOT / config["artifacts"] + path = artifacts / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Frozen configuration/runtime mismatch") + for source, digest in lock["sources"].items(): + if editing.file_hash(ROOT / source) != digest: + raise ValueError("Frozen source mismatch: " + source) + if editing.file_hash(artifacts / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Frozen protocol mismatch") + return editing.file_hash(path) + + +def run_edit(config, world, seed, condition, device): + verify_lock(config) + if (world, seed, condition) not in itertools.product( + config["worlds"], config["seeds"], config["conditions"] + ): + raise ValueError("Edit worker is outside the frozen matrix") + name = f"world-{world}-seed-{seed}-{condition}" + destination = ROOT / config["output"] / "editing" / name + destination.mkdir(parents=True, exist_ok=True) + with (destination / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + with mixture_adapter(): + editing.run_model( + ROOT / config["parent_root"] / name, destination, config["edit"], device + ) + + +def verify_receipt(path): + receipt = json.loads((path / "receipt.json").read_text()) + for name, digest in receipt["files"].items(): + if editing.file_hash(path / name) != digest: + raise ValueError("Gradient receipt mismatch: " + str(path / name)) + + +def run_gradient(config, world_seed, seed, device): + lock_hash = verify_lock(config) + if world_seed not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("Gradient worker is outside the frozen matrix") + original = json.loads((ROOT / config["gradient_config"]).read_text()) + gradient.verify_lock(ROOT, original) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + world = make_cross_world(world_seed, ROOT / original["source_world_root"]) + name = f"world-{world_seed}-seed-{seed}" + source = ROOT / config["gradient_parent"] / name + destination = ROOT / config["output"] / "gradient" / name + destination.mkdir(parents=True, exist_ok=True) + seal = json.loads((source / "complete.json").read_text()) + consumed = {"complete.json": editing.file_hash(source / "complete.json")} + with (destination / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if (destination / "complete.json").exists(): + raise FileExistsError("Completed gradient worker cannot be overwritten") + for step in config["gradient"]["states"]: + checkpoint = source / f"state-{step}.pt" + digest = editing.file_hash(checkpoint) + if digest != seal["files"][checkpoint.name]: + raise ValueError("Archived common state hash mismatch") + consumed[checkpoint.name] = digest + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + if saved["step"] != step: + raise ValueError("Common state step mismatch") + model = CausalLM(ModelConfig(**saved["config"])).to(device) + model.load_state_dict(saved["model"]) + sham = config["gradient"]["sham"] + if (world_seed, seed, step) == (sham["world"], sham["seed"], sham["step"]): + path = destination / "sham" + if not (path / "receipt.json").exists(): + gradient.measure_arm( + model, world, sham["condition"], False, original, device, path + ) + verify_receipt(path) + before = source / f"step-{step}-open-{sham['condition']}" + verify_receipt(before) + errors = {} + for kind in ("answer", "eos"): + with np.load(before / f"{kind}.npz") as a, np.load(path / f"{kind}.npz") as b: + for parameter in a.files: + reference = np.linalg.norm(a[parameter].astype(np.float64)) + difference = np.linalg.norm( + b[parameter].astype(np.float64) - a[parameter] + ) + error = ( + float(difference / reference) if reference else float(difference) + ) + errors[f"{kind}/{parameter}"] = error + if max(errors.values()) > config["gradient"]["sham_relative_tolerance"]: + raise ValueError("Historical-gradient sham failed") + write_json(destination / "sham-check.json", errors) + for condition in config["conditions"]: + path = destination / f"step-{step}-uniform-{condition}" + if not (path / "receipt.json").exists(): + with uniform_first_layer(model): + gradient.measure_arm(model, world, condition, False, original, device, path) + verify_receipt(path) + print(json.dumps({"event": "gradient_arm_complete", "path": str(path)}), flush=True) + del model, saved + verify_lock(config) + write_json( + destination / "complete.json", + { + "complete": True, + "created_at": gradient.stamp(), + "lock_sha256": lock_hash, + "parent": str(source), + "consumed": consumed, + "world": world_seed, + "seed": seed, + "device": str(device), + "gpu": torch.cuda.get_device_name(device), + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "new_uniform_arms": 9, + "files": { + str(p.relative_to(destination)): editing.file_hash(p) + for p in sorted(destination.rglob("*")) + if p.is_file() and p.suffix in ("npz", ".npz", ".json") + }, + }, + ) + + +def jobs(config): + result = [] + for world, seed in itertools.product(config["worlds"], config["seeds"]): + name = f"world-{world}-seed-{seed}" + result.append(("gradient/" + name, ["run-gradient", "--world", world, "--seed", seed])) + for condition in config["conditions"]: + result.append( + ( + "editing/" + name + "-" + condition, + ["run-edit", "--world", world, "--seed", seed, "--condition", condition], + ) + ) + return result + + +def dispatch(config, gpus, slots): + if not gpus or len(set(gpus)) != len(gpus) or slots < 1 or 0 in gpus: + raise ValueError( + "Unique healthy GPUs and positive concurrency required; GPU0 has ECC errors" + ) + lock_hash = verify_lock(config) + destination = ROOT / config["output"] + destination.mkdir(parents=True, exist_ok=True) + with (destination / ".dispatcher.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + pending, complete, failed, active = [], [], [], [] + for name, arguments in jobs(config): + if (destination / name / "complete.json").exists(): + complete.append(name) + else: + pending.append((name, arguments)) + while pending or active: + for item in active[:]: + code = item["process"].poll() + if code is None: + continue + item["log"].close() + good = code == 0 and (destination / item["name"] / "complete.json").exists() + (complete if good else failed).append(item["name"]) + active.remove(item) + if not failed: + for gpu in gpus: + while pending and sum(i["gpu"] == gpu for i in active) < slots: + name, arguments = pending.pop(0) + out = destination / name + out.mkdir(parents=True, exist_ok=True) + command = [sys.executable, "-m", "llm_memory_editability.bios_followup"] + command += [str(a) for a in arguments] + log = (out / "run.log").open("a") + env = { + **os.environ, + "PYTHONPATH": str(ROOT / "src"), + "CUDA_VISIBLE_DEVICES": str(gpu), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + process = subprocess.Popen( + command, cwd=ROOT, env=env, stdout=log, stderr=log + ) + write_json( + out / "launch.json", + { + "pid": process.pid, + "gpu": gpu, + "command": command, + "started": gradient.stamp(), + }, + ) + active.append({"name": name, "gpu": gpu, "process": process, "log": log}) + write_json( + destination / "status.json", + { + "state": "failed" if failed else "running" if active or pending else "complete", + "lock_sha256": lock_hash, + "complete": complete, + "failed": failed, + "pending": len(pending), + "active": [ + {"name": i["name"], "gpu": i["gpu"], "pid": i["process"].pid} + for i in active + ], + "updated": gradient.stamp(), + }, + ) + if failed and not active: + raise RuntimeError("Worker failure; unstarted jobs retained") + if pending or active: + time.sleep(5) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=("freeze", "dispatch", "run-edit", "run-gradient")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--condition") + parser.add_argument("--gpus", type=int, nargs="+") + parser.add_argument("--slots-per-gpu", type=int, default=1) + parser.add_argument("--device", default="cuda:0") + args = parser.parse_args() + torch.set_num_threads(2) + config = load_config() + if args.mode == "freeze": + print(json.dumps(freeze(config))) + elif args.mode == "dispatch": + dispatch(config, args.gpus, args.slots_per_gpu) + elif args.mode == "run-edit": + run_edit(config, args.world, args.seed, args.condition, torch.device(args.device)) + else: + run_gradient(config, args.world, args.seed, torch.device(args.device)) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_measure.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_measure.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf7c45f10b2be179635d21d0f3a7fde2ee6ca6c --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_measure.py @@ -0,0 +1,286 @@ +"""Pre-edit activation geometry and controlled mean-component interventions. + +Company means are candidate shared components, not assumed learned mechanisms. +All donors, recipients and controls depend only on the old world and fixed seeds. +""" + +import argparse +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import EOS, load_world, rng_for, write_json +from .bios_model import CausalLM, ModelConfig +from .bios_train import code_fingerprint, precision, tensor_data + + +@torch.no_grad() +def activation_summary(model, world, data): + device = data["tokens"].device + collected = [[] for _ in model.blocks] + detailed = {} + first_batch = [True] + handles = [] + # Actual-city atomic queries have final prompt position 3. + for layer, block in enumerate(model.blocks): + + def capture(_module, _inputs, output, layer=layer): + collected[layer].append(output[:, 3].float().cpu()) + if first_batch[0]: + detailed[f"z_positions_layer_{layer}"] = ( + output[:128, [1, 2, 3]].float().cpu().numpy() + ) + + handles.append(block.mlp.activation.register_forward_hook(capture)) + + def capture_mlp(_module, inputs, output, layer=layer): + if first_batch[0]: + detailed[f"x_positions_layer_{layer}"] = ( + inputs[0][:128, [1, 2, 3]].float().cpu().numpy() + ) + detailed[f"h_positions_layer_{layer}"] = ( + output[:128, [1, 2, 3]].float().cpu().numpy() + ) + + handles.append(block.mlp.register_forward_hook(capture_mlp)) + with precision(device): + for begin in range(2112, 4160, 256): + model( + data["prompts"][begin : begin + 256], data["lengths"][begin : begin + 256, None] - 1 + ) + first_batch[0] = False + for handle in handles: + handle.remove() + activations = [torch.cat(parts) for parts in collected] + summaries, means = [], [] + for layer, z in enumerate(activations): + mu = torch.stack([z[world.employers == c].mean(0) for c in range(64)]) + centered = mu - z.mean(0) + residual = z - mu[world.employers] + shared_variance = centered.square().mean().item() + individual_variance = residual.square().mean().item() + cosine = F.cosine_similarity(z, mu[world.employers], dim=-1) + summaries.append( + { + "layer": layer, + "mean_norm": z.norm(dim=-1).mean().item(), + "company_mean_variance": shared_variance, + "within_company_variance": individual_variance, + "shared_variance_fraction": shared_variance + / (shared_variance + individual_variance + 1e-20), + "member_to_company_cosine": cosine.mean().item(), + } + ) + means.append(mu) + detailed["query_ids"] = np.arange(2112, 2240) + detailed["token_positions"] = np.array([1, 2, 3]) + return summaries, means, activations, detailed + + +def probe_plan(world): + rng = rng_for(world.seed, 51) + recipients = rng.permutation(64)[:8] + result = [] + for c in recipients: + same = np.flatnonzero((world.defaults == world.defaults[c]) & (np.arange(64) != c))[0] + donor = rng.choice(np.flatnonzero(world.defaults != world.defaults[c])) + wrong = rng.choice( + np.flatnonzero(~np.isin(world.defaults, [world.defaults[c], world.defaults[donor]])) + ) + unrelated = rng.choice(np.flatnonzero(~np.isin(np.arange(64), [c, donor, same, wrong]))) + members = np.flatnonzero(world.employers == c) + other = np.flatnonzero(world.employers == unrelated) + ids = np.concatenate([2112 + members, 6208 + members, 2112 + other]) + # 6208 is the first birth-city row: employer 2048 + defaults 64 + actual/date 4096. + group = np.concatenate( + [np.where(world.exceptions[members], 1, 0), np.full(32, 2), np.full(32, 3)] + ) + result.append( + { + "recipient": int(c), + "donor": int(donor), + "same_answer": int(same), + "wrong_donor": int(wrong), + "unrelated": int(unrelated), + "ids": ids, + "group": group, + } + ) + return result + + +@torch.no_grad() +def causal_probes(model, world, data, means, behavior=False): + device = data["tokens"].device + results = [] + for plan_index, plan in enumerate(probe_plan(world)): + ids = torch.as_tensor(plan["ids"], device=device) + tokens = data["prompts"][ids] + positions = data["lengths"][ids, None] - 1 + donor_answer = int(world.city_tokens[world.defaults[plan["donor"]]]) + + def observe( + tokens=tokens, positions=positions, donor_answer=donor_answer, ids=ids, plan=plan + ): + with precision(device): + logits = model(tokens, positions)[:, 0].float() + probability = logits.softmax(-1)[:, donor_answer] + if not behavior: + return probability, None + first = logits.argmax(-1) + continuation = torch.zeros((len(ids), 6), dtype=torch.long, device=device) + continuation[:, :5] = tokens + rows = torch.arange(len(ids), device=device) + lengths = data["lengths"][ids] + continuation[rows, lengths] = first + ended = model(continuation, lengths[:, None])[:, 0].argmax(-1).eq(EOS) + truth = torch.as_tensor(world.answers[plan["ids"]], device=device) + return probability, { + "old_correct": (first.eq(truth) & ended).cpu().numpy(), + "donor_generated": (first.eq(donor_answer) & ended).cpu().numpy(), + "ended": ended.cpu().numpy(), + } + + baseline, baseline_behavior = observe() + for layer, mu_cpu in enumerate(means): + mu = mu_cpu.to(device) + c = plan["recipient"] + desired = mu[plan["donor"]] - mu[c] + generator = torch.Generator(device=device).manual_seed( + world.seed * 10000 + 100 * plan_index + layer + ) + random = torch.randn(desired.shape, generator=generator, device=device) + random = random * (desired.norm() / random.norm().clamp_min(1e-20)) + shifts = { + "donor": desired, + "same_answer_donor": mu[plan["same_answer"]] - mu[c], + "wrong_donor": mu[plan["wrong_donor"]] - mu[c], + "random_equal_norm": random, + "ablation": -(mu[c] - mu.mean(0)), + } + for kind, shift in shifts.items(): + + def patch(_module, _inputs, output, shift=shift): + edited = output.clone() + edited[:, 3] = edited[:, 3] + shift.to(output.dtype) + return edited + + handle = model.blocks[layer].mlp.activation.register_forward_hook(patch) + try: + changed, changed_behavior = observe() + finally: + handle.remove() + delta = (changed - baseline).cpu().numpy() + by_group = { + name: float(delta[plan["group"] == group].mean()) + for group, name in enumerate( + ( + "same_company_nonexception", + "old_exception", + "independent_attribute", + "unrelated_company", + ) + ) + } + result = { + "recipient": c, + "donor": plan["donor"], + "layer": layer, + "intervention": kind, + "shift_norm": shift.norm().item(), + **by_group, + "selective_shared_score": by_group["same_company_nonexception"] + - (by_group["independent_attribute"] + by_group["unrelated_company"]) / 2, + } + if behavior: + result["generation"] = {} + for group, name in enumerate(by_group): + mask = plan["group"] == group + known = mask & baseline_behavior["old_correct"] + result["generation"][name] = { + "n": int(mask.sum()), + "baseline_old_accuracy": float( + baseline_behavior["old_correct"][mask].mean() + ), + "changed_old_accuracy": float( + changed_behavior["old_correct"][mask].mean() + ), + "donor_generated_delta": float( + changed_behavior["donor_generated"][mask].mean() + - baseline_behavior["donor_generated"][mask].mean() + ), + "old_known": int(known.sum()), + "old_broken": int((known & ~changed_behavior["old_correct"]).sum()), + "nontermination_rate": float((~changed_behavior["ended"][mask]).mean()), + } + results.append(result) + return results + + +def run(args): + started = time.perf_counter() + torch.set_num_threads(4) + device = torch.device(args.device) + world = load_world(args.world) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + model.eval() + data = tensor_data(world, device) + summary, means, activations, detailed = activation_summary(model, world, data) + probes = causal_probes(model, world, data, means, behavior=args.behavior) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + out / "actual-city-activations.npz", + **{f"z_{i}": z.numpy() for i, z in enumerate(activations)}, + ) + np.savez_compressed(out / "input-activation-output-position-sample.npz", **detailed) + write_json( + out / "measurements.json", + { + "step": checkpoint["step"], + "device": str(device), + "precision": "BF16 autocast" if device.type == "cuda" else "FP32 CPU diagnostic", + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": hashlib.sha256(Path(args.checkpoint).read_bytes()).hexdigest(), + "measurement_seconds": time.perf_counter() - started, + "torch_version": torch.__version__, + "hardware": torch.cuda.get_device_name(device) if device.type == "cuda" else "CPU", + "behavior": args.behavior, + **code_fingerprint(), + "geometry": summary, + "probes": probes, + "scope": ( + "candidate company-mean components at final query token; " + "exploratory development measurement" + ), + }, + ) + print( + json.dumps( + {"event": "measurement_complete", "step": checkpoint["step"], "probes": len(probes)} + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument( + "--behavior", action="store_true", help="Also score complete generated answers" + ) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_mechanism_causal.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_mechanism_causal.py new file mode 100644 index 0000000000000000000000000000000000000000..8ac824d1ef628725bf1ee9ca778d381516508a80 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_mechanism_causal.py @@ -0,0 +1,969 @@ +"""Locked P4 necessity and downstream restoration diagnostics. + +Q is fitted only on actual queries in an archived exception case's S union R, +grouped by the model's own membership predictions. Truth-matched donor queries +are a subsequent diagnostic, never calibration. Restoring a same-query clean +downstream signal tests recovery from an artificial lesion, not edit repair. +""" + +import csv +import json +from pathlib import Path + +import numpy as np +import torch + +from .bios_causal_paths import make_donor_plan +from .bios_cross import CHAINS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_mechanism_interventions import ( + Site, + attach_state_operation, + calibration_plan, + downstream_routing_site, + fit_predicted_group_bases, + match_delta_norm, + projection_component, + query_site_roles, + remove_projection, + restore_projection, + valid_predicted_groups, +) +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import file_sha256 +from .bios_train import precision + +SOURCE = Site(0, 2) +DOWNSTREAM = Site(1, 2) +RANK = 32 +FAMILIES = ( + "default", + "actual", + "other_chain_default", + "attribute_3", + "attribute_4", + "attribute_5", + "attribute_6", + "membership", + "other_chain_actual", + "group_root", +) +ARMS = ( + "clean", + "sham", + "target_remove", + "random_remove", + "complement_remove", + "rescue_only", + "remove_rescue", + "remove_wrong_source_rescue", + "remove_random_rescue", +) +TRANSFER_TYPES = ( + "different_group_same_actual_different_default", + "different_group_same_default", + "different_group_same_default_same_actual", +) +TRANSFER_ARMS = ( + "sham", + "full_donor", + "full_norm_random", + "projected_target", + "projected_random", + "projected_complement", +) + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen diagnostic contract changed: {path}") + else: + write_json(path, value) + + +def _same_arrays(path, arrays): + if path.exists(): + with np.load(path) as existing: + if set(existing.files) != set(arrays) or any( + not np.array_equal(existing[key], value) for key, value in arrays.items() + ): + raise ValueError(f"Diagnostic plan changed: {path}") + else: + atomic_numpy_save(path, **arrays) + + +def _sources(): + directory = Path(__file__).parent + names = ( + "bios_mechanism_causal.py", + "bios_mechanism_interventions.py", + "bios_causal_paths.py", + "bios_cross.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_path_diagnostics.py", + ) + sources = {name: file_sha256(directory / name) for name in names} + runner = directory.parents[1] / "scripts/analyze_bios_mechanism_causal.py" + sources["runner"] = file_sha256(runner) + return sources + + +def validate_lock(lock): + if (lock.get("mechanism"), lock.get("layer"), lock.get("position")) != ("default_path", 0, 2): + raise ValueError("This runner only instantiates the locked default_path L0/pos2 candidate") + if lock.get("known_only") is not False or not lock.get("locked_at_utc"): + raise ValueError("An all-eligible, timestamped candidate lock is required") + + +def make_probe_plan(world, chain, recipients): + """Same people and fixed queries in every intervention, without knowledge filtering.""" + recipients = np.asarray(recipients, dtype=np.int64) + ids = [ + world.derived_ids[chain, recipients], + world.actual_ids[chain, recipients], + world.derived_ids[1 - chain, recipients], + ] + for relation in (3, 4, 5, 6): + candidates = np.flatnonzero(world.relation == relation) + by_person = np.full(len(world.actual_ids[chain]), -1, dtype=np.int64) + by_person[world.person[candidates]] = candidates + if (by_person[recipients] < 0).any(): + raise ValueError("An independent control query is missing") + ids.append(by_person[recipients]) + ids.extend([world.membership_ids[chain, recipients], world.actual_ids[1 - chain, recipients]]) + person_families = len(ids) + roots = world.root_ids[chain] + query_ids = np.concatenate([*ids, roots]) + return { + "query_id": query_ids, + "person": np.r_[np.tile(recipients, person_families), np.full(len(roots), -1)], + "family": np.r_[ + np.repeat(np.arange(person_families), len(recipients)), + np.full(len(roots), person_families), + ], + # -1 means not applicable; root facts are not ordinary people. + "recipient_old_exception": np.r_[ + np.tile(world.exceptions[chain, recipients].astype(np.int8), person_families), + np.full(len(roots), -1, dtype=np.int8), + ], + "answer": world.answers[query_ids], + } + + +def wrong_source_indices(families): + """Fixed one-person cyclic shift within each family, never chosen by answers.""" + families = np.asarray(families) + index = np.arange(len(families)) + for family in np.unique(families): + selected = np.flatnonzero(families == family) + if len(selected) < 2: + raise ValueError("Wrong-source controls require at least two queries per family") + index[selected] = np.roll(selected, 1) + return index + + +def make_transfer_plan(world, chain, per_population=64): + """Truth matching is restricted to this explicitly labeled offline diagnostic.""" + old = make_donor_plan(world, chain, per_population) + original = old["pair_type"] == 1 + recipients = old["recipient"][original] + train = world.person[world.train_ids[chain]] + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + rng = rng_for(world.seed, 978, chain) + donor_rows = [old["donor"][original]] + count_rows = [old["candidate_count"][original]] + for same_actual in (False, True): + donors, counts = [], [] + for recipient in recipients: + mask = (group[train] != group[recipient]) & (default[train] == default[recipient]) + if same_actual: + mask &= actual[train] == actual[recipient] + candidates = train[mask] + donors.append(rng.choice(candidates) if len(candidates) else -1) + counts.append(len(candidates)) + donor_rows.append(np.asarray(donors)) + count_rows.append(np.asarray(counts)) + donor = np.concatenate(donor_rows).astype(np.int64) + recipient = np.tile(recipients, len(TRANSFER_TYPES)) + safe = np.maximum(donor, 0) + return { + "case_id": np.arange(len(donor)), + "recipient": recipient, + "donor": donor, + "pair_type": np.repeat(np.arange(len(TRANSFER_TYPES)), len(recipients)), + "candidate_count": np.concatenate(count_rows), + "recipient_old_exception": world.exceptions[chain, recipient], + "same_actual": (actual[safe] == actual[recipient]) & (donor >= 0), + "same_default": (default[safe] == default[recipient]) & (donor >= 0), + "recipient_default": default[recipient], + "recipient_actual": actual[recipient], + "donor_default": np.where(donor >= 0, default[safe], -1), + "donor_actual": np.where(donor >= 0, actual[safe], -1), + } + + +def generate_queries( + model, prompts, lengths, device, batch_size=256, *, operations=None, capture_sites=() +): + """Two free generation passes with identical pre-answer operations, no answer input. + + operations(begin,end) returns (label, site, operation) triples. Every operation + returns its intended delta and availability; realized post-cast norms are + measured separately. Both passes are retained so norm matching is auditable. + """ + if len(prompts) == 0 or batch_size < 1: + raise ValueError("Generation needs nonempty queries and a positive batch size") + lengths = np.asarray(lengths) + if prompts.shape != (len(lengths), 5) or not np.isin(lengths, [4, 5]).all(): + raise ValueError("Unexpected symbolic query shape") + arrays = {"prediction": [], "ended": []} + for site in capture_sites: + query_site_roles(lengths, site.position) + arrays[f"state_{site.layer}_{site.position}"] = [] + calls = 0 + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + end = min(begin + batch_size, len(prompts)) + p = torch.as_tensor(prompts[begin:end], device=device) + n = torch.as_tensor(lengths[begin:end], device=device) + hooks, traces, captures = [], {}, {} + try: + for label, site, operation in () if operations is None else operations(begin, end): + query_site_roles(lengths[begin:end], site.position) + + def measured(value, operation=operation): + changed, trace = operation(value) + return changed, {**trace, "realized_delta": changed.float() - value.float()} + + hook, trace = attach_state_operation(model, site, measured) + hooks.append(hook) + traces[label] = trace + for site in capture_sites: + key = f"state_{site.layer}_{site.position}" + captures[key] = [] + + def capture( + _module, _inputs, output, key=key, position=site.position, captures=captures + ): + captures[key].append(output[:, position].detach().float()) + + hooks.append(model.blocks[site.layer].register_forward_hook(capture)) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + calls += 2 + arrays["prediction"].append(first.cpu().numpy()) + arrays["ended"].append(second.eq(EOS).cpu().numpy()) + for key, states in captures.items(): + arrays[key].append(states[0].cpu().numpy()) + drift = torch.linalg.vector_norm(states[1] - states[0], dim=-1) + arrays.setdefault(f"{key}_pass_drift", []).append(drift.cpu().numpy()) + for label, trace in traces.items(): + if len(trace) != 2: + raise ValueError( + "Every intervention must occur in both free-generation passes" + ) + for kind in ("delta", "realized_delta"): + norms = torch.stack( + [torch.linalg.vector_norm(t[kind].float(), dim=-1) for t in trace], + dim=1, + ) + arrays.setdefault(f"{label}_{kind}_norm", []).append(norms.cpu().numpy()) + valid = torch.stack([t["valid"] for t in trace], dim=1) + arrays.setdefault(f"{label}_valid", []).append(valid.cpu().numpy()) + finally: + for hook in hooks: + hook.remove() + result = {key: np.concatenate(value) for key, value in arrays.items()} + result.update( + forward_calls=np.asarray(calls), + forward_examples=np.asarray(2 * len(prompts)), + padded_token_positions=np.asarray(11 * len(prompts)), + logical_token_positions=np.asarray(int((2 * lengths + 1).sum())), + ) + return result + + +def _identity_trace(value): + return value, { + "delta": torch.zeros_like(value, dtype=torch.float32), + "valid": torch.ones(len(value), dtype=torch.bool, device=value.device), + } + + +def lesion_operations( + arm, source_bases, downstream_bases, clean_downstream, wrong_index, seed, device +): + """Return a deterministic batch factory. Wrong-source choice never sees truth.""" + if arm not in ARMS: + raise ValueError("Unknown necessity/restoration arm") + if arm == "clean": + return lambda _begin, _end: [] + if arm == "sham": + return lambda _begin, _end: [("source", SOURCE, _identity_trace)] + source = {key: basis.tensors(device) for key, basis in source_bases.items()} + downstream = ( + None + if downstream_bases is None + else {key: basis.tensors(device) for key, basis in downstream_bases.items()} + ) + needs_downstream = "rescue" in arm + if needs_downstream and downstream is None: + raise ValueError("Downstream basis is unavailable; recovery cannot be estimated") + wrong_index = np.asarray(wrong_index) + if len(wrong_index) != len(clean_downstream): + raise ValueError("Wrong-source plan length mismatch") + coefficients = ( + np.random.default_rng(seed) + .standard_normal((len(clean_downstream), source_bases["random"].rank)) + .astype(np.float32) + ) + + def factory(begin, end): + ops = [] + if arm == "clean": + return ops + if arm == "sham": + return [("source", SOURCE, _identity_trace)] + if arm != "rescue_only": + kind = ( + arm.removesuffix("_remove") + if arm in ("random_remove", "complement_remove") + else "target" + ) + q, mean, _ = source[kind] + tq, tm, _ = source["target"] + + def remove(value): + reference = ( + None + if kind == "target" + else torch.linalg.vector_norm(projection_component(value, tq, tm), dim=-1) + ) + return remove_projection(value, q, mean, reference) + + ops.append(("source", SOURCE, remove)) + if needs_downstream: + clean = torch.as_tensor(clean_downstream[begin:end], device=device) + wrong = torch.as_tensor(clean_downstream[wrong_index[begin:end]], device=device) + tq = downstream["target"][0] + rq = downstream["random"][0] + noise = torch.as_tensor(coefficients[begin:end], device=device) @ rq.T + + def recover(value): + _, same_query_trace = restore_projection(value, clean, tq) + correct_delta = same_query_trace["delta"] + reference = torch.linalg.vector_norm(correct_delta, dim=-1) + if arm == "remove_wrong_source_rescue": + return restore_projection(value, wrong, tq, reference) + if arm == "remove_random_rescue": + delta, valid = match_delta_norm(noise, reference) + return value + delta.to(value.dtype), {"delta": delta, "valid": valid} + return restore_projection(value, clean, tq) + + ops.append(("downstream", DOWNSTREAM, recover)) + return ops + + return factory + + +def transfer_operations(arm, bases, recipient, donor, seed, device): + """A locked-basis manipulation check, never a basis-fitting input.""" + if arm not in TRANSFER_ARMS or recipient.shape != donor.shape: + raise ValueError("Invalid donor manipulation") + if arm.startswith("projected_") and bases is None: + raise ValueError("Projected donor diagnostic requires an available source basis") + full_delta = donor.astype(np.float32) - recipient.astype(np.float32) + if arm == "sham": + delta, valid = np.zeros_like(full_delta), np.ones(len(donor), dtype=bool) + elif arm == "full_donor": + delta, valid = full_delta, np.ones(len(donor), dtype=bool) + else: + if arm == "full_norm_random": + raw = np.random.default_rng(seed).standard_normal(full_delta.shape).astype(np.float32) + reference = np.linalg.norm(full_delta, axis=-1) + else: + tq = bases["target"].q + target_delta = (full_delta @ tq) @ tq.T + reference = np.linalg.norm(target_delta, axis=-1) + q = bases[arm.removeprefix("projected_")].q + raw = (full_delta @ q) @ q.T + matched, available = match_delta_norm(torch.from_numpy(raw), torch.from_numpy(reference)) + delta, valid = matched.numpy(), available.numpy() + + def factory(begin, end): + change = torch.as_tensor(delta[begin:end], device=device) + available = torch.as_tensor(valid[begin:end], device=device) + + def operation(value): + return value + change.to(value.dtype), {"delta": change, "valid": available} + + return [("source", SOURCE, operation)] + + return factory + + +def _availability(arrays): + valid = np.ones(len(arrays["prediction"]), dtype=bool) + for key, value in arrays.items(): + if key.endswith("_valid"): + valid &= value.all(axis=1) + return valid + + +def score_rows(arrays, baseline, plan, arm, labels=FAMILIES, label_key="family"): + """All eligible rows first; original-correct strata remain descriptive only.""" + base_correct = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + correct = (arrays["prediction"] == plan["answer"]) & arrays["ended"] + available = _availability(arrays) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available + n, nb = int(chosen.sum()), int((chosen & base_correct).sum()) + before, after = int((chosen & base_correct).sum()), int((chosen & correct).sum()) + row = { + "arm": arm, + "family": family, + "population": population, + "requested": int(requested.sum()), + "available": n, + "unavailable": int((requested & ~available).sum()), + "baseline_correct": before, + "correct": after, + "accuracy": after / n if n else None, + "delta_accuracy": (after - before) / n if n else None, + "known_became_wrong": int((chosen & base_correct & ~correct).sum()), + "wrong_became_correct": int((chosen & ~base_correct & correct).sum()), + "known_denominator": nb, + "known_retention": int((chosen & base_correct & correct).sum()) / nb + if nb + else None, + "termination_error": int((chosen & ~arrays["ended"]).sum()), + "prediction_changed": int( + ( + chosen + & ( + (arrays["prediction"] != baseline["prediction"]) + | (arrays["ended"] != baseline["ended"]) + ) + ).sum() + ), + } + for label in ("source", "downstream"): + for kind in ("delta", "realized_delta"): + key = f"{label}_{kind}_norm" + row[f"mean_{key}"] = ( + float(arrays[key][chosen, 0].mean()) if n and key in arrays else None + ) + rows.append(row) + return rows + + +def paired_score_rows( + left, right, baseline, plan, left_name, right_name, labels=FAMILIES, label_key="family" +): + """Contrasts use a common availability mask, never unmatched denominators.""" + correct_left = (left["prediction"] == plan["answer"]) & left["ended"] + correct_right = (right["prediction"] == plan["answer"]) & right["ended"] + correct_clean = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + available_left, available_right = _availability(left), _availability(right) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available_left & available_right + n = int(chosen.sum()) + nl, nr = int((chosen & correct_left).sum()), int((chosen & correct_right).sum()) + known_right_wrong = chosen & correct_clean & ~correct_right + denominator = int(known_right_wrong.sum()) + rows.append( + { + "left": left_name, + "right": right_name, + "family": family, + "population": population, + "requested": int(requested.sum()), + "common_available": n, + "left_unavailable": int((requested & ~available_left).sum()), + "right_unavailable": int((requested & ~available_right).sum()), + "left_correct": nl, + "right_correct": nr, + "accuracy_difference": (nl - nr) / n if n else None, + "right_wrong_left_correct": int((chosen & ~correct_right & correct_left).sum()), + "right_correct_left_wrong": int((chosen & correct_right & ~correct_left).sum()), + "original_known_right_wrong": denominator, + "original_known_right_wrong_left_recovered": int( + (known_right_wrong & correct_left).sum() + ), + "conditional_recovery_auxiliary": int((known_right_wrong & correct_left).sum()) + / denominator + if denominator + else None, + } + ) + return rows + + +def _check_predictions(generated, archived, ids): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], archived[key][ids]): + raise ValueError(f"Clean frozen-model generation differs from archive: {key}") + + +def _cost(arrays): + return { + key: int(arrays[key]) + for key in ( + "forward_calls", + "forward_examples", + "padded_token_positions", + "logical_token_positions", + ) + } + + +def _cached_generate(path, model, world, ids, device, batch_size, **kwargs): + if path.exists(): + with np.load(path) as stored: + result = dict(stored) + if not np.array_equal(result.pop("query_id"), ids): + raise ValueError("Cached generation query plan differs") + return result + result = generate_queries( + model, world.prompts[ids], world.lengths[ids], device, batch_size, **kwargs + ) + atomic_numpy_save(path, query_id=ids, **result) + return result + + +def _fit_chain(model, world, chain, pair, dest, device, batch_size, archived): + plan = calibration_plan( + world.actual_ids[chain], + world.person, + world.membership_ids[chain], + pair["E"], + pair["replay"], + ) + _same_arrays( + dest / "calibration-plan.npz", {key: np.asarray(value) for key, value in plan.items()} + ) + actual = _cached_generate( + dest / "calibration-actual.npz", + model, + world, + plan["actual_query_ids"], + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + membership = _cached_generate( + dest / "calibration-membership.npz", + model, + world, + plan["membership_query_ids"], + device, + batch_size, + ) + _check_predictions(actual, archived, plan["actual_query_ids"]) + _check_predictions(membership, archived, plan["membership_query_ids"]) + prefix = f"{CHAINS[chain]}:" + allowed = np.array( + [i for i, label in enumerate(world.token_labels) if label.startswith(prefix)] + ) + groups, valid = valid_predicted_groups(membership["prediction"], membership["ended"], allowed) + _same_arrays(dest / "self-predicted-groups.npz", {"prediction": groups, "valid": valid}) + bases, reports, basis_arrays = {}, {}, {} + for label, site in (("source", SOURCE), ("downstream", DOWNSTREAM)): + basis, report = fit_predicted_group_bases( + actual[f"state_{site.layer}_{site.position}"], groups, valid, rank=RANK, seed=74 + chain + ) + bases[label], reports[label] = basis, report + if basis is not None: + for kind, value in basis.items(): + for field in ("q", "mean", "scale"): + basis_arrays[f"{label}_{kind}_{field}"] = getattr(value, field) + _same_arrays(dest / "bases.npz", basis_arrays) + information = { + "S_count": len(pair["E"]), + "R_count": len(pair["replay"]), + "actual_queries": len(plan["actual_query_ids"]), + "additional_membership_queries": len(plan["membership_query_ids"]), + "derived_calibration_queries": 0, + "true_memberships_supplied": False, + "membership_syntax_rule": prefix, + "invalid_groups_never_replaced": True, + "calibration_cost": {"actual": _cost(actual), "membership": _cost(membership)}, + "basis_reports": reports, + "variant": "group_means", + "basis_sha256": file_sha256(dest / "bases.npz"), + } + _freeze_json(dest / "calibration.json", information) + # Truth is read only after Q and its information contract are frozen. These + # labels score calibration quality; they never select rows or alter Q. + membership_correct = ( + membership["prediction"] == world.answers[plan["membership_query_ids"]] + ) & membership["ended"] + _freeze_json( + dest / "calibration-diagnostics.json", + { + "role": "offline scoring after frozen Q; never fitting or row selection", + "queries": len(groups), + "valid_predictions": int(valid.sum()), + "valid_rate": float(valid.mean()), + "correct_predictions": int(membership_correct.sum()), + "accuracy": float(membership_correct.mean()), + "accuracy_given_valid_auxiliary": float(membership_correct[valid].mean()) + if valid.any() + else None, + "basis_sha256": information["basis_sha256"], + }, + ) + return bases + + +def run_chain(model, world, chain, pair, dest, device, batch_size, per_population, archived): + dest.mkdir(parents=True, exist_ok=True) + bases = _fit_chain(model, world, chain, pair, dest, device, batch_size, archived) + transfer = make_transfer_plan(world, chain, per_population) + _same_arrays(dest / "transfer-plan.npz", transfer) + recipients = transfer["recipient"][transfer["pair_type"] == 0] + plan = make_probe_plan(world, chain, recipients) + plan["wrong_source_index"] = wrong_source_indices(plan["family"]) + plan["wrong_source_query_id"] = plan["query_id"][plan["wrong_source_index"]] + plan["wrong_source_same_answer"] = plan["answer"] == plan["answer"][plan["wrong_source_index"]] + _same_arrays(dest / "probe-plan.npz", plan) + ids = plan["query_id"] + query_site_roles(world.lengths[ids], SOURCE.position) + if downstream_routing_site(SOURCE, len(model.blocks), world.lengths[ids] - 1) != DOWNSTREAM: + raise ValueError("Candidate/downstream site mismatch") + clean = _cached_generate( + dest / "clean.npz", + model, + world, + ids, + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + _check_predictions(clean, archived, ids) + rows, states, costs, arm_arrays = [], {}, {"clean": _cost(clean)}, {} + clean_down = clean[f"state_{DOWNSTREAM.layer}_{DOWNSTREAM.position}"] + for arm in ARMS: + if arm not in ("clean", "sham") and bases["source"] is None: + states[arm] = "unavailable_source_rank" + continue + if "rescue" in arm and bases["downstream"] is None: + states[arm] = "unavailable_downstream_rank" + continue + if arm == "clean": + generated = clean + else: + operations = lesion_operations( + arm, + bases["source"], + bases["downstream"], + clean_down, + plan["wrong_source_index"], + [world.seed, 979, chain], + device, + ) + generated = _cached_generate( + dest / f"{arm}.npz", model, world, ids, device, batch_size, operations=operations + ) + if arm in ("sham", "rescue_only"): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], clean[key]): + raise ValueError(f"No-lesion control changed output: {arm}/{key}") + rows.extend(score_rows(generated, clean, plan, arm)) + costs[arm], states[arm] = _cost(generated), "complete" + arm_arrays[arm] = generated + comparisons = [ + (arm, "clean") + for arm in ("sham", "target_remove", "random_remove", "complement_remove", "rescue_only") + ] + comparisons += [("target_remove", arm) for arm in ("random_remove", "complement_remove")] + comparisons += [ + (arm, "target_remove") + for arm in ("remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue") + ] + comparisons += [ + ("remove_rescue", arm) for arm in ("remove_wrong_source_rescue", "remove_random_rescue") + ] + paired_rows = [] + for left, right in comparisons: + if left in arm_arrays and right in arm_arrays: + paired_rows.extend( + paired_score_rows(arm_arrays[left], arm_arrays[right], clean, plan, left, right) + ) + # Donor activations are read only after both bases and their provenance are frozen. + valid = transfer["donor"] >= 0 + selected = {key: value[valid] for key, value in transfer.items()} + people = np.unique(np.r_[selected["recipient"], selected["donor"]]) + donor_ids = world.derived_ids[chain, people] + donor_clean = _cached_generate( + dest / "transfer-clean.npz", + model, + world, + donor_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + _check_predictions(donor_clean, archived, donor_ids) + ri, di = ( + np.searchsorted(people, selected["recipient"]), + np.searchsorted(people, selected["donor"]), + ) + source_state = donor_clean[f"state_{SOURCE.layer}_{SOURCE.position}"] + donor_baseline = {key: donor_clean[key][ri] for key in ("prediction", "ended")} + donor_plan = {**selected, "answer": selected["recipient_default"]} + transfer_rows, transfer_status = [], {} + costs["transfer_clean"] = _cost(donor_clean) + for arm in TRANSFER_ARMS: + if arm.startswith("projected_") and bases["source"] is None: + transfer_status[arm] = "unavailable_source_rank" + continue + ops = transfer_operations( + arm, + bases["source"], + source_state[ri], + source_state[di], + [world.seed, 980, chain], + device, + ) + generated = _cached_generate( + dest / f"transfer-{arm}.npz", + model, + world, + world.derived_ids[chain, selected["recipient"]], + device, + batch_size, + operations=ops, + ) + if arm == "sham": + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], donor_baseline[key]): + raise ValueError("Transfer sham changed output") + scored = score_rows( + generated, donor_baseline, donor_plan, arm, labels=TRANSFER_TYPES, label_key="pair_type" + ) + for row in scored: + code = TRANSFER_TYPES.index(row["family"]) + chosen = (selected["pair_type"] == code) & _availability(generated) + requested = transfer["pair_type"] == code + if row["population"] != "all": + exception = row["population"] == "old_exception" + chosen &= selected["recipient_old_exception"] == exception + requested &= transfer["recipient_old_exception"] == exception + row["plan_requested"] = int(requested.sum()) + row["missing_donors"] = int((requested & ~valid).sum()) + for role in ("recipient_actual", "donor_default", "donor_actual"): + matched = (generated["prediction"] == selected[role]) & generated["ended"] + base_matched = (donor_baseline["prediction"] == selected[role]) & donor_baseline[ + "ended" + ] + row[f"matches_{role}"] = int((chosen & matched).sum()) + row[f"baseline_matches_{role}"] = int((chosen & base_matched).sum()) + # Donor's own clean response is descriptive, not an eligibility filter. + row["donor_answered_default"] = int( + ( + chosen + & donor_clean["ended"][di] + & (donor_clean["prediction"][di] == selected["donor_default"]) + ).sum() + ) + transfer_rows.extend(scored) + transfer_status[arm], costs[f"transfer_{arm}"] = "complete", _cost(generated) + for filename, contents in ( + ("necessity.csv", rows), + ("paired-necessity.csv", paired_rows), + ("transfer.csv", transfer_rows), + ): + with (dest / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + dest / "status.json", + { + "arms": states, + "transfer_arms": transfer_status, + "evaluation_cost": costs, + "information_boundary": "truth-matched donor states are diagnostic only", + }, + ) + return {"chain": CHAINS[chain], "arms": states, "transfer_arms": transfer_status} + + +def scientific_outputs(output): + """Seal only producer-owned artifacts, excluding mutable queue logs and locks.""" + names = { + "calibration-plan.npz", + "calibration-actual.npz", + "calibration-membership.npz", + "self-predicted-groups.npz", + "bases.npz", + "calibration.json", + "calibration-diagnostics.json", + "transfer-plan.npz", + "probe-plan.npz", + "transfer-clean.npz", + "necessity.csv", + "paired-necessity.csv", + "transfer.csv", + "status.json", + } + names.update(f"{arm}.npz" for arm in ARMS) + names.update(f"transfer-{arm}.npz" for arm in TRANSFER_ARMS) + paths = [output / "contract.json"] + for chain in CHAINS: + paths.extend( + output / chain / name for name in sorted(names) if (output / chain / name).exists() + ) + return {str(path.relative_to(output)): file_sha256(path) for path in paths} + + +def run_model(run, output, lock_path, *, device="cuda", batch_size=256, per_population=64): + """One original pre-edit checkpoint, both chains; separate outputs, restartable nodes.""" + run, output, lock_path = Path(run).resolve(), Path(output).resolve(), Path(lock_path).resolve() + if output == run or run in output.parents: + raise ValueError("Never write diagnostics inside the frozen parent") + lock = json.loads(lock_path.read_text()) + validate_lock(lock) + config = json.loads((run / "config.json").read_text()) + if ( + config["world"] not in (0, 1) + or config["model"]["width"] not in (256, 768) + or config["seed"] not in (0, 1) + or config["condition"] not in (*CHAINS, "neither") + ): + raise ValueError("The original 24-model development matrix is required") + step = config["study"]["steps"] + if step != 15360 or per_population != 64: + raise ValueError("The parent step and 64+64 recipient budget are fixed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent runtime differs: {key}") + device = torch.device(device) + weights = run / f"model-{step}.pt" + contract = { + "run": str(run), + "step": step, + "world": config["world"], + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "parent_config_sha256": file_sha256(run / "config.json"), + "parent_weights_sha256": file_sha256(weights), + "lock": lock, + "lock_sha256": file_sha256(lock_path), + "sources": _sources(), + "source_site": [0, 2], + "downstream_site": [1, 2], + "rank": RANK, + "per_population": per_population, + "batch_size": batch_size, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": device.type, + "checkpoint_role": "pre_edit_clean_only", + "calibration": "S_union_R_actual_queries_with_self_predicted_membership_groups", + "families": list(FAMILIES), + "arms": list(ARMS), + "transfer_types": list(TRANSFER_TYPES), + "transfer_arms": list(TRANSFER_ARMS), + "wrong_source_rule": "cyclic_previous_query_within_family_no_truth_or_prediction_selection", + "cross_query_reference": "The actual-calibration mean is reused for all query families", + "recovery_source": "Same checkpoint and same query clean post-L1/pos2 target projection", + "rescue_only_role": "No-lesion downstream sham; cannot establish necessity", + "random_recovery": "Random rank32 downstream basis; same-query recovery delta norm", + "rank_failure": "Unavailable, never padded or replaced; report coverage by organization", + "interpretation": ( + "Artificial-lesion behavior recovery; no claim of edit repair " + "or organizational specificity" + ), + } + output.mkdir(parents=True, exist_ok=True) + _freeze_json(output / "contract.json", contract) + complete_path = output / "complete.json" + if complete_path.exists(): + complete = json.loads(complete_path.read_text()) + for name, digest in complete["outputs"].items(): + if file_sha256(output / name) != digest: + raise ValueError(f"Completed diagnostic artifact changed: {name}") + return complete + repository = Path(__file__).resolve().parents[2] + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent generated world changed") + saved = torch.load(weights, map_location="cpu", weights_only=False) + final = json.loads((run / "learning-complete.json").read_text()) + if ( + saved["config"] != config["model"] + or saved["step"] != step + or state_hash(saved["model"]) != final["model_sha256"] + ): + raise ValueError("Parent model identity mismatch") + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + with np.load(run / f"predictions-{step}.npz") as stored: + archived = {key: stored[key] for key in ("prediction", "ended")} + completed = [] + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + reference = run / "edits" / f"{name}-exception-mlp" + with np.load(reference / "sets.npz") as old: + for key in ("E", "replay", "exception"): + if not np.array_equal(old[key], pair[key]): + raise ValueError( + f"Original exception calibration permission changed: {name}/{key}" + ) + if not (reference / "complete.json").exists(): + raise ValueError("Original exception case is incomplete") + completed.append( + run_chain( + model, + world, + chain, + pair, + output / name, + device, + batch_size, + per_population, + archived, + ) + ) + print( + json.dumps({"event": "necessity_chain_complete", "run": str(run), "chain": name}), + flush=True, + ) + if _sources() != contract["sources"]: + raise ValueError("Diagnostic implementation changed during execution") + outputs = scientific_outputs(output) + complete = {"status": "complete", "chains": completed, "outputs": outputs} + write_json(complete_path, complete) + return complete diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..322ecd4a965475d9878cbb14cb7a3eee131cf9ca --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py @@ -0,0 +1,1082 @@ +"""P4 v2: unchanged interventions with explicit local numerical baselines. + +Q is fitted only on actual queries in an archived exception case's S union R, +grouped by the model's own membership predictions. Truth-matched donor queries +are a subsequent diagnostic, never calibration. Restoring a same-query clean +downstream signal tests recovery from an artificial lesion, not edit repair. +""" + +import csv +import json +from pathlib import Path + +import numpy as np +import torch + +from .bios_causal_paths import make_donor_plan +from .bios_cross import CHAINS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_mechanism_interventions import ( + Site, + attach_state_operation, + calibration_plan, + downstream_routing_site, + fit_predicted_group_bases, + match_delta_norm, + projection_component, + query_site_roles, + remove_projection, + restore_projection, + valid_predicted_groups, +) +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import file_sha256 +from .bios_train import precision + +SOURCE = Site(0, 2) +DOWNSTREAM = Site(1, 2) +RANK = 32 +NUMERICAL_POLICY = { + "version": "p4-numerical-policy-v2", + "original_identity_gate": "20608 queries; original order/batch512; exact archive values/EOS", + "subset_baseline": "Same query/order/batch local clean for every causal contrast", + "archive_subset_difference": "All queries and both outputs retained; no exclusions", + "donor_baseline": "Extra clean replay in duplicated recipient order and intervention batch", + "local_sham_and_rescue_only": "Strict exact value/EOS equality; never relaxed", + "restore_reference": "Unchanged v1 first-pass pre-answer source; pass drift remains recorded", + "scientific_design": "Candidate, rank, calibration, intervention, pairing, strata unchanged", + "precision": "Unchanged BF16 autocast; FP32 weights; TF32 allowed as in original training", +} +FAMILIES = ( + "default", + "actual", + "other_chain_default", + "attribute_3", + "attribute_4", + "attribute_5", + "attribute_6", + "membership", + "other_chain_actual", + "group_root", +) +ARMS = ( + "clean", + "sham", + "target_remove", + "random_remove", + "complement_remove", + "rescue_only", + "remove_rescue", + "remove_wrong_source_rescue", + "remove_random_rescue", +) +TRANSFER_TYPES = ( + "different_group_same_actual_different_default", + "different_group_same_default", + "different_group_same_default_same_actual", +) +TRANSFER_ARMS = ( + "sham", + "full_donor", + "full_norm_random", + "projected_target", + "projected_random", + "projected_complement", +) + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen diagnostic contract changed: {path}") + else: + write_json(path, value) + + +def _same_arrays(path, arrays): + if path.exists(): + with np.load(path) as existing: + if set(existing.files) != set(arrays) or any( + not np.array_equal(existing[key], value) for key, value in arrays.items() + ): + raise ValueError(f"Diagnostic plan changed: {path}") + else: + atomic_numpy_save(path, **arrays) + + +def _sources(): + directory = Path(__file__).parent + names = ( + "bios_mechanism_causal_v2.py", + "bios_mechanism_causal.py", + "bios_mechanism_interventions.py", + "bios_causal_paths.py", + "bios_cross.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_path_diagnostics.py", + ) + sources = {name: file_sha256(directory / name) for name in names} + runner = directory.parents[1] / "scripts/analyze_bios_mechanism_causal_v2.py" + sources["runner"] = file_sha256(runner) + return sources + + +def validate_lock(lock): + if (lock.get("mechanism"), lock.get("layer"), lock.get("position")) != ("default_path", 0, 2): + raise ValueError("This runner only instantiates the locked default_path L0/pos2 candidate") + if lock.get("known_only") is not False or not lock.get("locked_at_utc"): + raise ValueError("An all-eligible, timestamped candidate lock is required") + + +def make_probe_plan(world, chain, recipients): + """Same people and fixed queries in every intervention, without knowledge filtering.""" + recipients = np.asarray(recipients, dtype=np.int64) + ids = [ + world.derived_ids[chain, recipients], + world.actual_ids[chain, recipients], + world.derived_ids[1 - chain, recipients], + ] + for relation in (3, 4, 5, 6): + candidates = np.flatnonzero(world.relation == relation) + by_person = np.full(len(world.actual_ids[chain]), -1, dtype=np.int64) + by_person[world.person[candidates]] = candidates + if (by_person[recipients] < 0).any(): + raise ValueError("An independent control query is missing") + ids.append(by_person[recipients]) + ids.extend([world.membership_ids[chain, recipients], world.actual_ids[1 - chain, recipients]]) + person_families = len(ids) + roots = world.root_ids[chain] + query_ids = np.concatenate([*ids, roots]) + return { + "query_id": query_ids, + "person": np.r_[np.tile(recipients, person_families), np.full(len(roots), -1)], + "family": np.r_[ + np.repeat(np.arange(person_families), len(recipients)), + np.full(len(roots), person_families), + ], + # -1 means not applicable; root facts are not ordinary people. + "recipient_old_exception": np.r_[ + np.tile(world.exceptions[chain, recipients].astype(np.int8), person_families), + np.full(len(roots), -1, dtype=np.int8), + ], + "answer": world.answers[query_ids], + } + + +def wrong_source_indices(families): + """Fixed one-person cyclic shift within each family, never chosen by answers.""" + families = np.asarray(families) + index = np.arange(len(families)) + for family in np.unique(families): + selected = np.flatnonzero(families == family) + if len(selected) < 2: + raise ValueError("Wrong-source controls require at least two queries per family") + index[selected] = np.roll(selected, 1) + return index + + +def make_transfer_plan(world, chain, per_population=64): + """Truth matching is restricted to this explicitly labeled offline diagnostic.""" + old = make_donor_plan(world, chain, per_population) + original = old["pair_type"] == 1 + recipients = old["recipient"][original] + train = world.person[world.train_ids[chain]] + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + rng = rng_for(world.seed, 978, chain) + donor_rows = [old["donor"][original]] + count_rows = [old["candidate_count"][original]] + for same_actual in (False, True): + donors, counts = [], [] + for recipient in recipients: + mask = (group[train] != group[recipient]) & (default[train] == default[recipient]) + if same_actual: + mask &= actual[train] == actual[recipient] + candidates = train[mask] + donors.append(rng.choice(candidates) if len(candidates) else -1) + counts.append(len(candidates)) + donor_rows.append(np.asarray(donors)) + count_rows.append(np.asarray(counts)) + donor = np.concatenate(donor_rows).astype(np.int64) + recipient = np.tile(recipients, len(TRANSFER_TYPES)) + safe = np.maximum(donor, 0) + return { + "case_id": np.arange(len(donor)), + "recipient": recipient, + "donor": donor, + "pair_type": np.repeat(np.arange(len(TRANSFER_TYPES)), len(recipients)), + "candidate_count": np.concatenate(count_rows), + "recipient_old_exception": world.exceptions[chain, recipient], + "same_actual": (actual[safe] == actual[recipient]) & (donor >= 0), + "same_default": (default[safe] == default[recipient]) & (donor >= 0), + "recipient_default": default[recipient], + "recipient_actual": actual[recipient], + "donor_default": np.where(donor >= 0, default[safe], -1), + "donor_actual": np.where(donor >= 0, actual[safe], -1), + } + + +def generate_queries( + model, prompts, lengths, device, batch_size=256, *, operations=None, capture_sites=() +): + """Two free generation passes with identical pre-answer operations, no answer input. + + operations(begin,end) returns (label, site, operation) triples. Every operation + returns its intended delta and availability; realized post-cast norms are + measured separately. Both passes are retained so norm matching is auditable. + """ + if len(prompts) == 0 or batch_size < 1: + raise ValueError("Generation needs nonempty queries and a positive batch size") + lengths = np.asarray(lengths) + if prompts.shape != (len(lengths), 5) or not np.isin(lengths, [4, 5]).all(): + raise ValueError("Unexpected symbolic query shape") + arrays = {"prediction": [], "ended": []} + for site in capture_sites: + query_site_roles(lengths, site.position) + arrays[f"state_{site.layer}_{site.position}"] = [] + calls = 0 + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + end = min(begin + batch_size, len(prompts)) + p = torch.as_tensor(prompts[begin:end], device=device) + n = torch.as_tensor(lengths[begin:end], device=device) + hooks, traces, captures = [], {}, {} + try: + for label, site, operation in () if operations is None else operations(begin, end): + query_site_roles(lengths[begin:end], site.position) + + def measured(value, operation=operation): + changed, trace = operation(value) + return changed, {**trace, "realized_delta": changed.float() - value.float()} + + hook, trace = attach_state_operation(model, site, measured) + hooks.append(hook) + traces[label] = trace + for site in capture_sites: + key = f"state_{site.layer}_{site.position}" + captures[key] = [] + + def capture( + _module, _inputs, output, key=key, position=site.position, captures=captures + ): + captures[key].append(output[:, position].detach().float()) + + hooks.append(model.blocks[site.layer].register_forward_hook(capture)) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + calls += 2 + arrays["prediction"].append(first.cpu().numpy()) + arrays["ended"].append(second.eq(EOS).cpu().numpy()) + for key, states in captures.items(): + arrays[key].append(states[0].cpu().numpy()) + drift = torch.linalg.vector_norm(states[1] - states[0], dim=-1) + arrays.setdefault(f"{key}_pass_drift", []).append(drift.cpu().numpy()) + for label, trace in traces.items(): + if len(trace) != 2: + raise ValueError( + "Every intervention must occur in both free-generation passes" + ) + for kind in ("delta", "realized_delta"): + norms = torch.stack( + [torch.linalg.vector_norm(t[kind].float(), dim=-1) for t in trace], + dim=1, + ) + arrays.setdefault(f"{label}_{kind}_norm", []).append(norms.cpu().numpy()) + valid = torch.stack([t["valid"] for t in trace], dim=1) + arrays.setdefault(f"{label}_valid", []).append(valid.cpu().numpy()) + finally: + for hook in hooks: + hook.remove() + result = {key: np.concatenate(value) for key, value in arrays.items()} + result.update( + forward_calls=np.asarray(calls), + forward_examples=np.asarray(2 * len(prompts)), + padded_token_positions=np.asarray(11 * len(prompts)), + logical_token_positions=np.asarray(int((2 * lengths + 1).sum())), + ) + return result + + +def _identity_trace(value): + return value, { + "delta": torch.zeros_like(value, dtype=torch.float32), + "valid": torch.ones(len(value), dtype=torch.bool, device=value.device), + } + + +def lesion_operations( + arm, source_bases, downstream_bases, clean_downstream, wrong_index, seed, device +): + """Return a deterministic batch factory. Wrong-source choice never sees truth.""" + if arm not in ARMS: + raise ValueError("Unknown necessity/restoration arm") + if arm == "clean": + return lambda _begin, _end: [] + if arm == "sham": + return lambda _begin, _end: [("source", SOURCE, _identity_trace)] + source = {key: basis.tensors(device) for key, basis in source_bases.items()} + downstream = ( + None + if downstream_bases is None + else {key: basis.tensors(device) for key, basis in downstream_bases.items()} + ) + needs_downstream = "rescue" in arm + if needs_downstream and downstream is None: + raise ValueError("Downstream basis is unavailable; recovery cannot be estimated") + wrong_index = np.asarray(wrong_index) + if len(wrong_index) != len(clean_downstream): + raise ValueError("Wrong-source plan length mismatch") + coefficients = ( + np.random.default_rng(seed) + .standard_normal((len(clean_downstream), source_bases["random"].rank)) + .astype(np.float32) + ) + + def factory(begin, end): + ops = [] + if arm == "clean": + return ops + if arm == "sham": + return [("source", SOURCE, _identity_trace)] + if arm != "rescue_only": + kind = ( + arm.removesuffix("_remove") + if arm in ("random_remove", "complement_remove") + else "target" + ) + q, mean, _ = source[kind] + tq, tm, _ = source["target"] + + def remove(value): + reference = ( + None + if kind == "target" + else torch.linalg.vector_norm(projection_component(value, tq, tm), dim=-1) + ) + return remove_projection(value, q, mean, reference) + + ops.append(("source", SOURCE, remove)) + if needs_downstream: + clean = torch.as_tensor(clean_downstream[begin:end], device=device) + wrong = torch.as_tensor(clean_downstream[wrong_index[begin:end]], device=device) + tq = downstream["target"][0] + rq = downstream["random"][0] + noise = torch.as_tensor(coefficients[begin:end], device=device) @ rq.T + + def recover(value): + _, same_query_trace = restore_projection(value, clean, tq) + correct_delta = same_query_trace["delta"] + reference = torch.linalg.vector_norm(correct_delta, dim=-1) + if arm == "remove_wrong_source_rescue": + return restore_projection(value, wrong, tq, reference) + if arm == "remove_random_rescue": + delta, valid = match_delta_norm(noise, reference) + return value + delta.to(value.dtype), {"delta": delta, "valid": valid} + return restore_projection(value, clean, tq) + + ops.append(("downstream", DOWNSTREAM, recover)) + return ops + + return factory + + +def transfer_operations(arm, bases, recipient, donor, seed, device): + """A locked-basis manipulation check, never a basis-fitting input.""" + if arm not in TRANSFER_ARMS or recipient.shape != donor.shape: + raise ValueError("Invalid donor manipulation") + if arm.startswith("projected_") and bases is None: + raise ValueError("Projected donor diagnostic requires an available source basis") + full_delta = donor.astype(np.float32) - recipient.astype(np.float32) + if arm == "sham": + delta, valid = np.zeros_like(full_delta), np.ones(len(donor), dtype=bool) + elif arm == "full_donor": + delta, valid = full_delta, np.ones(len(donor), dtype=bool) + else: + if arm == "full_norm_random": + raw = np.random.default_rng(seed).standard_normal(full_delta.shape).astype(np.float32) + reference = np.linalg.norm(full_delta, axis=-1) + else: + tq = bases["target"].q + target_delta = (full_delta @ tq) @ tq.T + reference = np.linalg.norm(target_delta, axis=-1) + q = bases[arm.removeprefix("projected_")].q + raw = (full_delta @ q) @ q.T + matched, available = match_delta_norm(torch.from_numpy(raw), torch.from_numpy(reference)) + delta, valid = matched.numpy(), available.numpy() + + def factory(begin, end): + change = torch.as_tensor(delta[begin:end], device=device) + available = torch.as_tensor(valid[begin:end], device=device) + + def operation(value): + return value + change.to(value.dtype), {"delta": change, "valid": available} + + return [("source", SOURCE, operation)] + + return factory + + +def _availability(arrays): + valid = np.ones(len(arrays["prediction"]), dtype=bool) + for key, value in arrays.items(): + if key.endswith("_valid"): + valid &= value.all(axis=1) + return valid + + +def score_rows(arrays, baseline, plan, arm, labels=FAMILIES, label_key="family"): + """All eligible rows first; original-correct strata remain descriptive only.""" + base_correct = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + correct = (arrays["prediction"] == plan["answer"]) & arrays["ended"] + available = _availability(arrays) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available + n, nb = int(chosen.sum()), int((chosen & base_correct).sum()) + before, after = int((chosen & base_correct).sum()), int((chosen & correct).sum()) + row = { + "arm": arm, + "family": family, + "population": population, + "requested": int(requested.sum()), + "available": n, + "unavailable": int((requested & ~available).sum()), + "baseline_correct": before, + "correct": after, + "accuracy": after / n if n else None, + "delta_accuracy": (after - before) / n if n else None, + "known_became_wrong": int((chosen & base_correct & ~correct).sum()), + "wrong_became_correct": int((chosen & ~base_correct & correct).sum()), + "known_denominator": nb, + "known_retention": int((chosen & base_correct & correct).sum()) / nb + if nb + else None, + "termination_error": int((chosen & ~arrays["ended"]).sum()), + "prediction_changed": int( + ( + chosen + & ( + (arrays["prediction"] != baseline["prediction"]) + | (arrays["ended"] != baseline["ended"]) + ) + ).sum() + ), + } + for label in ("source", "downstream"): + for kind in ("delta", "realized_delta"): + key = f"{label}_{kind}_norm" + row[f"mean_{key}"] = ( + float(arrays[key][chosen, 0].mean()) if n and key in arrays else None + ) + rows.append(row) + return rows + + +def paired_score_rows( + left, right, baseline, plan, left_name, right_name, labels=FAMILIES, label_key="family" +): + """Contrasts use a common availability mask, never unmatched denominators.""" + correct_left = (left["prediction"] == plan["answer"]) & left["ended"] + correct_right = (right["prediction"] == plan["answer"]) & right["ended"] + correct_clean = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + available_left, available_right = _availability(left), _availability(right) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available_left & available_right + n = int(chosen.sum()) + nl, nr = int((chosen & correct_left).sum()), int((chosen & correct_right).sum()) + known_right_wrong = chosen & correct_clean & ~correct_right + denominator = int(known_right_wrong.sum()) + rows.append( + { + "left": left_name, + "right": right_name, + "family": family, + "population": population, + "requested": int(requested.sum()), + "common_available": n, + "left_unavailable": int((requested & ~available_left).sum()), + "right_unavailable": int((requested & ~available_right).sum()), + "left_correct": nl, + "right_correct": nr, + "accuracy_difference": (nl - nr) / n if n else None, + "right_wrong_left_correct": int((chosen & ~correct_right & correct_left).sum()), + "right_correct_left_wrong": int((chosen & correct_right & ~correct_left).sum()), + "original_known_right_wrong": denominator, + "original_known_right_wrong_left_recovered": int( + (known_right_wrong & correct_left).sum() + ), + "conditional_recovery_auxiliary": int((known_right_wrong & correct_left).sum()) + / denominator + if denominator + else None, + } + ) + return rows + + +def _check_predictions(generated, archived, ids): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], archived[key][ids]): + raise ValueError(f"Clean frozen-model generation differs from archive: {key}") + + +def record_archive_comparison(path, generated, archived, ids): + """Archive differences are audited, never used for calibration or row selection.""" + ids = np.asarray(ids) + if generated["prediction"].shape != ids.shape or generated["ended"].shape != ids.shape: + raise ValueError("Local generation shape differs from its declared query plan") + if generated["ended"].dtype != bool or archived["ended"].dtype != bool: + raise ValueError("Archive and local termination masks must be boolean") + _same_arrays( + path, + { + "query_id": ids, + "local_prediction": generated["prediction"], + "local_ended": generated["ended"], + "archive_prediction": archived["prediction"][ids], + "archive_ended": archived["ended"][ids], + "prediction_changed": generated["prediction"] != archived["prediction"][ids], + "ended_changed": generated["ended"] != archived["ended"][ids], + }, + ) + + +def verify_original_replay(model, world, archived, output, device): + """Strong identity/numerical gate; original query order and batch remain exact.""" + ids = np.arange(len(world.answers)) + replay = _cached_generate(output / "original-replay.npz", model, world, ids, device, 512) + _check_predictions(replay, archived, ids) + _freeze_json( + output / "original-replay.json", + { + "status": "exact_archive_value_and_EOS_replay", + "queries": len(ids), + "batch_size": 512, + "prediction_differences": 0, + "ended_differences": 0, + "extra_identity_gate_cost": _cost(replay), + "raw_sha256": file_sha256(output / "original-replay.npz"), + }, + ) + return replay + + +def _cost(arrays): + return { + key: int(arrays[key]) + for key in ( + "forward_calls", + "forward_examples", + "padded_token_positions", + "logical_token_positions", + ) + } + + +def _cached_generate(path, model, world, ids, device, batch_size, **kwargs): + if path.exists(): + with np.load(path) as stored: + result = dict(stored) + if not np.array_equal(result.pop("query_id"), ids): + raise ValueError("Cached generation query plan differs") + return result + result = generate_queries( + model, world.prompts[ids], world.lengths[ids], device, batch_size, **kwargs + ) + atomic_numpy_save(path, query_id=ids, **result) + return result + + +def _fit_chain(model, world, chain, pair, dest, device, batch_size, archived): + plan = calibration_plan( + world.actual_ids[chain], + world.person, + world.membership_ids[chain], + pair["E"], + pair["replay"], + ) + _same_arrays( + dest / "calibration-plan.npz", {key: np.asarray(value) for key, value in plan.items()} + ) + actual = _cached_generate( + dest / "calibration-actual.npz", + model, + world, + plan["actual_query_ids"], + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + membership = _cached_generate( + dest / "calibration-membership.npz", + model, + world, + plan["membership_query_ids"], + device, + batch_size, + ) + record_archive_comparison( + dest / "archive-calibration-actual.npz", actual, archived, plan["actual_query_ids"] + ) + record_archive_comparison( + dest / "archive-calibration-membership.npz", + membership, + archived, + plan["membership_query_ids"], + ) + prefix = f"{CHAINS[chain]}:" + allowed = np.array( + [i for i, label in enumerate(world.token_labels) if label.startswith(prefix)] + ) + groups, valid = valid_predicted_groups(membership["prediction"], membership["ended"], allowed) + _same_arrays(dest / "self-predicted-groups.npz", {"prediction": groups, "valid": valid}) + bases, reports, basis_arrays = {}, {}, {} + for label, site in (("source", SOURCE), ("downstream", DOWNSTREAM)): + basis, report = fit_predicted_group_bases( + actual[f"state_{site.layer}_{site.position}"], groups, valid, rank=RANK, seed=74 + chain + ) + bases[label], reports[label] = basis, report + if basis is not None: + for kind, value in basis.items(): + for field in ("q", "mean", "scale"): + basis_arrays[f"{label}_{kind}_{field}"] = getattr(value, field) + _same_arrays(dest / "bases.npz", basis_arrays) + information = { + "S_count": len(pair["E"]), + "R_count": len(pair["replay"]), + "actual_queries": len(plan["actual_query_ids"]), + "additional_membership_queries": len(plan["membership_query_ids"]), + "derived_calibration_queries": 0, + "true_memberships_supplied": False, + "membership_syntax_rule": prefix, + "invalid_groups_never_replaced": True, + "calibration_cost": {"actual": _cost(actual), "membership": _cost(membership)}, + "basis_reports": reports, + "variant": "group_means", + "basis_sha256": file_sha256(dest / "bases.npz"), + } + _freeze_json(dest / "calibration.json", information) + # Truth is read only after Q and its information contract are frozen. These + # labels score calibration quality; they never select rows or alter Q. + membership_correct = ( + membership["prediction"] == world.answers[plan["membership_query_ids"]] + ) & membership["ended"] + _freeze_json( + dest / "calibration-diagnostics.json", + { + "role": "offline scoring after frozen Q; never fitting or row selection", + "queries": len(groups), + "valid_predictions": int(valid.sum()), + "valid_rate": float(valid.mean()), + "correct_predictions": int(membership_correct.sum()), + "accuracy": float(membership_correct.mean()), + "accuracy_given_valid_auxiliary": float(membership_correct[valid].mean()) + if valid.any() + else None, + "basis_sha256": information["basis_sha256"], + }, + ) + return bases + + +def run_chain(model, world, chain, pair, dest, device, batch_size, per_population, archived): + dest.mkdir(parents=True, exist_ok=True) + bases = _fit_chain(model, world, chain, pair, dest, device, batch_size, archived) + transfer = make_transfer_plan(world, chain, per_population) + _same_arrays(dest / "transfer-plan.npz", transfer) + recipients = transfer["recipient"][transfer["pair_type"] == 0] + plan = make_probe_plan(world, chain, recipients) + plan["wrong_source_index"] = wrong_source_indices(plan["family"]) + plan["wrong_source_query_id"] = plan["query_id"][plan["wrong_source_index"]] + plan["wrong_source_same_answer"] = plan["answer"] == plan["answer"][plan["wrong_source_index"]] + _same_arrays(dest / "probe-plan.npz", plan) + ids = plan["query_id"] + query_site_roles(world.lengths[ids], SOURCE.position) + if downstream_routing_site(SOURCE, len(model.blocks), world.lengths[ids] - 1) != DOWNSTREAM: + raise ValueError("Candidate/downstream site mismatch") + clean = _cached_generate( + dest / "clean.npz", + model, + world, + ids, + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + record_archive_comparison(dest / "archive-probe-clean.npz", clean, archived, ids) + rows, states, costs, arm_arrays = [], {}, {"clean": _cost(clean)}, {} + clean_down = clean[f"state_{DOWNSTREAM.layer}_{DOWNSTREAM.position}"] + for arm in ARMS: + if arm not in ("clean", "sham") and bases["source"] is None: + states[arm] = "unavailable_source_rank" + continue + if "rescue" in arm and bases["downstream"] is None: + states[arm] = "unavailable_downstream_rank" + continue + if arm == "clean": + generated = clean + else: + operations = lesion_operations( + arm, + bases["source"], + bases["downstream"], + clean_down, + plan["wrong_source_index"], + [world.seed, 979, chain], + device, + ) + generated = _cached_generate( + dest / f"{arm}.npz", model, world, ids, device, batch_size, operations=operations + ) + if arm in ("sham", "rescue_only"): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], clean[key]): + raise ValueError(f"No-lesion control changed output: {arm}/{key}") + rows.extend(score_rows(generated, clean, plan, arm)) + costs[arm], states[arm] = _cost(generated), "complete" + arm_arrays[arm] = generated + comparisons = [ + (arm, "clean") + for arm in ("sham", "target_remove", "random_remove", "complement_remove", "rescue_only") + ] + comparisons += [("target_remove", arm) for arm in ("random_remove", "complement_remove")] + comparisons += [ + (arm, "target_remove") + for arm in ("remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue") + ] + comparisons += [ + ("remove_rescue", arm) for arm in ("remove_wrong_source_rescue", "remove_random_rescue") + ] + paired_rows = [] + for left, right in comparisons: + if left in arm_arrays and right in arm_arrays: + paired_rows.extend( + paired_score_rows(arm_arrays[left], arm_arrays[right], clean, plan, left, right) + ) + # Donor activations are read only after both bases and their provenance are frozen. + valid = transfer["donor"] >= 0 + selected = {key: value[valid] for key, value in transfer.items()} + people = np.unique(np.r_[selected["recipient"], selected["donor"]]) + donor_ids = world.derived_ids[chain, people] + donor_clean = _cached_generate( + dest / "transfer-clean.npz", + model, + world, + donor_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + record_archive_comparison(dest / "archive-transfer-cache.npz", donor_clean, archived, donor_ids) + ri, di = ( + np.searchsorted(people, selected["recipient"]), + np.searchsorted(people, selected["donor"]), + ) + source_state = donor_clean[f"state_{SOURCE.layer}_{SOURCE.position}"] + # v2: the causal baseline has exactly the intervention query order and batch shape. + # The donor/recipient source cache and intervention delta definitions stay unchanged. + local_ids = world.derived_ids[chain, selected["recipient"]] + transfer_local = _cached_generate( + dest / "transfer-local-clean.npz", + model, + world, + local_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + record_archive_comparison( + dest / "archive-transfer-local-clean.npz", transfer_local, archived, local_ids + ) + _same_arrays( + dest / "transfer-reference-drift.npz", + { + "query_id": local_ids, + "cache_vs_local_state_norm": np.linalg.norm( + source_state[ri] - transfer_local["state_0_2"], axis=1 + ), + "cache_prediction": donor_clean["prediction"][ri], + "cache_ended": donor_clean["ended"][ri], + "local_prediction": transfer_local["prediction"], + "local_ended": transfer_local["ended"], + }, + ) + donor_baseline = {key: transfer_local[key] for key in ("prediction", "ended")} + donor_plan = {**selected, "answer": selected["recipient_default"]} + transfer_rows, transfer_status = [], {} + costs["transfer_clean"] = _cost(donor_clean) + costs["transfer_local_clean"] = _cost(transfer_local) + for arm in TRANSFER_ARMS: + if arm.startswith("projected_") and bases["source"] is None: + transfer_status[arm] = "unavailable_source_rank" + continue + ops = transfer_operations( + arm, + bases["source"], + source_state[ri], + source_state[di], + [world.seed, 980, chain], + device, + ) + generated = _cached_generate( + dest / f"transfer-{arm}.npz", + model, + world, + world.derived_ids[chain, selected["recipient"]], + device, + batch_size, + operations=ops, + ) + if arm == "sham": + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], donor_baseline[key]): + raise ValueError("Transfer sham changed output") + scored = score_rows( + generated, donor_baseline, donor_plan, arm, labels=TRANSFER_TYPES, label_key="pair_type" + ) + for row in scored: + code = TRANSFER_TYPES.index(row["family"]) + chosen = (selected["pair_type"] == code) & _availability(generated) + requested = transfer["pair_type"] == code + if row["population"] != "all": + exception = row["population"] == "old_exception" + chosen &= selected["recipient_old_exception"] == exception + requested &= transfer["recipient_old_exception"] == exception + row["plan_requested"] = int(requested.sum()) + row["missing_donors"] = int((requested & ~valid).sum()) + for role in ("recipient_actual", "donor_default", "donor_actual"): + matched = (generated["prediction"] == selected[role]) & generated["ended"] + base_matched = (donor_baseline["prediction"] == selected[role]) & donor_baseline[ + "ended" + ] + row[f"matches_{role}"] = int((chosen & matched).sum()) + row[f"baseline_matches_{role}"] = int((chosen & base_matched).sum()) + # Donor's own clean response is descriptive, not an eligibility filter. + row["donor_answered_default"] = int( + ( + chosen + & donor_clean["ended"][di] + & (donor_clean["prediction"][di] == selected["donor_default"]) + ).sum() + ) + transfer_rows.extend(scored) + transfer_status[arm], costs[f"transfer_{arm}"] = "complete", _cost(generated) + for filename, contents in ( + ("necessity.csv", rows), + ("paired-necessity.csv", paired_rows), + ("transfer.csv", transfer_rows), + ): + with (dest / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + dest / "status.json", + { + "arms": states, + "transfer_arms": transfer_status, + "evaluation_cost": costs, + "information_boundary": "truth-matched donor states are diagnostic only", + }, + ) + archive_rows = {} + for path in sorted(dest.glob("archive-*.npz")): + with np.load(path) as comparison: + archive_rows[path.stem] = { + "queries": len(comparison["query_id"]), + "prediction_differences": int(comparison["prediction_changed"].sum()), + "ended_differences": int(comparison["ended_changed"].sum()), + "case_exclusion": False, + } + write_json(dest / "archive-discrepancies.json", archive_rows) + return {"chain": CHAINS[chain], "arms": states, "transfer_arms": transfer_status} + + +def scientific_outputs(output): + """Seal only producer-owned artifacts, excluding mutable queue logs and locks.""" + names = { + "archive-calibration-actual.npz", + "archive-calibration-membership.npz", + "archive-probe-clean.npz", + "archive-transfer-cache.npz", + "archive-transfer-local-clean.npz", + "archive-discrepancies.json", + "transfer-local-clean.npz", + "transfer-reference-drift.npz", + "calibration-plan.npz", + "calibration-actual.npz", + "calibration-membership.npz", + "self-predicted-groups.npz", + "bases.npz", + "calibration.json", + "calibration-diagnostics.json", + "transfer-plan.npz", + "probe-plan.npz", + "transfer-clean.npz", + "necessity.csv", + "paired-necessity.csv", + "transfer.csv", + "status.json", + } + names.update(f"{arm}.npz" for arm in ARMS) + names.update(f"transfer-{arm}.npz" for arm in TRANSFER_ARMS) + paths = [ + output / "contract.json", + output / "original-replay.npz", + output / "original-replay.json", + ] + for chain in CHAINS: + paths.extend( + output / chain / name for name in sorted(names) if (output / chain / name).exists() + ) + return {str(path.relative_to(output)): file_sha256(path) for path in paths} + + +def run_model(run, output, lock_path, *, device="cuda", batch_size=256, per_population=64): + """One original pre-edit checkpoint, both chains; separate outputs, restartable nodes.""" + run, output, lock_path = Path(run).resolve(), Path(output).resolve(), Path(lock_path).resolve() + if output == run or run in output.parents: + raise ValueError("Never write diagnostics inside the frozen parent") + lock = json.loads(lock_path.read_text()) + validate_lock(lock) + config = json.loads((run / "config.json").read_text()) + if ( + config["world"] not in (0, 1) + or config["model"]["width"] not in (256, 768) + or config["seed"] not in (0, 1) + or config["condition"] not in (*CHAINS, "neither") + ): + raise ValueError("The original 24-model development matrix is required") + step = config["study"]["steps"] + if step != 15360 or per_population != 64: + raise ValueError("The parent step and 64+64 recipient budget are fixed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent runtime differs: {key}") + device = torch.device(device) + weights = run / f"model-{step}.pt" + contract = { + "numerical_policy": NUMERICAL_POLICY, + "run": str(run), + "step": step, + "world": config["world"], + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "parent_config_sha256": file_sha256(run / "config.json"), + "parent_weights_sha256": file_sha256(weights), + "lock": lock, + "lock_sha256": file_sha256(lock_path), + "sources": _sources(), + "source_site": [0, 2], + "downstream_site": [1, 2], + "rank": RANK, + "per_population": per_population, + "batch_size": batch_size, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": device.type, + "checkpoint_role": "pre_edit_clean_only", + "calibration": "S_union_R_actual_queries_with_self_predicted_membership_groups", + "families": list(FAMILIES), + "arms": list(ARMS), + "transfer_types": list(TRANSFER_TYPES), + "transfer_arms": list(TRANSFER_ARMS), + "wrong_source_rule": "cyclic_previous_query_within_family_no_truth_or_prediction_selection", + "cross_query_reference": "The actual-calibration mean is reused for all query families", + "recovery_source": "Same checkpoint and same query clean post-L1/pos2 target projection", + "rescue_only_role": "No-lesion downstream sham; cannot establish necessity", + "random_recovery": "Random rank32 downstream basis; same-query recovery delta norm", + "rank_failure": "Unavailable, never padded or replaced; report coverage by organization", + "interpretation": ( + "Artificial-lesion behavior recovery; no claim of edit repair " + "or organizational specificity" + ), + } + output.mkdir(parents=True, exist_ok=True) + _freeze_json(output / "contract.json", contract) + complete_path = output / "complete.json" + if complete_path.exists(): + complete = json.loads(complete_path.read_text()) + for name, digest in complete["outputs"].items(): + if file_sha256(output / name) != digest: + raise ValueError(f"Completed diagnostic artifact changed: {name}") + return complete + repository = Path(__file__).resolve().parents[2] + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent generated world changed") + saved = torch.load(weights, map_location="cpu", weights_only=False) + final = json.loads((run / "learning-complete.json").read_text()) + if ( + saved["config"] != config["model"] + or saved["step"] != step + or state_hash(saved["model"]) != final["model_sha256"] + ): + raise ValueError("Parent model identity mismatch") + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + with np.load(run / f"predictions-{step}.npz") as stored: + archived = {key: stored[key] for key in ("prediction", "ended")} + verify_original_replay(model, world, archived, output, device) + completed = [] + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + reference = run / "edits" / f"{name}-exception-mlp" + with np.load(reference / "sets.npz") as old: + for key in ("E", "replay", "exception"): + if not np.array_equal(old[key], pair[key]): + raise ValueError( + f"Original exception calibration permission changed: {name}/{key}" + ) + if not (reference / "complete.json").exists(): + raise ValueError("Original exception case is incomplete") + completed.append( + run_chain( + model, + world, + chain, + pair, + output / name, + device, + batch_size, + per_population, + archived, + ) + ) + print( + json.dumps({"event": "necessity_chain_complete", "run": str(run), "chain": name}), + flush=True, + ) + if _sources() != contract["sources"]: + raise ValueError("Diagnostic implementation changed during execution") + outputs = scientific_outputs(output) + complete = {"status": "complete", "chains": completed, "outputs": outputs} + write_json(complete_path, complete) + return complete diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_mechanism_edit.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_mechanism_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..6e51c693528d73250f62b70686f96b42b7eb9e4f --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_mechanism_edit.py @@ -0,0 +1,611 @@ +"""P1 counterfactual edits with frozen parent models and exact restart state. + +The supervised pool S is fixed at 93 facts. E_changed, propagation D, and +unchanged U are recomputed from each arm's truth, independently of that pool. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_cross_train import evaluate, tensor_queries +from .bios_cross_train import source_hashes as parent_source_hashes +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +ARMS = ("old-fact-rehearsal", "root-only", "actual-only", "class-balanced-exception") +OPTIONAL_ARM = "all-freeze-embedding" +REFERENCE_ARMS = ("coherent", "exception") +DEFAULT_STUDY = { + "protocol": "v2.8-development-mechanism-P1", + "widths": [256, 768], + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "arms": list(ARMS), + "edit_steps": 512, + "edit_checkpoints": [0, 32, 128, 512], + "edit_lr": 3e-5, + "retention_kl": 1.0, + "batch_size": 128, + "save_every": 32, + "gradient_steps": [0, 31, 127, 511], +} + + +def load_study(path=None, arms=None): + study = json.loads(json.dumps(DEFAULT_STUDY)) + if path: + supplied = json.loads(Path(path).read_text()) + unknown = set(supplied) - set(study) + if unknown: + raise ValueError(f"Unknown P1 configuration keys: {sorted(unknown)}") + study.update(supplied) + if arms is not None: + study["arms"] = list(arms) + if not study["arms"] or len(set(study["arms"])) != len(study["arms"]): + raise ValueError("At least one unique arm is required") + if set(study["arms"]) - set((*ARMS, OPTIONAL_ARM)): + raise ValueError("Unknown P1 arm") + if study["edit_steps"] < 1 or study["batch_size"] != 128 or study["save_every"] < 1: + raise ValueError("Positive budgets and the original batch size 128 are required") + checkpoints = study["edit_checkpoints"] + if not checkpoints or checkpoints != sorted(set(checkpoints)) or checkpoints[0] != 0: + raise ValueError("Checkpoints must be unique, ordered, and include zero") + if checkpoints[-1] != study["edit_steps"]: + raise ValueError("The final checkpoint must equal the fixed edit budget") + if study["edit_lr"] <= 0 or study["retention_kl"] < 0: + raise ValueError("Invalid optimization settings") + for key in ("widths", "worlds", "seeds", "conditions"): + if not study[key] or len(set(study[key])) != len(study[key]): + raise ValueError(f"Nonempty, unique matrix entries required: {key}") + if set(study["conditions"]) - set(CONDITIONS): + raise ValueError("Unknown organization condition") + return study + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def source_hashes(): + result = parent_source_hashes() + result[Path(__file__).name] = file_hash(__file__) + runner = Path(__file__).resolve().parents[2] / "scripts/run_bios_mechanism_edit.py" + result[runner.name] = file_hash(runner) + return result + + +def sampling_streams(world, chain, steps=512, batch_size=128): + """Match the original generator, including the order of its two draws.""" + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + supervised = rng.integers(len(pair["E"]), size=(steps, batch_size)) + replay = rng.integers(len(pair["replay"]), size=(steps, batch_size)) + return supervised, replay + + +def make_arm(world, chain, arm, pair=None): + if arm not in (*ARMS, OPTIONAL_ARM, *REFERENCE_ARMS): + raise ValueError(f"Unknown arm: {arm}") + pair = edit_pair(world, chain) if pair is None else pair + supervised = pair["E"].copy() + root = np.intersect1d(supervised, world.root_ids[chain]) + actual = np.intersect1d(supervised, world.actual_ids[chain]) + assert (len(supervised), len(root), len(actual)) == (93, 3, 90) + target = world.answers.copy() + if arm == "root-only": + target[root] = pair["exception"][root] + elif arm == "actual-only": + target[actual] = pair["exception"][actual] + elif arm in ("exception", "class-balanced-exception", OPTIONAL_ARM): + target[supervised] = pair["exception"][supervised] + elif arm == "coherent": + target[supervised] = pair["coherent"][supervised] + # Recompute derived truth, rather than copying the original D declaration. + for task in range(2): + target[world.derived_ids[task]] = target[world.root_ids[task, world.memberships[task]]] + changed = target != world.answers + e = np.flatnonzero(changed & (world.relation < 10)) + d = np.flatnonzero(changed & (world.relation >= 10)) + u = np.flatnonzero(~changed) + if not np.isin(e, supervised).all() or not np.array_equal( + target[pair["replay"]], world.answers[pair["replay"]] + ): + raise ValueError("Supervision or common retention pool violates the truth contract") + if np.intersect1d(pair["replay"], supervised).size: + raise ValueError("The replay pool overlaps S") + selected_people = np.isin(world.memberships[chain], pair["groups"]) + selected_facts = (world.person >= 0) & selected_people[np.maximum(world.person, 0)] + old_exceptions = np.zeros(len(world.answers), dtype=bool) + old_exceptions[world.actual_ids[chain, selected_people & world.exceptions[chain]]] = True + relevant = np.isin(world.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(world.answers), -1, dtype=np.int64) + strata[~changed & old_exceptions] = 0 + strata[~changed & selected_facts & ~old_exceptions] = 1 + strata[~changed & ~selected_facts & relevant] = 2 + strata[~changed & ~selected_facts & ~relevant] = 3 + assert np.array_equal(strata >= 0, ~changed) + supervised_unchanged = np.intersect1d(supervised, u) + probe_unchanged = np.intersect1d(pair["D"], u) + supplied = np.union1d(supervised, pair["replay"]) + # Keep the archived heldout pool; add newly unchanged D, which is never trained. + heldout = np.setdiff1d( + np.intersect1d(np.union1d(pair["heldout"], probe_unchanged), u), supplied + ) + weights = np.ones(len(supervised), dtype=np.float64) + root_mask = np.isin(supervised, root) + if arm == "class-balanced-exception": + weights[root_mask] = len(supervised) / (2 * len(root)) + weights[~root_mask] = len(supervised) / (2 * len(actual)) + return { + "target": target, + "S": supervised, + "S_root": root, + "S_actual": actual, + "S_root_mask": root_mask, + "S_weights": weights, + "E_changed": e, + "E_changed_root": np.intersect1d(e, root), + "E_changed_actual": np.intersect1d(e, actual), + "D": d, + "D_conflict": np.intersect1d(d, pair["conflict_D"]), + "D_probe": pair["D"], + "D_probe_conflict": pair["conflict_D"], + "D_probe_unchanged": probe_unchanged, + "U": u, + "strata": strata, + "heldout": heldout, + "unseen": np.setdiff1d(u, supplied), + "S_unchanged": supervised_unchanged, + "replay": pair["replay"], + "other_chain": np.flatnonzero( + ~changed & np.isin(world.relation, [7, 8, 9, 11] if chain == 0 else [0, 1, 2, 10]) + ), + "independent": np.flatnonzero(~changed & np.isin(world.relation, [3, 4, 5, 6])), + "groups": pair["groups"], + } + + +def accuracy(correct, ids): + return { + "n": len(ids), + "correct": int(correct[ids].sum()), + "accuracy": float(correct[ids].mean()) if len(ids) else None, + } + + +def retention(correct, old_correct, ids): + known = ids[old_correct[ids]] + broken = int((~correct[known]).sum()) + return { + "n": len(ids), + "known": len(known), + "unknown": len(ids) - len(known), + "broken": broken, + "rate": broken / len(known) if len(known) else None, + } + + +def arm_metrics(world, spec, arrays, old_correct): + correct = arrays["correct"] + result = { + name: accuracy(correct, spec[name]) + for name in ( + "S", + "S_root", + "S_actual", + "E_changed", + "E_changed_root", + "E_changed_actual", + "D", + "D_conflict", + "D_probe", + ) + } + for name in ("D", "D_conflict", "D_probe", "D_probe_conflict"): + for split, pool in (("trained", world.train_ids), ("heldout", world.heldout_ids)): + result[f"{name}_{split}"] = accuracy(correct, np.intersect1d(spec[name], pool)) + for name, pool in ( + ("full", spec["U"]), + ("heldout", spec["heldout"]), + ("unseen", spec["unseen"]), + ): + result[f"U_{name}"] = retention(correct, old_correct, pool) + result[f"U_{name}_strata"] = { + str(group): retention( + correct, old_correct, np.intersect1d(pool, np.flatnonzero(spec["strata"] == group)) + ) + for group in range(4) + } + for name in ("S_unchanged", "D_probe_unchanged", "replay", "other_chain", "independent"): + result[f"U_{name}"] = retention(correct, old_correct, spec[name]) + return result + + +def weighted_supervision(logits, labels, weights): + """Average over sampled examples, never renormalize observed class mass.""" + losses = F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), reduction="none") + per_example = losses.reshape(len(labels), -1).mean(-1) + return (per_example * weights).mean(), per_example + + +def select_edit_parameters(model, arm): + if arm != OPTIONAL_ARM: + return select_parameters(model, "mlp", 3) + selected = select_parameters(model, "all") + model.token.weight.requires_grad_(False) + return [parameter for parameter in selected if parameter.requires_grad] + + +def _gradient_norm(loss, selected): + gradients = torch.autograd.grad(loss, selected, retain_graph=True, allow_unused=True) + total = sum(g.detach().float().square().sum() for g in gradients if g is not None) + return float(torch.sqrt(total)) if isinstance(total, torch.Tensor) else 0.0 + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen contract mismatch: {path}") + else: + write_json(path, value) + + +def _contract_hash(contract): + return hashlib.sha256(json.dumps(contract, sort_keys=True).encode()).hexdigest() + + +def _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device): + return { + "model": model.state_dict(), + "config": model.config_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "contract_sha256": _contract_hash(contract), + "timeline": timeline, + "update_stats": stats, + "seconds": seconds, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + } + + +def run_case(model, baseline_state, world, data, old_arrays, chain, arm, dest, study, parent): + """Run or resume one fixed-budget case; no evaluation result changes training.""" + dest = Path(dest) + dest.mkdir(parents=True, exist_ok=True) + device = data["tokens"].device + spec = make_arm(world, chain, arm) + e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"], study["batch_size"]) + contract = { + "parent": parent, + "study": study, + "chain": CHAINS[chain], + "arm": arm, + "sources": source_hashes(), + "sets_sha256": {key: array_hash(value) for key, value in spec.items()}, + "edit_sampling_sha256": array_hash(e_choices), + "replay_sampling_sha256": array_hash(r_choices), + "old_correct_sha256": array_hash(old_arrays["correct"]), + } + _freeze_json(dest / "contract.json", contract) + if (dest / "complete.json").exists(): + completed = json.loads((dest / "complete.json").read_text()) + if completed["contract_sha256"] != _contract_hash(contract): + raise ValueError("Completion contract mismatch") + return completed + model.load_state_dict(baseline_state) + selected = select_edit_parameters(model, arm) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(spec["replay"]), 256): + ids = torch.as_tensor(spec["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + new_data = tensor_queries(world, device, spec["target"]) + atomic_numpy_save( + dest / "sets.npz", + **spec, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, stats, seconds = 0, [], [], 0.0 + resume_path = dest / "resume.pt" + if resume_path.exists(): + state = torch.load(resume_path, map_location="cpu", weights_only=False) + if state["contract_sha256"] != _contract_hash(contract): + raise ValueError("Resume contract mismatch") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + first, timeline, stats, seconds = ( + state["step"], + state["timeline"], + state["update_stats"], + state["seconds"], + ) + if len(stats) != first or first > study["edit_steps"]: + raise ValueError("Invalid restart progress") + torch.set_rng_state(state["torch_rng"]) + if device.type == "cuda": + torch.cuda.set_rng_state(state["cuda_rng"], device) + weights = torch.as_tensor(spec["S_weights"], device=device, dtype=torch.float32) + root_mask = torch.as_tensor(spec["S_root_mask"], device=device) + for step in range(first, study["edit_steps"] + 1): + if step in study["edit_checkpoints"] and not any(p["step"] == step for p in timeline): + arrays = evaluate(model, data, spec["target"]) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + timeline.append( + { + "step": step, + **arm_metrics(world, spec, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + ) + write_json(dest / "trajectory.json", timeline) + if step % study["save_every"] == 0 or step in study["edit_checkpoints"]: + atomic_torch_save( + _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device), + resume_path, + ) + write_json(dest / "update-stats.json", stats) + if step == study["edit_steps"]: + break + model.train() + optimizer.zero_grad(set_to_none=True) + choices = torch.as_tensor(e_choices[step], device=device) + ei = torch.as_tensor(spec["S"][e_choices[step]], device=device) + replay_choices = torch.as_tensor(r_choices[step], device=device) + ri = torch.as_tensor(spec["replay"][r_choices[step]], device=device) + roots = root_mask[choices] + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce, per_example = weighted_supervision(logits, new_data["labels"][ei], weights[choices]) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[replay_choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + study["retention_kl"] * kl + point = { + "step": step + 1, + "root_samples": int(roots.sum()), + "actual_samples": int((~roots).sum()), + "ce": float(ce.detach()), + "kl": float(kl.detach()), + "loss": float(loss.detach()), + } + if step in study["gradient_steps"]: + for name, mask in (("root", roots), ("actual", ~roots)): + component = (per_example * weights[choices] * mask).mean() + point[f"{name}_ce_gradient_norm"] = _gradient_norm(component, selected) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite P1 edit") + point["total_gradient_norm"] = float(norm) + point["gradient_clipped"] = bool(norm > 1) + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + stats.append(point) + if (step + 1) % 128 == 0: + print( + json.dumps({"event": "progress", "case": dest.name, "step": step + 1}), flush=True + ) + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": study["edit_steps"]}, + dest / "model-final.pt", + ) + completed = { + "status": "complete", + "contract_sha256": _contract_hash(contract), + "final_model_sha256": state_hash(model.state_dict()), + "parameters_updated": sum(p.numel() for p in selected), + "final": timeline[-1], + "root_samples": sum(p["root_samples"] for p in stats), + "actual_samples": sum(p["actual_samples"] for p in stats), + "clipped_updates": sum(p["gradient_clipped"] for p in stats), + } + if source_hashes() != contract["sources"]: + raise ValueError("P1 source files changed during this edit") + write_json(dest / "complete.json", completed) + return completed + + +def rescore_references(world, baseline, out, study, old_correct, parent): + """Archive provenance and recompute metrics without mutating historical files.""" + for chain, name in enumerate(CHAINS): + e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"]) + pair = edit_pair(world, chain) + for arm in REFERENCE_ARMS: + source = baseline / "edits" / f"{name}-{arm}-mlp" + spec = make_arm(world, chain, arm, pair) + with np.load(source / "sets.npz") as archived: + for key, expected in ( + ("E", spec["S"]), + ("replay", spec["replay"]), + ("edit_sampling", e_choices), + ("replay_sampling", r_choices), + ("old_correct", old_correct), + (arm, spec["target"]), + ): + if not np.array_equal(archived[key], expected): + raise ValueError(f"Reference reuse contract failed for {source}/{key}") + if not (source / "complete.json").exists(): + raise ValueError(f"Historical reference is incomplete: {source}") + timeline, hashes = [], {} + for step in study["edit_checkpoints"]: + path = source / f"predictions-{step}.npz" + with np.load(path) as stored: + arrays = {key: stored[key] for key in ("prediction", "ended", "correct")} + recomputed = (arrays["prediction"] == spec["target"]) & arrays["ended"] + if not np.array_equal(arrays["correct"], recomputed): + raise ValueError("Historical prediction correctness mismatch") + timeline.append({"step": step, **arm_metrics(world, spec, arrays, old_correct)}) + hashes[path.name] = file_hash(path) + dest = out / "references" / f"{name}-{arm}-mlp" + dest.mkdir(parents=True, exist_ok=True) + _freeze_json( + dest / "contract.json", {"parent": parent, "source": str(source), "files": hashes} + ) + atomic_numpy_save(dest / "sets.npz", **spec, old_correct=old_correct) + write_json(dest / "trajectory.json", timeline) + + +def run_model(baseline, output, study, device): + baseline, output = Path(baseline).resolve(), Path(output).resolve() + if output == baseline or baseline in output.parents: + raise ValueError("P1 results must not be written inside a frozen parent directory") + output.mkdir(parents=True, exist_ok=True) + config_path = baseline / "config.json" + config = json.loads(config_path.read_text()) + if config["sources"] != parent_source_hashes(): + raise ValueError("Frozen parent training sources have changed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent and P1 runtime differ: {key}") + parent_study = config["study"] + for key in ("edit_steps", "edit_checkpoints", "edit_lr", "retention_kl"): + if study[key] != parent_study[key]: + raise ValueError(f"Historical reference configuration differs: {key}") + parent_step = parent_study["steps"] + weights_path = baseline / f"model-{parent_step}.pt" + saved = torch.load(weights_path, map_location="cpu", weights_only=False) + if saved["config"] != config["model"] or saved["step"] != parent_step: + raise ValueError("Parent weight configuration mismatch") + final = json.loads((baseline / "learning-complete.json").read_text()) + if state_hash(saved["model"]) != final["model_sha256"]: + raise ValueError("Parent model state hash mismatch") + world = make_cross_world(config["world"]) + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent world does not match the current generated truth") + parent = { + "directory": str(baseline), + "config_sha256": file_hash(config_path), + "weights_sha256": file_hash(weights_path), + "model_sha256": final["model_sha256"], + "width": config["model"]["width"], + "world": config["world"], + "seed": config["seed"], + "condition": config["condition"], + "step": parent_step, + } + runtime = { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "python": platform.python_version(), + "numpy": np.__version__, + "device_type": device.type, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "precision": "BF16 autocast; FP32 weights and optimizer" + if device.type == "cuda" + else "FP32", + } + contract = {"parent": parent, "study": study, "sources": source_hashes(), "runtime": runtime} + _freeze_json(output / "contract.json", contract) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.cuda.manual_seed_all(config["seed"]) + torch.manual_seed(config["seed"]) + model = CausalLM(ModelConfig(**saved["config"])).to(device) + model.load_state_dict(saved["model"]) + data = tensor_queries(world, device) + old_arrays = evaluate(model, data, world.answers) + with np.load(baseline / f"predictions-{parent_step}.npz") as archived: + for key in ("correct", "prediction", "ended"): + if not np.array_equal(old_arrays[key], archived[key]): + raise ValueError(f"Parent predictions changed under this runtime: {key}") + atomic_numpy_save(output / "baseline-predictions.npz", **old_arrays) + write_json( + output / "runtime.json", + {**runtime, "device": str(device), "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES")}, + ) + rescore_references(world, baseline, output, study, old_arrays["correct"], parent) + completed = [] + for chain, name in enumerate(CHAINS): + for arm in study["arms"]: + dest = output / "edits" / f"{name}-{arm}" + result = run_case( + model, saved["model"], world, data, old_arrays, chain, arm, dest, study, parent + ) + completed.append(f"{name}-{arm}") + write_json( + output / "status.json", + {"state": "running", "complete": completed, "updated": time.time()}, + ) + print( + json.dumps( + {"event": "edit_complete", "case": dest.name, "D": result["final"]["D"]} + ), + flush=True, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "contract_sha256": _contract_hash(contract), + "edit_cases": len(completed), + "cases": completed, + "references": 4, + }, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config") + parser.add_argument("--arms", nargs="+", choices=(*ARMS, OPTIONAL_ARM)) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + args = parser.parse_args() + study = load_study(args.config, args.arms) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + try: + run_model(args.baseline, out, study, torch.device(args.device)) + except Exception as exc: + write_json(out / "failure.json", {"type": type(exc).__name__, "message": str(exc)}) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py new file mode 100644 index 0000000000000000000000000000000000000000..4d87971e01bb7f679239d58f88ea4ac1b054eb88 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py @@ -0,0 +1,375 @@ +"""Uninstantiated P4 projection diagnostics and equal-parameter branches. + +These operators do not choose a real layer, fit a real model's basis, read world +membership truth, or run an experiment. The caller must freeze a candidate and +an information budget first. Group means are not, by themselves, evidence of +an organizational representation. +""" + +from dataclasses import dataclass + +import numpy as np +import torch + + +@dataclass(frozen=True) +class Site: + layer: int + position: int + + +@dataclass(frozen=True) +class Basis: + q: np.ndarray + mean: np.ndarray + scale: np.ndarray + + @property + def rank(self): + return self.q.shape[1] + + def tensors(self, device): + return tuple( + torch.as_tensor(value, dtype=torch.float32, device=device) + for value in (self.q, self.mean, self.scale) + ) + + +def calibration_plan(actual_query_ids, person_by_query, membership_query_ids, supervised, replay): + """Only actual queries in S union R; bridge IDs specify additional self-queries. + + All arguments are query/identity metadata. No group truth or answers are + accepted. In particular this never constructs a derived query to fit Q. + """ + allowed = np.union1d(supervised, replay) + actual = np.intersect1d(actual_query_ids, allowed) + people = np.asarray(person_by_query)[actual] + if (people < 0).any() or len(np.unique(people)) != len(people): + raise ValueError("Calibration must contain one actual query per valid person") + membership = np.asarray(membership_query_ids)[people] + return { + "actual_query_ids": actual, + "person_ids": people, + "membership_query_ids": membership, + "logical_actual_queries": len(actual), + "logical_additional_membership_queries": len(membership), + "derived_calibration_queries": 0, + } + + +def valid_predicted_groups(prediction, ended, allowed_group_tokens): + prediction, ended = np.asarray(prediction), np.asarray(ended) + if prediction.ndim != 1 or ended.shape != prediction.shape or ended.dtype != bool: + raise ValueError("Group predictions require one value and a boolean termination mask") + valid = ended & np.isin(prediction, allowed_group_tokens) + # Invalid predictions are recorded, never replaced with the true group. + return np.where(valid, prediction, -1), valid + + +def _row_span(values, relative_tolerance=1e-6, absolute_tolerance=1e-8): + _, singular, vh = np.linalg.svd(values, full_matrices=False) + threshold = ( + max(absolute_tolerance, relative_tolerance * singular[0]) + if len(singular) + else absolute_tolerance + ) + numerical_rank = int((singular > threshold).sum()) + return vh[:numerical_rank].T, singular, numerical_rank + + +def _orthogonal_residual(values, q): + return values - (values @ q) @ q.T if q.shape[1] else values.copy() + + +def _normalized_basis(q, calibration): + projected = calibration @ q + mean, std = projected.mean(0), projected.std(0) + floor = max(float(np.sqrt(np.mean(std * std))) * 0.01, 1e-8) + std = np.maximum(std, floor) + unit = (projected - mean) / std + total_std = float(np.sqrt(np.mean(np.sum(unit * unit, axis=-1)))) + if not np.isfinite(total_std) or total_std <= 1e-8: + raise ValueError("A nonzero calibration variance is required") + basis = Basis( + q.astype(np.float32), mean.astype(np.float32), (std * total_std).astype(np.float32) + ) + if not np.allclose(basis.q.T @ basis.q, np.eye(q.shape[1]), atol=1e-5): + raise ValueError("The constructed basis is not orthonormal") + return basis + + +def fit_predicted_group_bases( + activations, + predicted_groups, + valid, + *, + rank=32, + seed=74, + variant="group_means", + predicted_answers=None, + answer_valid=None, +): + """Construct a target, orthogonal within-group complement, and random basis. + + Main method input: permitted actual-query states and model-predicted groups. + The optional answer-centered variant is a diagnostic until separately + preregistered. It uses model predictions from those same actual queries; + it does not request default/derived answer truth or extra derived states. + Rank failure returns unavailable; random directions never fill missing rank. + """ + x = np.asarray(activations, dtype=np.float64) + groups, used = np.asarray(predicted_groups), np.asarray(valid).copy() + if x.ndim != 2 or groups.shape != (len(x),) or used.shape != groups.shape or used.dtype != bool: + raise ValueError("Mismatched calibration arrays") + if not np.isfinite(x).all() or rank < 1 or rank > x.shape[1]: + raise ValueError("Finite activations and a feasible positive rank are required") + if (groups[used] < 0).any(): + raise ValueError("Invalid group predictions cannot be marked valid") + if variant not in ("group_means", "answer_centered_diagnostic"): + raise ValueError("Unknown basis variant") + answers = None + if variant == "answer_centered_diagnostic": + if predicted_answers is None or answer_valid is None: + raise ValueError("Answer centering requires model answers and validity flags") + answers, av = np.asarray(predicted_answers), np.asarray(answer_valid) + if answers.shape != groups.shape or av.shape != groups.shape or av.dtype != bool: + raise ValueError("Mismatched predicted answer arrays") + used &= av + report = { + "available": False, + "variant": variant, + "rank_requested": rank, + "calibration_rows": len(x), + "used_rows": int(used.sum()), + "invalid_rows": int((~used).sum()), + "uses_group_truth": False, + "uses_derived_calibration": False, + "random_seed": seed, + } + if not used.any(): + return None, {**report, "reason": "No valid model-predicted calibration groups"} + values, labels = x[used], groups[used] + unique, inverse = np.unique(labels, return_inverse=True) + group_means = np.stack([values[inverse == index].mean(0) for index in range(len(unique))]) + target_matrix = group_means - group_means.mean(0) + answer_span = np.empty((x.shape[1], 0)) + if answers is not None: + answer_labels = answers[used] + answer_means = np.stack( + [values[answer_labels == label].mean(0) for label in np.unique(answer_labels)] + ) + answer_span, _, _ = _row_span(answer_means - answer_means.mean(0)) + target_matrix = _orthogonal_residual(target_matrix, answer_span) + target_span, singular, target_rank = _row_span(target_matrix) + report.update( + predicted_groups=len(unique), + answer_span_rank=answer_span.shape[1], + target_numerical_rank=target_rank, + target_singular_values=singular.tolist(), + ) + if target_rank < rank: + return None, { + **report, + "reason": "Target has fewer than the required independent directions", + } + target = target_span[:, :rank] + residual = values - group_means[inverse] + residual = _orthogonal_residual(_orthogonal_residual(residual, answer_span), target) + complement_span, complement_singular, complement_rank = _row_span(residual) + report.update( + complement_numerical_rank=complement_rank, + complement_singular_values=complement_singular.tolist(), + ) + if complement_rank < rank: + return None, { + **report, + "reason": "Complement has fewer than the required independent directions", + } + if x.shape[1] - answer_span.shape[1] < rank: + return None, {**report, "reason": "Insufficient common admissible dimension"} + random_values = np.random.default_rng(seed).standard_normal((x.shape[1], rank)) + random_values = _orthogonal_residual(random_values.T, answer_span).T + random, triangular = np.linalg.qr(random_values, mode="reduced") + if (np.abs(np.diag(triangular)) < 1e-8).any(): + return None, {**report, "reason": "Random control is numerically rank deficient"} + bases = { + name: _normalized_basis(q, values) + for name, q in ( + ("target", target), + ("complement", complement_span[:, :rank]), + ("random", random), + ) + } + report["normalization"] = { + name: { + "rank": basis.rank, + "total_variance": float( + np.mean(np.sum(((values @ basis.q - basis.mean) / basis.scale) ** 2, axis=1)) + ), + "answer_span_overlap": float(np.linalg.norm(answer_span.T @ basis.q)), + } + for name, basis in bases.items() + } + return bases, {**report, "available": True, "reason": None} + + +def projection_component(values, q, mean): + # Explicit FP32 is necessary: .float() alone does not disable an outer + # autocast context for matrix products in a forward hook. + with torch.autocast(device_type=values.device.type, enabled=False): + return (values.float() @ q.float() - mean.float()) @ q.float().T + + +def match_delta_norm(delta, reference_norms, tolerance=1e-12): + """Zero-length controls with a positive target norm are explicitly unusable.""" + norms = torch.linalg.vector_norm(delta.float(), dim=-1) + reference_norms = torch.as_tensor(reference_norms, dtype=norms.dtype, device=norms.device) + if reference_norms.shape != norms.shape or bool((reference_norms < 0).any()): + raise ValueError("One nonnegative reference norm is required per case") + valid = (norms > tolerance) | (reference_norms <= tolerance) + scale = torch.where( + valid, reference_norms / norms.clamp_min(tolerance), torch.zeros_like(norms) + ) + return delta * scale[:, None], valid + + +def remove_projection(values, q, mean, reference_norms=None): + delta = -projection_component(values, q, mean) + valid = torch.ones(len(values), device=values.device, dtype=torch.bool) + if reference_norms is not None: + delta, valid = match_delta_norm(delta, reference_norms) + return values + delta.to(values.dtype), {"delta": delta, "valid": valid} + + +def restore_projection(values, clean_source, q, reference_norms=None): + """Restore only a fixed later-site projection, not an entire clean activation. + + clean_source must be from the same declared checkpoint and clean query, or + an explicitly labeled wrong-source control. A pre-edit source in an edited + model is a separate diagnostic and may undo the edit; it is never implicit. + """ + if values.shape != clean_source.shape: + raise ValueError("Restoration source and receiving states must have the same shape") + with torch.autocast(device_type=values.device.type, enabled=False): + delta = ((clean_source.float() - values.float()) @ q.float()) @ q.float().T + valid = torch.ones(len(values), device=values.device, dtype=torch.bool) + if reference_norms is not None: + delta, valid = match_delta_norm(delta, reference_norms) + return values + delta.to(values.dtype), {"delta": delta, "valid": valid} + + +def validate_restoration_sites(source, receiver, layers, answer_positions, allow_readout=False): + """A later relational post-block must still have a path to the value readout.""" + if not (0 <= source.layer < receiver.layer < layers): + raise ValueError("Restoration must be at a strictly later block, never the ablation point") + if source.position < 0 or receiver.position < 0: + raise ValueError("Token positions must be nonnegative") + if receiver.position < source.position: + raise ValueError("The receiving token is causally before the source token") + answer_positions = np.asarray(answer_positions) + if (answer_positions < receiver.position).any(): + raise ValueError("The receiving state cannot include an answer token") + if receiver.layer == layers - 1: + if (receiver.position < answer_positions).any(): + raise ValueError("Final-block earlier-token patches cannot affect value readout") + if not allow_readout: + raise ValueError("Final answer-marker restoration is a readout control, not routing") + return {"readout_control": receiver.layer == layers - 1} + + +def downstream_routing_site(source, layers, answer_positions): + """Prespecified L+1/same-token rescue; late candidates have no such rescue.""" + if source.layer > layers - 3: + raise ValueError("This late candidate has no nonterminal same-token routing rescue") + receiver = Site(source.layer + 1, source.position) + validate_restoration_sites(source, receiver, layers, answer_positions) + return receiver + + +def query_site_roles(lengths, position): + lengths = np.asarray(lengths) + if not np.isin(lengths, [4, 5]).all() or position not in (2, 3, 4): + raise ValueError("Only the declared basic/derived symbolic query forms are supported") + if (position >= lengths).any(): + raise ValueError("An intervention cannot use a future answer-token position") + return np.where( + position == lengths - 1, + "answer_marker", + "first_relation" if position == 2 else "second_relation", + ) + + +def attach_state_operation(model, site, operation): + """Attach a batch-local operation; caller supplies fixed source/control states. + + Operations return (new_state, diagnostics). Prompt and EOS passes may use + the same pre-answer operation; future answer tokens must never be sources. + """ + if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: + raise ValueError("Invalid intervention site") + traces = [] + + def intervene(_module, _inputs, output): + if site.position >= output.shape[1]: + raise ValueError("Intervention site is outside this query") + changed, trace = operation(output[:, site.position]) + if changed.shape != output[:, site.position].shape: + raise ValueError("An intervention changed the residual dimension") + result = output.clone() + result[:, site.position] = changed + traces.append(trace) + return result + + return model.blocks[site.layer].register_forward_hook(intervene), traces + + +def attach_equal_branch(model, basis, site, bottleneck=32, seed=73): + """The main experiment adds this branch to a common trainable MLP scope.""" + from .bios_branch import ResidualBranch + + if hasattr(model, "edit_branch"): + raise ValueError("An edit branch is already attached") + if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: + raise ValueError("Invalid branch site") + if site.position not in (2, 3): + raise ValueError("Method branches are restricted to locked relation candidates 2/3") + device = next(model.parameters()).device + branch = ResidualBranch(*basis.tensors(device), width=bottleneck, seed=seed) + model.add_module("edit_branch", branch) + + def add(_module, _inputs, output): + if site.position >= output.shape[1]: + raise ValueError("Branch site is outside this query") + changed = output.clone() + changed[:, site.position] += branch(output[:, site.position]) + return changed + + handle = model.blocks[site.layer].register_forward_hook(add) + expected = bottleneck * (basis.rank + model.config.width) + if sum(parameter.numel() for parameter in branch.parameters()) != expected: + raise ValueError("Unequal branch parameter count") + return branch, handle + + +def select_branch_parameters(model, branch, *, train_common_mlp=True, start=3): + from .bios_model import select_parameters + + if model.edit_branch is not branch: + raise ValueError("The branch is not attached to this model") + if train_common_mlp: + selected = select_parameters(model, "mlp", start) + else: + selected = [] + for parameter in model.parameters(): + parameter.requires_grad_(False) + parameter.grad = None + for parameter in branch.parameters(): + parameter.requires_grad_(True) + parameter.grad = None + selected.append(parameter) + return selected + + +def remove_equal_branch(model, handle): + handle.remove() + delattr(model, "edit_branch") diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_model.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7190d562883dec0d900e7ac14e894975f76499fb --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_model.py @@ -0,0 +1,120 @@ +"""Ordinary causal GPT-2-style language model used by protocol v2.3.""" + +import math +from dataclasses import asdict, dataclass + +import torch +from torch import nn +from torch.nn import functional as F + + +@dataclass(frozen=True) +class ModelConfig: + vocab_size: int + width: int = 768 + layers: int = 8 + heads: int = 12 + context: int = 128 + + +class Attention(nn.Module): + def __init__(self, config): + super().__init__() + self.heads = config.heads + self.qkv = nn.Linear(config.width, 3 * config.width) + self.proj = nn.Linear(config.width, config.width) + + def forward(self, x): + batch, length, width = x.shape + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +class MLP(nn.Module): + def __init__(self, width): + super().__init__() + self.up = nn.Linear(width, 4 * width) + self.activation = nn.GELU(approximate="tanh") + self.down = nn.Linear(4 * width, width) + + def forward(self, x): + return self.down(self.activation(self.up(x))) + + +class Block(nn.Module): + def __init__(self, config): + super().__init__() + self.ln1, self.ln2 = nn.LayerNorm(config.width), nn.LayerNorm(config.width) + self.attention = Attention(config) + self.mlp = MLP(config.width) + + def forward(self, x): + x = x + self.attention(self.ln1(x)) + return x + self.mlp(self.ln2(x)) + + +class CausalLM(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.token = nn.Embedding(config.vocab_size, config.width) + self.position = nn.Embedding(config.context, config.width) + self.blocks = nn.ModuleList([Block(config) for _ in range(config.layers)]) + self.ln_final = nn.LayerNorm(config.width) + self.apply(self._initialize) + for block in self.blocks: + for module in (block.attention.proj, block.mlp.down): + nn.init.normal_(module.weight, std=0.02 / math.sqrt(2 * config.layers)) + + @staticmethod + def _initialize(module): + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, std=0.02) + if isinstance(module, nn.Linear): + nn.init.zeros_(module.bias) + elif isinstance(module, nn.LayerNorm): + nn.init.ones_(module.weight) + nn.init.zeros_(module.bias) + + def forward(self, tokens, positions=None): + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + for block in self.blocks: + x = block(x) + 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 config_dict(self): + return asdict(self.config) + + +def select_parameters(model, scope, start=3): + if scope not in {"all", "mlp", "down"}: + raise ValueError("Scope must be all, mlp or down") + selected = list(model.parameters()) if scope == "all" else [] + if scope == "mlp": + selected = [p for block in model.blocks[start : start + 3] for p in block.mlp.parameters()] + elif scope == "down": + selected = [model.blocks[start + 1].mlp.down.weight] + ids = {id(p) for p in selected} + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) in ids) + parameter.grad = None + return selected + + +def matmul_flops(config, batch, sequence=6, output_positions=2, backward=True): + """Executed-shape dense/attention FLOPs estimate; excludes elementwise operations. + + Multiplication and addition each count as one. Backward uses a factor of two + forwards, a conventional upper approximation also used for frozen parameters. + This is not a hardware counter or a cross-editor exact FLOP measurement. + """ + d, layers, vocab = config.width, config.layers, config.vocab_size + forward = layers * (24 * batch * sequence * d * d + 4 * batch * sequence * sequence * d) + forward += 2 * batch * output_positions * d * vocab + return forward * (3 if backward else 1) diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_organization.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_organization.py new file mode 100644 index 0000000000000000000000000000000000000000..a64a674326bdc2e7202a987e0ac941b40640d912 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_organization.py @@ -0,0 +1,256 @@ +"""Equal-presentation bioS corpora differing only in document organization. + +A joins a person's six facts to the true employer default. B keeps the person's +facts together but supplies an unrelated company's default. C keeps B's exact +actual/default pair and moves the other five personal facts to distinct company +origins. No fact is falsified; every condition uses the same presentation pool. +""" + +import numpy as np + +from .bios_data import EOS, N_BASE, N_COMPANIES, N_PEOPLE, RELATIONS, array_hash, rng_for + +CONDITIONS = ("A", "B", "C") +CONDITION_NAMES = {"A": "relation_linked", "B": "person_grouped", "C": "shuffled"} +PERSONAL_RELATIONS = (0, 2, 3, 4, 5, 6) +N_PRESENTATIONS = N_PEOPLE * len(RELATIONS) + + +def _fact_lookup(world): + """Look up fact IDs without depending on the current contiguous numbering.""" + lookup = np.full((7, N_PEOPLE), -1, dtype=np.int64) + for relation in range(7): + ids = np.flatnonzero(world.relation[:N_BASE] == relation) + subjects = world.company[ids] if relation == 1 else world.person[ids] + lookup[relation, subjects] = ids + return lookup + + +def make_documents(world, condition, organization_seed=0): + """Return (2048, 7) fact IDs in canonical relation order. + + Organization is fixed across epochs. Random group ordering and within-group + assignment use a separate seed, shared across all three conditions. C's + seven company origins are distinct, including its unlinked default. + """ + if condition not in CONDITIONS: + raise ValueError(f"Unknown organization condition: {condition}") + if organization_seed < 0: + raise ValueError("organization_seed must be nonnegative") + lookup = _fact_lookup(world) + documents = np.empty((N_PEOPLE, 7), dtype=np.int64) + people = np.arange(N_PEOPLE) + for relation in PERSONAL_RELATIONS: + documents[:, relation] = lookup[relation, people] + documents[:, 1] = lookup[1, world.employers] + if condition == "A": + return documents + + rng = rng_for(world.seed, 101, organization_seed) + members = np.stack( + [rng.permutation(np.flatnonzero(world.employers == c)) for c in range(N_COMPANIES)] + ) + if members.shape != (N_COMPANIES, 32): + raise ValueError("Organization protocol requires 64 companies with 32 people each") + # Independent company cycles per employee-rank lane avoid a stable unrelated + # company partner. Every cycle is a derangement and visits every company. + cycles = np.stack([rng.permutation(N_COMPANIES) for _ in range(32)]) + lane = np.arange(32)[:, None] + anchors = members[cycles, lane] + documents[anchors, 1] = lookup[1, np.roll(cycles, -1, axis=1)] + if condition == "C": + for shift, relation in enumerate((0, 3, 4, 5, 6), start=2): + donor_members = members.copy() + # Each donor person contributes exactly one fact of this relation. + for row in donor_members: + rng.shuffle(row) + donors = donor_members[np.roll(cycles, -shift, axis=1), lane] + documents[anchors, relation] = lookup[relation, donors] + return documents + + +def apply_epoch(documents, world_seed, epoch): + """Apply a shared row permutation and cyclic slot rotation (zero-based epoch). + + Every seven complete epochs, every presentation visits all seven positions. + The permutation depends on the world and epoch, never on the condition. + """ + documents = np.asarray(documents) + if documents.shape != (N_PEOPLE, 7) or epoch < 0: + raise ValueError("Expected canonical (2048, 7) documents and nonnegative epoch") + rows = rng_for(world_seed, 102, epoch).permutation(N_PEOPLE) + return np.roll(documents[rows], epoch % 7, axis=1) + + +def document_epoch(world, condition, epoch, organization_seed=0): + return apply_epoch(make_documents(world, condition, organization_seed), world.seed, epoch) + + +def render_documents(world, ids): + """Render facts with cross-fact causal attention, answer/EOS-only supervision. + + Each row is one document, independently batched; no inter-document attention + is required. Positions select logits that predict the next answer/EOS token. + """ + ids = np.asarray(ids, dtype=np.int64) + if ids.ndim != 2 or ids.shape[1] != 7 or np.any((ids < 0) | (ids >= N_BASE)): + raise ValueError("Expected seven base fact IDs per document") + tokens = np.empty((*ids.shape, 6), dtype=np.int64) + tokens[:, :, :4] = world.prompts[ids, :4] + tokens[:, :, 4] = world.answers[ids] + tokens[:, :, 5] = EOS + positions = (np.arange(7)[:, None] * 6 + np.array([3, 4])).ravel() + labels = np.stack([world.answers[ids], np.full_like(ids, EOS)], axis=-1) + return { + "tokens": tokens.reshape(len(ids), 42), + "positions": np.broadcast_to(positions, (len(ids), 14)).copy(), + "labels": labels.reshape(len(ids), 14), + "fact_ids": ids.copy(), + } + + +def presentation_ids(world, documents): + """Assign each shared presentation to exactly one canonical document slot. + + Personal presentation IDs are 7*person+relation. The 32 default copies use + 7*employee+1, assigned in sorted row order. This assignment is made before + epoch rotation, and permits a fixed text/template for every presentation. + """ + documents = np.asarray(documents, dtype=np.int64) + if documents.shape != (N_PEOPLE, 7): + raise ValueError("Expected canonical (2048, 7) documents") + if not np.all(world.relation[documents] == np.arange(7)): + raise ValueError("Presentation assignment requires canonical relation order") + ids = world.person[documents] * 7 + world.relation[documents] + for company in range(N_COMPANIES): + rows = np.flatnonzero(world.company[documents[:, 1]] == company) + people = np.flatnonzero(world.employers == company) + if len(rows) != len(people): + raise ValueError("Each company default must have 32 presentations") + ids[rows, 1] = people * 7 + 1 + if not np.array_equal(np.sort(ids.ravel()), np.arange(N_PRESENTATIONS)): + raise ValueError("Presentations were lost or duplicated") + return ids + + +def audit_organizations(world, documents): + """Fail on confounds and report the measured organization intervention.""" + if set(documents) != set(CONDITIONS): + raise ValueError("Audit requires A, B and C") + expected_counts = np.where(world.relation[:N_BASE] == 1, 32, 1) + expected_answers = np.bincount( + world.answers[:N_BASE], weights=expected_counts, minlength=world.vocab_size + ).astype(np.int64) + conditions = {} + for condition, ids in documents.items(): + if ids.shape != (N_PEOPLE, 7) or not np.all(world.relation[ids] == np.arange(7)): + raise ValueError("Invalid document shape or relation slots") + counts = np.bincount(ids.ravel(), minlength=N_BASE) + if not np.array_equal(counts, expected_counts): + raise ValueError("Per-fact presentation counts differ") + answers = np.bincount(world.answers[ids].ravel(), minlength=world.vocab_size) + if not np.array_equal(answers, expected_answers): + raise ValueError("Answer-token presentation counts differ") + companies, people = world.company[ids], world.person[ids] + same_company = companies[:, :, None] == companies[:, None, :] + same_person = (people[:, :, None] == people[:, None, :]) & (people[:, :, None] >= 0) + personal = people[:, PERSONAL_RELATIONS] + all_personal_same = np.all(personal == personal[:, :1], axis=1) + if condition in ("A", "B") and not all_personal_same.all(): + raise ValueError("Person aggregation was broken") + if condition == "A" and not np.all(companies == companies[:, :1]): + raise ValueError("A contains a broken employer/default link") + if condition in ("B", "C") and np.any(companies[:, 1] == companies[:, 2]): + raise ValueError("Unrelated default accidentally matches actual person's employer") + if condition == "C" and np.any( + np.sort(companies, axis=1)[:, 1:] == np.sort(companies, axis=1)[:, :-1] + ): + raise ValueError("C contains two facts with the same company origin") + pids = presentation_ids(world, ids) + slots = np.zeros((N_BASE, 7), dtype=np.int64) + for epoch in range(7): + arranged = apply_epoch(ids, world.seed, epoch) + for slot in range(7): + np.add.at(slots[:, slot], arranged[:, slot], 1) + if not np.array_equal(slots, np.repeat(expected_counts[:, None], 7, axis=1)): + raise ValueError("Per-fact positions are not balanced over seven epochs") + default_actual_same = world.answers[ids[:, 1]] == world.answers[ids[:, 2]] + conditions[condition] = { + "name": CONDITION_NAMES[condition], + "documents": len(ids), + "presentations": int(ids.size), + "unique_base_facts": int(np.count_nonzero(counts)), + "document_tokens": 42, + "supervised_tokens_per_document": 14, + "total_input_tokens_per_epoch": int(ids.size * 6), + "total_supervised_tokens_per_epoch": int(ids.size * 2), + "facts_sha256": array_hash(ids), + "presentation_ids_sha256": array_hash(pids), + "exposure_sha256": array_hash(counts), + "answer_histogram_sha256": array_hash(answers), + "seven_epoch_fact_slot_sha256": array_hash(slots), + "company_origin_cooccurrence": same_company.mean(axis=0).tolist(), + "person_origin_cooccurrence": same_person.mean(axis=0).tolist(), + "all_personal_same_fraction": float(all_personal_same.mean()), + "default_actual_same_answer_count": int(default_actual_same.sum()), + "default_actual_same_answer_rate": float(default_actual_same.mean()), + "relation_counts": { + relation: int((world.relation[ids] == i).sum()) + for i, relation in enumerate(RELATIONS) + }, + } + if not np.array_equal(documents["B"][:, 1:3], documents["C"][:, 1:3]): + raise ValueError("B and C must share exactly the same default/actual fact pairs") + return { + "schema": "bios-organization-v1", + "world_seed": world.seed, + "truth_sha256": array_hash(world.answers), + "relation_slot_order": list(RELATIONS), + "same_truth_and_per_fact_presentations": True, + "position_balance_period_epochs": 7, + "same_default_actual_pairs_B_C": True, + "templates_and_aliases": "symbolic tokens fixed; English view uses common presentations", + "conditions": conditions, + } + + +def english_fact(world, fact_id, variant=0): + """Readable supplemental view; this text is not used in symbolic training.""" + if not 0 <= fact_id < N_BASE: + raise ValueError("Expected a base fact") + relation = int(world.relation[fact_id]) + subject = ( + world.names["companies"][int(world.company[fact_id])] + if relation == 1 + else (world.names["people"][int(world.person[fact_id])]) + ) + kind, raw = world.token_labels[int(world.answers[fact_id])].split(":", 1) + fields = { + "company": "companies", + "city": "cities", + "university": "universities", + "major": "majors", + } + value = raw if kind == "date" else world.names[fields[kind]][int(raw)] + templates = ( + ("{s} works for {v}.", "{s}'s employer is {v}.", "{v} employs {s}."), + ( + "{s}'s default work city is {v}.", + "{s} uses {v} as the default work city.", + "The default work city for {s} is {v}.", + ), + ( + "{s}'s actual work city is {v}.", + "{s} actually works in {v}.", + "The actual work city of {s} is {v}.", + ), + ("{s} was born on {v}.", "{s}'s birth date is {v}.", "The birth date of {s} is {v}."), + ("{s} was born in {v}.", "{s}'s birth city is {v}.", "The birth city of {s} is {v}."), + ("{s} attended {v}.", "{s}'s university is {v}.", "{s} studied at {v}."), + ( + "{s} majored in {v}.", + "{s}'s academic major is {v}.", + "The academic major of {s} is {v}.", + ), + ) + return templates[relation][variant % 3].format(s=subject, v=value) diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_organization_train.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_organization_train.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5d2bba261629aecc04944afd599bb827c634a8 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_organization_train.py @@ -0,0 +1,521 @@ +"""Matched A/B/C organization training; independent of the legacy SA/AS runs. + +An update contains 16 separate seven-fact causal documents and 28 isolated old +derived queries. Their supervised tokens are weighted 80:20. Each document is +a separate batch row, so attention never crosses document boundaries. +""" + +import argparse +import fcntl +import hashlib +import json +import math +import os +import platform +import random +import time +import traceback +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import ( + N_BASE, + N_PEOPLE, + N_QUERIES, + RELATIONS, + array_hash, + load_world, + rng_for, + write_json, +) +from .bios_model import CausalLM, ModelConfig, matmul_flops +from .bios_organization import apply_epoch, make_documents, render_documents +from .bios_train import code_fingerprint, evaluate, precision, tensor_data + +DOCUMENT_BATCH = 16 +DERIVED_BATCH = 28 +STEPS_PER_EPOCH = N_PEOPLE // DOCUMENT_BATCH +DEFAULT_STEPS = 14336 +WARMUP_EPOCHS = 16 +CHECKPOINTS = (0, 896, 1792, 3584, 7168, 10752, 14336, 21504, 28672) + + +def checkpoint_steps(steps): + if steps < 1: + raise ValueError("steps must be positive") + return sorted({step for step in CHECKPOINTS if step <= steps} | {steps}) + + +def derived_schedule(world_seed, steps, pool=None): + """Condition-independent stream; exhaust each permutation before repeating.""" + rng = rng_for(world_seed, 702) + size = steps * DERIVED_BATCH + pool = np.arange(N_BASE, N_QUERIES) if pool is None else np.asarray(pool) + if not len(pool) or len(np.unique(pool)) != len(pool): + raise ValueError("Derived pool must be nonempty and unique") + if np.any(pool < N_BASE) or np.any(pool >= N_QUERIES): + raise ValueError("Derived pool contains non-derived queries") + cycles = [rng.permutation(pool) for _ in range(math.ceil(size / len(pool)))] + return np.concatenate(cycles)[:size].reshape(steps, DERIVED_BATCH) + + +def learning_rate(step, base_lr): + # A constant rate within each complete epoch also matches per-fact LR exposure. + return base_lr * min((step // STEPS_PER_EPOCH + 1) / WARMUP_EPOCHS, 1.0) + + +def state_hash(state): + digest = hashlib.sha256() + for name, tensor in sorted(state.items()): + value = tensor.detach().cpu().contiguous() + digest.update(name.encode()) + digest.update(str(value.dtype).encode()) + digest.update(str(tuple(value.shape)).encode()) + digest.update(value.numpy().tobytes()) + return digest.hexdigest() + + +def schedule_hash(documents, world_seed, epochs): + digest = hashlib.sha256() + for epoch in range(epochs): + digest.update(np.ascontiguousarray(apply_epoch(documents, world_seed, epoch)).tobytes()) + return digest.hexdigest() + + +def update_flops(config): + return matmul_flops(config, DOCUMENT_BATCH, sequence=42, output_positions=14) + matmul_flops( + config, DERIVED_BATCH, sequence=6, output_positions=2 + ) + + +def two_context_backward(model, documents, isolated, derived_ids, device): + """Compute the exact per-token joint objective without retaining both graphs.""" + with precision(device): + logits = model(documents["tokens"], documents["positions"]) + doc_loss = F.cross_entropy(logits.float().flatten(0, 1), documents["labels"].flatten()) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(isolated["tokens"][derived_ids], isolated["positions"][derived_ids]) + derived_loss = F.cross_entropy( + logits.float().flatten(0, 1), isolated["labels"][derived_ids].flatten() + ) + (0.2 * derived_loss).backward() + return doc_loss.detach(), derived_loss.detach() + + +def atomic_torch_save(value, path): + temporary = path.with_suffix(path.suffix + ".tmp") + torch.save(value, temporary) + os.replace(temporary, path) + + +def atomic_numpy_save(path, **arrays): + temporary = path.with_suffix(path.suffix + ".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def core_sources(): + directory = Path(__file__).resolve().parent + names = ( + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization.py", + "bios_organization_train.py", + ) + return {name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in names} + + +def make_config(args, world, model, documents, derived): + steps = args.steps + epochs = math.ceil(steps / STEPS_PER_EPOCH) + return { + "protocol": "v2.4", + "dataset": "bios-organization-v1", + "phase": "development", + "run_kind": "full" + if steps == DEFAULT_STEPS and (args.width, args.layers, args.heads) == (768, 8, 12) + else "smoke", + "condition": args.condition, + "world_seed": world.seed, + "seed": args.seed, + "organization_seed": args.organization_seed, + "steps": steps, + "model": model.config_dict(), + "parameters": sum(p.numel() for p in model.parameters()), + "model_initial_sha256": state_hash(model.state_dict()), + "lr": args.lr, + "optimizer": "AdamW", + "weight_decay": 0.1, + "gradient_clip_norm": 1.0, + "warmup_epochs": WARMUP_EPOCHS, + "warmup_steps": WARMUP_EPOCHS * STEPS_PER_EPOCH, + "lr_rule": "constant within epoch: base_lr * min((epoch + 1) / 16, 1)", + "documents_per_step": DOCUMENT_BATCH, + "facts_per_document": 7, + "derived_queries_per_step": DERIVED_BATCH, + "document_weight": 0.8, + "derived_weight": 0.2, + "document_shape": {"sequence": 42, "supervised_positions": 14}, + "derived_shape": {"sequence": 6, "supervised_positions": 2}, + "context_objective": "answer+EOS only; same-document preceding facts visible causally", + "isolated_objective": "old-world derived QA only; no supporting document", + "cross_document_attention": False, + "evaluation": "all 14400 isolated queries; greedy value then generated EOS", + "steps_per_epoch": STEPS_PER_EPOCH, + "epochs": steps / STEPS_PER_EPOCH, + "checkpoints": checkpoint_steps(steps), + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "lengths_sha256": array_hash(world.lengths), + "documents_sha256": array_hash(documents), + "document_schedule_sha256": schedule_hash(documents, world.seed, epochs), + "derived_schedule_sha256": array_hash(derived), + "planned_atomic_presentations": steps * 112, + "planned_derived_presentations": steps * 28, + "planned_total_presentations": steps * 140, + "planned_document_presentations": steps * DOCUMENT_BATCH, + "planned_input_tokens_including_padding": steps * (16 * 42 + 28 * 6), + "planned_supervised_tokens": steps * (16 * 14 + 28 * 2), + "planned_train_matmul_flops_estimate": steps * update_flops(model.config), + "flops_method": "executed dense/attention shapes; backward=2x forward; excludes " + "elementwise operations, evaluation, padding-free reinterpretation", + "core_source_sha256": core_sources(), + } + + +def run_locked(args, out): + torch.set_num_threads(args.threads) + torch.manual_seed(args.seed) + random.seed(args.seed) + np.random.seed(args.seed) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + world = load_world(args.world) + documents = make_documents(world, args.condition, args.organization_seed) + from .bios_capacity import qa_split, split_metrics + + split_mode = getattr(args, "qa_split", "all") + train_ids, heldout_ids = qa_split(world, split_mode) + derived = derived_schedule(world.seed, args.steps, train_ids) + model = CausalLM(ModelConfig(world.vocab_size, args.width, args.layers, args.heads)).to(device) + config = make_config(args, world, model, documents, derived) + if getattr(args, "study", "legacy") == "capacity-v1": + config["core_source_sha256"]["bios_capacity.py"] = hashlib.sha256( + Path(__file__).with_name("bios_capacity.py").read_bytes() + ).hexdigest() + config.update( + { + "protocol": "v2.5-development", + "run_kind": "capacity-development", + "qa_split": split_mode, + "qa_train_ids": train_ids.tolist(), + "qa_heldout_ids": heldout_ids.tolist(), + "qa_split_policy": "half within company and old-exception stratum; world seed only", + "evaluation": "all base plus separately reported trained/heldout derived queries", + } + ) + config_path = out / "config.json" + if args.resume: + if not config_path.exists() or not (out / "resume.pt").exists(): + raise ValueError("Resume requires config.json and an atomic resume.pt checkpoint") + original = json.loads(config_path.read_text()) + differences = [key for key, value in config.items() if original.get(key) != value] + if differences: + raise ValueError("Resume configuration mismatch: " + ", ".join(differences)) + elif config_path.exists() or any(out.glob("model-*.pt")) or (out / "resume.pt").exists(): + raise ValueError("Output already contains a run; use a fresh directory or --resume") + else: + config.update( + { + "world": str(Path(args.world).resolve()), + "output": str(out.resolve()), + "execution": { + "device": args.device, + "threads": args.threads, + "torch": torch.__version__, + "python": platform.python_version(), + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast on CUDA; FP32 weights/loss/Adam moments", + "deterministic_algorithms": torch.are_deterministic_algorithms_enabled(), + "allow_tf32": torch.backends.cuda.matmul.allow_tf32, + }, + **code_fingerprint(), + } + ) + write_json(config_path, config) + atomic_numpy_save(out / "schedule.npz", documents=documents, derived=derived) + optimizer = torch.optim.AdamW( + model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + isolated = tensor_data(world, device) + counts = np.zeros(N_QUERIES, dtype=np.int64) + slot_counts = np.zeros((N_BASE, 7), dtype=np.int64) + weighted_exposure = np.zeros(N_QUERIES, dtype=np.float64) + timeline, losses = [], [] + train_seconds, first_step = 0.0, 0 + if args.resume: + state = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if state["config_sha256"] != hashlib.sha256(config_path.read_bytes()).hexdigest(): + raise ValueError("Resume checkpoint configuration fingerprint mismatch") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + torch.set_rng_state(state["torch_rng"]) + if device.type == "cuda" and state["cuda_rng"] is not None: + torch.cuda.set_rng_state(state["cuda_rng"], device) + random.setstate(state["python_rng"]) + np.random.set_state(state["numpy_rng"]) + counts, slot_counts = state["counts"], state["slot_counts"] + weighted_exposure = state["weighted_exposure"] + timeline, train_seconds, first_step = ( + state["timeline"], + state["train_seconds"], + state["step"], + ) + resumes_path = out / "resumes.json" + resumes = json.loads(resumes_path.read_text()) if resumes_path.exists() else [] + resumes.append({"from_step": first_step, "device": args.device, **code_fingerprint()}) + write_json(resumes_path, resumes) + if (out / "failure.json").exists(): + os.replace(out / "failure.json", out / f"failure-before-resume-{len(resumes)}.json") + if device.type == "cuda": + torch.cuda.reset_peak_memory_stats(device) + cached_epoch, cached_documents = None, None + active_step = first_step + try: + for step in range(first_step, args.steps + 1): + active_step = step + if step in checkpoint_steps(args.steps) and not (args.resume and step == first_step): + started = time.perf_counter() + metrics, arrays = evaluate(model, isolated, world, batch_size=args.eval_batch_size) + if getattr(args, "study", "legacy") == "capacity-v1": + metrics.update(split_metrics(world, arrays, train_ids, heldout_ids)) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slot_exposure=slot_counts, + lr_weighted_exposure=weighted_exposure, + ) + atomic_torch_save( + { + "model": { + key: value.detach().cpu() for key, value in model.state_dict().items() + }, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + record = { + "step": step, + "epoch": step / STEPS_PER_EPOCH, + **metrics, + "train_seconds": train_seconds, + "train_matmul_flops_estimate": step * update_flops(model.config), + "presentations": int(counts.sum()), + "document_presentations": step * DOCUMENT_BATCH, + "base_presentations": int(counts[:N_BASE].sum()), + "derived_presentations": int(counts[N_BASE:].sum()), + "coverage_base": float((counts[:N_BASE] > 0).mean()), + "coverage_derived": float((counts[N_BASE:] > 0).mean()), + "world_tokens": int((counts * (world.lengths + 2)).sum()), + "input_tokens_including_padding": step * (16 * 42 + 28 * 6), + "supervised_tokens": step * (16 * 14 + 28 * 2), + "exposure_sha256": array_hash(counts), + "slot_exposure_sha256": array_hash(slot_counts), + "lr_weighted_exposure_sha256": array_hash(weighted_exposure), + "lr_weighted_exposure_by_relation": { + relation: float(weighted_exposure[world.relation == i].sum()) + for i, relation in enumerate((*RELATIONS, "derived")) + }, + "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "eval_and_checkpoint_seconds": time.perf_counter() - started, + "mean_training_loss_since_previous": float(np.mean([x[0] for x in losses])) + if losses + else None, + "mean_context_document_loss": float(np.mean([x[1] for x in losses])) + if losses + else None, + "mean_isolated_derived_loss": float(np.mean([x[2] for x in losses])) + if losses + else None, + } + timeline.append(record) + write_json(out / "learning.json", timeline) + atomic_torch_save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) + if device.type == "cuda" + else None, + "python_rng": random.getstate(), + "numpy_rng": np.random.get_state(), + "timeline": timeline, + "counts": counts, + "slot_counts": slot_counts, + "weighted_exposure": weighted_exposure, + "train_seconds": train_seconds, + "step": step, + "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), + }, + out / "resume.pt", + ) + losses = [] + print( + json.dumps( + { + "event": "checkpoint", + "step": step, + "base": metrics["base_accuracy"], + "derived": metrics["derived_accuracy"], + "train_seconds": train_seconds, + } + ), + flush=True, + ) + if step == args.steps: + break + epoch = step // STEPS_PER_EPOCH + if cached_epoch != epoch: + ordered = apply_epoch(documents, world.seed, epoch) + rendered = render_documents(world, ordered) + # One small epoch tensor transfer; training slices never join documents. + cached_documents = { + key: torch.as_tensor(rendered[key], device=device) + for key in ("tokens", "positions", "labels") + } + cached_epoch = epoch + offset = (step % STEPS_PER_EPOCH) * DOCUMENT_BATCH + batch = { + key: value[offset : offset + DOCUMENT_BATCH] + for key, value in cached_documents.items() + } + fact_ids = ordered[offset : offset + DOCUMENT_BATCH] + derived_ids = torch.as_tensor(derived[step], device=device) + lr = learning_rate(step, args.lr) + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + doc_loss, derived_loss = two_context_backward( + model, batch, isolated, derived_ids, device + ) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(doc_loss + derived_loss) or not torch.isfinite(norm): + raise FloatingPointError("Nonfinite document/derived loss or gradient norm") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - started + dloss, qloss = float(doc_loss), float(derived_loss) + losses.append((0.8 * dloss + 0.2 * qloss, dloss, qloss)) + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, derived[step], 1) + np.add.at(slot_counts, (fact_ids, np.arange(7)[None, :]), 1) + np.add.at(weighted_exposure, fact_ids.ravel(), lr) + np.add.at(weighted_exposure, derived[step], lr) + if (step + 1) % 100 == 0: + print( + json.dumps( + { + "event": "progress", + "step": step + 1, + "epoch": (step + 1) / STEPS_PER_EPOCH, + "loss": float(np.mean([x[0] for x in losses[-100:]])), + "train_seconds": train_seconds, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "step": args.steps, + "status": "complete", + "final": timeline[-1], + "exposure_sha256": array_hash(counts), + "slot_exposure_sha256": array_hash(slot_counts), + "model_final_sha256": state_hash(model.state_dict()), + }, + ) + except BaseException as error: + write_json( + out / "failure.json", + { + "step": active_step, + "reason": str(error), + "type": type(error).__name__, + "traceback": traceback.format_exc(), + "train_seconds": train_seconds, + "last_committed_checkpoint": timeline[-1]["step"] if timeline else None, + }, + ) + raise + + +def train(args): + checkpoint_steps(args.steps) + if ( + getattr(args, "qa_split", "all") != "all" + and getattr(args, "study", "legacy") != "capacity-v1" + ): + raise ValueError("Heldout QA requires explicit capacity study") + if args.width < 1 or args.layers < 1 or args.heads < 1 or args.width % args.heads: + raise ValueError("Model dimensions must be positive and width divisible by heads") + if args.lr <= 0 or not math.isfinite(args.lr): + raise ValueError("Learning rate must be finite and positive") + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".train.lock").open("a") as lock: + try: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as error: + raise RuntimeError("Another process is training in this output directory") from error + run_locked(args, out) + + +def parser(): + result = argparse.ArgumentParser(description=__doc__) + result.add_argument("--world", required=True) + result.add_argument("--output", required=True) + result.add_argument("--condition", choices=("A", "B", "C"), required=True) + result.add_argument("--seed", type=int, default=0) + result.add_argument("--organization-seed", type=int, default=0) + result.add_argument("--steps", type=int, default=DEFAULT_STEPS) + result.add_argument("--lr", type=float, default=1e-4) + result.add_argument("--device", default="cuda") + result.add_argument("--threads", type=int, default=4) + result.add_argument("--eval-batch-size", type=int, default=512) + result.add_argument("--width", type=int, default=768) + result.add_argument("--layers", type=int, default=8) + result.add_argument("--heads", type=int, default=12) + result.add_argument("--study", choices=("legacy", "capacity-v1"), default="legacy") + result.add_argument("--qa-split", choices=("all", "half"), default="all") + result.add_argument("--resume", action="store_true") + return result + + +def main(): + train(parser().parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_data.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_data.py new file mode 100644 index 0000000000000000000000000000000000000000..98352c46d29112ab2ac2be7212204897c13aea18 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_data.py @@ -0,0 +1,455 @@ +"""Pinned six-attribute bioS reconstruction for plan 14.27 (not the old graph).""" + +from __future__ import annotations + +import ast +import calendar +import hashlib +import json +import random +from collections import Counter +from pathlib import Path + +import numpy as np + +SOURCE = Path("data/bios-source") +MATERIAL = SOURCE / "data-synthetic-pretrain/Capo-bioS-bioR" +SOURCE_CODE = MATERIAL / "Capo-bioS-bioR.py" +MONTHS = list(calendar.month_name)[1:] +ATTRS = ("date", "birthcity", "university", "field", "workcity", "company") +TASKS = (*ATTRS, "year", "parity", "company_city", "city_company", "comparison") + +# View 0 of the first six tasks is the question wording in Part 3.1, section 2.2. +# Additional tasks and views are an explicit measurement adaptation. +QUESTIONS = { + "date": [ + "What is the birth date of {n}?", + "On what date was {n} born?", + "Give {n}'s full date of birth.", + "When was {n} born?", + "State the birthday, including the year, of {n}.", + "What is {n}'s complete birth date?", + ], + "birthcity": [ + "What is the birth city of {n}?", + "In which city was {n} born?", + "Give {n}'s city of birth.", + "Where was {n} born?", + "Name the birthplace city of {n}.", + "What city is {n}'s birthplace?", + ], + "university": [ + "Which university did {n} study?", + "Where did {n} attend university?", + "Give the university attended by {n}.", + "At which university did {n} study?", + "Name {n}'s university.", + "What university educated {n}?", + ], + "field": [ + "What major did {n} study?", + "What was {n}'s field of study?", + "Give {n}'s university major.", + "In what subject did {n} major?", + "Name the discipline studied by {n}.", + "Which subject did {n} study at university?", + ], + "company": [ + "Which company did {n} work for?", + "Who was {n}'s employer?", + "Give the company employing {n}.", + "At what company did {n} work?", + "Name {n}'s employer.", + "What is the name of the company where {n} worked?", + ], + "workcity": [ + "Where did {n} work?", + "In which city did {n} work?", + "Give {n}'s work city.", + "What city was {n}'s employer based in?", + "Name the city of {n}'s workplace.", + "What was {n}'s city of employment?", + ], + "year": [ + "What is the birth year of {n}?", + "In which year was {n} born?", + "Give only {n}'s birth year.", + "Name the year in {n}'s date of birth.", + "What year marks {n}'s birth?", + "State the year of birth for {n}.", + ], + "parity": [ + "Was {n} born in an even-numbered month?", + "Is {n}'s birth month number even?", + "Does the month of {n}'s birth have an even number?", + "Is the calendar month when {n} was born even-numbered?", + "For {n}, is the birth month one of months 2, 4, 6, 8, 10, or 12?", + "Is the number of {n}'s birth month divisible by two?", + ], + "company_city": [ + "Give {n}'s company, then work city.", + "Name the employer of {n}, followed by its city.", + "For {n}, list company before workplace city.", + "What company employed {n}, and in what city?", + "State {n}'s company and city, in that order.", + "Report {n}'s employer first and work city second.", + ], + "city_company": [ + "Give {n}'s work city, then company.", + "Name the work city of {n}, followed by the employer.", + "For {n}, list workplace city before company.", + "In what city did {n} work, and for what company?", + "State {n}'s work city and company, in that order.", + "Report {n}'s work city first and employer second.", + ], + "comparison": [ + "Who was born earlier, {a} or {b}?", + "Which was born first: {a} or {b}?", + "Between {a} and {b}, name the older person.", + "Whose date of birth is earlier, {a}'s or {b}'s?", + "Compare the birthdays of {a} and {b}. Who is older?", + "Of {a} and {b}, who has the earlier birthday including the year?", + ], +} + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write_json(path, obj): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(obj, indent=2, ensure_ascii=False) + "\n") + temp.replace(path) + + +def load_json(path): + return json.loads(Path(path).read_text()) + + +def verify_source(): + manifest = load_json("configs/bios-source-manifest.json") + for row in manifest["files"]: + if digest(SOURCE / row["path"]) != row["sha256"]: + raise ValueError(f"Official source changed: {row['path']}") + return manifest + + +def source_templates(): + """Read literal templates without importing or changing the upstream source.""" + tree = ast.parse(SOURCE_CODE.read_text()) + fn = next( + n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "get_text_simple3" + ) + values = {} + for node in fn.body: + if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name): + name = node.targets[0].id + if name.startswith("sentence_structures"): + values[int(name[-1]) - 1] = ast.literal_eval(node.value) + return [values[i] for i in range(6)] + + +def date(p): + return f"{MONTHS[p['month'] - 1]} {p['day']}, {p['year']}" + + +def date_key(p): + return p["year"], p["month"], p["day"] + + +def render_sentences(p, templates, ids, order=range(6)): + fields = dict( + birthday=date(p), + birthcity=p["birthcity"], + university=p["university"], + field=p["field"], + company1city=p["workcity"], + company1name=p["company"], + ) + return [ + " " + templates[a][ids[a]].format(name=p["name"] if j == 0 else p["pronoun"], **fields) + for j, a in enumerate(order) + ] + + +def make_people(seed, count): + if count % 10: + raise ValueError("Population must permit exact 50/10/40 splits") + rng = random.Random(seed) + pools = { + key: (MATERIAL / "fields" / f"{key}.txt").read_text().splitlines() + for key in ( + "first_name", + "middle_name", + "last_name", + "city", + "university", + "field", + "company", + ) + } + names, people = set(), [] + for i in range(count): + while True: + name_ids = [ + rng.randrange(len(pools[k])) for k in ("first_name", "middle_name", "last_name") + ] + name = " ".join( + pools[k][v] + for k, v in zip(("first_name", "middle_name", "last_name"), name_ids, strict=True) + ) + if name not in names: + names.add(name) + break + indices = { + k: rng.randrange(len(pools[k])) for k in ("city", "university", "field", "company") + } + company, city = [s.strip() for s in pools["company"][indices["company"]].split(";", 1)] + people.append( + dict( + id=i, + name=name, + name_ids=name_ids, + attribute_ids=indices, + year=rng.randrange(1900, 2100), + month=rng.randrange(1, 13), + day=rng.randrange(1, 29), + birthcity=pools["city"][indices["city"]], + university=pools["university"][indices["university"]], + field=pools["field"][indices["field"]], + company=company, + workcity=city, + pronoun="He" if i % 2 == 0 else "She", + ) + ) + ids = list(range(count)) + random.Random(seed + 1000000).shuffle(ids) + for j, i in enumerate(ids): + people[i]["split"] = ( + "train" if j < count // 2 else ("dev" if j < 6 * count // 10 else "test") + ) + # One balanced comparison row per person. Both participants stay in the same split. + for split in ("train", "dev", "test"): + indices = [p["id"] for p in people if p["split"] == split] + random.Random(seed + len(indices)).shuffle(indices) + for j in range(0, len(indices), 2): + a, b = indices[j : j + 2] + if date_key(people[a]) == date_key(people[b]): + for k in range(j + 2, len(indices)): + c = indices[k] + if date_key(people[a]) != date_key(people[c]): + indices[j + 1], indices[k] = indices[k], indices[j + 1] + b = c + break + else: + raise ValueError("Equal-date terminal pair; choose a new prespecified seed") + people[a]["partner"] = b + people[b]["partner"] = a + return people + + +def answer(p, task, other=None): + if task == "date": + return date(p) + if task == "year": + return str(p["year"]) + if task == "parity": + return "yes" if p["month"] % 2 == 0 else "no" + if task == "company_city": + return f"{p['company']}; {p['workcity']}" + if task == "city_company": + return f"{p['workcity']}; {p['company']}" + if task == "comparison": + return min((p, other), key=date_key)["name"] + return p[task] + + +def question(p, task, view=0, other=None, cot=False): + q = QUESTIONS[task][view].format(n=p["name"], a=p["name"], b=other["name"] if other else "") + return "Question: " + q + (" Explain briefly." if cot else "") + "\nAnswer:" + + +def reasoning(p, task, other=None): + value = answer(p, task, other) + if task == "parity": + return ( + f"{date(p)}; {MONTHS[p['month'] - 1]} is month {p['month']}; " + f"{p['month']} is {'even' if p['month'] % 2 == 0 else 'odd'}; Answer: {value}" + ) + if task == "comparison": + return f"{p['name']}: {date(p)}; {other['name']}: {date(other)}; Answer: {value}" + if task == "year": + return f"{date(p)}; the year is {p['year']}; Answer: {value}" + if task in ("company_city", "city_company"): + return f"company: {p['company']}; work city: {p['workcity']}; Answer: {value}" + return f"{task}: {value}; Answer: {value}" + + +def edit_cases(people, seed): + rng = random.Random(seed + 3000000) + groups = [ + [p for p in people if p["split"] == "test" and p["month"] % 2 == parity] + for parity in (0, 1) + ] + selected = rng.sample(groups[0], 8) + rng.sample(groups[1], 8) + result = [] + for p in selected: + month = rng.choice([m for m in range(1, 13) if m % 2 != p["month"] % 2]) + year = rng.choice([y for y in range(1900, 2100) if y != p["year"]]) + result.append( + dict( + person_id=p["id"], + old_month=p["month"], + old_year=p["year"], + new_month=month, + new_year=year, + day=p["day"], + cells=[ + dict(month=m, year=y) + for m, y in ( + (p["month"], p["year"]), + (month, p["year"]), + (p["month"], year), + (month, year), + ) + ], + ) + ) + return result + + +def prepare_world(cfg, seed, tokenizer): + root = Path(cfg["data_root"]) / f"world-{seed}" + if (root / "audit.json").exists(): + audit = load_json(root / "audit.json") + for f, h in audit["files"].items(): + if digest(root / f) != h: + raise ValueError(f"Data changed: {root / f}") + return audit + root.mkdir(parents=True, exist_ok=True) + manifest = verify_source() + source_hash = digest(SOURCE_CODE) + templates = source_templates() + people = make_people(seed, cfg["people"]) + write_json(root / "people.json", people) + write_json(root / "edit-cases.json", edit_cases(people, seed)) + write_json(root / "questions.json", QUESTIONS) + rng = random.Random(seed + 2000000) + template_ids = np.empty((len(people), 5, 6), dtype=np.int16) + # Store separately tokenized full-name/pronoun sentences; no splitting at periods. + # This preserves abbreviations in company names and city names. + all_ids, lengths = [], [] + with (root / "biographies.jsonl").open("w") as out: + for p in people: + for variant in range(5): + ids = [rng.randrange(len(t)) for t in templates] + template_ids[p["id"], variant] = ids + sentences = render_sentences(p, templates, ids) + out.write( + json.dumps( + dict( + person_id=p["id"], + variant=variant, + template_ids=ids, + order=list(ATTRS), + source_sha256=source_hash, + text="".join(sentences), + ) + ) + + "\n" + ) + for a in range(6): + # Force this attribute first, and then second, to obtain both name forms. + full = render_sentences(p, templates, ids, [a])[0] + pro = render_sentences(p, templates, ids, [(a + 1) % 6, a])[1] + for text in (full, pro): + enc = tokenizer.encode(text).ids + all_ids.append(enc) + lengths.append(len(enc)) + max_len = max(lengths) + packed = np.zeros((len(all_ids), max_len), dtype=np.uint16) + for i, tokens in enumerate(all_ids): + packed[i, : len(tokens)] = tokens + np.save(root / "sentence-tokens.npy", packed.reshape(len(people), 5, 6, 2, max_len)) + np.save( + root / "sentence-lengths.npy", + np.array(lengths, dtype=np.int16).reshape(len(people), 5, 6, 2), + ) + np.save(root / "template-ids.npy", template_ids) + assert len({p["name"] for p in people}) == len(people) + for p in people: + assert people[p["partner"]]["split"] == p["split"] + assert date_key(p) != date_key(people[p["partner"]]) + counts = Counter(p["split"] for p in people) + for task in TASKS: + assert len(QUESTIONS[task]) == len(set(QUESTIONS[task])) == 6 + files = [ + "people.json", + "edit-cases.json", + "questions.json", + "biographies.jsonl", + "sentence-tokens.npy", + "sentence-lengths.npy", + "template-ids.npy", + ] + audit = dict( + seed=seed, + people=len(people), + splits=dict(counts), + source_revision=manifest["revision"], + source_sha256=digest(SOURCE_CODE), + template_counts=dict(zip(ATTRS, map(len, templates), strict=True)), + variants=5, + facts_per_person=6, + passes=540, + tasks_per_train_person=11, + train_rows=counts["train"] * 11, + qa_training_views=[0], + globally_held_out_views=list(range(1, 6)), + equal_date_comparisons=0, + cross_split_comparisons=0, + comparison_first_answer_fraction={ + s: np.mean( + [date_key(p) < date_key(people[p["partner"]]) for p in people if p["split"] == s] + ).item() + for s in counts + }, + city_collisions=sum(p["birthcity"] == p["workcity"] for p in people), + max_sentence_tokens=max_len, + files={f: digest(root / f) for f in files}, + ) + write_json(root / "audit.json", audit) + return audit + + +class BioStream: + """One deterministic pass presents every person exactly once, including the tail.""" + + def __init__(self, root, seed, condition): + self.tokens = np.load(Path(root) / "sentence-tokens.npy", mmap_mode="r") + self.lengths = np.load(Path(root) / "sentence-lengths.npy", mmap_mode="r") + self.seed, self.condition = seed, condition + self.count = self.tokens.shape[0] + + def pass_tokens(self, epoch): + rng = np.random.default_rng(np.random.SeedSequence([self.seed, epoch, 1427])) + people = rng.permutation(self.count) + stream = [50256] + order_hash = hashlib.sha256() + for pid in people: + variant = 0 if self.condition == "S" else (epoch + int(pid)) % 5 + order = rng.permutation(6) if self.condition == "MP" else np.arange(6) + order_hash.update(np.array([pid, variant, *order], dtype=np.int64).tobytes()) + for j, attr in enumerate(order): + form = int(j != 0) + size = self.lengths[pid, variant, attr, form] + stream.extend(self.tokens[pid, variant, attr, form, :size]) + stream.append(50256) + return np.asarray(stream, dtype=np.int64), order_hash.hexdigest() + + def exact_token_budget(self, passes): + # Permuting only changes which sentence uses the full name; sum its exact sizes. + return sum(len(self.pass_tokens(e)[0]) - 1 for e in range(passes)) diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_diagnostics.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..dc0de9f1aeb4e6e8a48ea33b265811985ebea4d8 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_diagnostics.py @@ -0,0 +1,463 @@ +"""Frozen endpoint diagnostics for bioS; no training and no ground-truth auto inputs.""" + +from __future__ import annotations + +import calendar +import json +import os +import random +import re +import time +from collections import defaultdict +from pathlib import Path + +import torch +from tokenizers import Tokenizer + +from .bios_original_data import ATTRS, TASKS, answer, date, digest, load_json, question, write_json +from .bios_original_train import ( + amp, + encode_row, + generate, + load_model, + normalize, + sequence_scores, + setup, +) + +DEFAULT_ROOT = "docs/development-artifacts/bios-original-diagnostics-v1" +TASK_PAIR = ("parity", "comparison") + + +def select_people(people, world, count=24): + """Sample whole development partner pairs without model-dependent filtering.""" + if count % 2: + raise ValueError("The development count must consist of whole pairs") + pairs = [ + (p["id"], p["partner"]) for p in people if p["split"] == "dev" and p["id"] < p["partner"] + ] + pairs = random.Random(world + 930001).sample(pairs, count // 2) + return sorted(i for pair in pairs for i in pair) + + +def parse_date(text): + """Strict full-string date parser; malformed generations remain failures.""" + text = normalize(text) + names = {name.casefold(): i for i, name in enumerate(calendar.month_name) if i} + match = re.fullmatch(r"([a-z]+) ([1-9]|1\d|2[0-8]), (\d{4})", text) + if match is None or match[1] not in names: + return None + return (int(match[3]), names[match[1]], int(match[2])) + + +def operation_prompt(task, first, second=None): + """Exact rule-training prompt; only supplied strings enter this function.""" + if task == "parity": + parsed = parse_date(first) + month = calendar.month_name[parsed[1]] if parsed else first + return f"Question: Is {month} an even-numbered month?\nAnswer:" + if task == "comparison": + return f"Question: Which date is earlier, {first} or {second}?\nAnswer:" + raise ValueError(task) + + +def decode_operation(task, generated, first, second=None, names=None): + """Map a model-selected supplied date to its name without consulting truth.""" + if task == "parity": + return normalize(generated) + chosen = normalize(generated) + values = [normalize(first), normalize(second)] + if values[0] == values[1] or chosen not in values: + return None + return names[values.index(chosen)] + + +def symbolic_operation(task, first, second=None, names=None): + """A separately labelled host-computation ceiling, never a model result.""" + a = parse_date(first) + if a is None: + return None + if task == "parity": + return "yes" if a[1] % 2 == 0 else "no" + b = parse_date(second) + if b is None or a == b: + return None + return names[0 if a < b else 1] + + +def audit_batches(people, tasks, cot, batch_size): + """Select one original physical batch per split, independent of predictions.""" + eligible = [p for p in people if p["split"] in ("dev", "test")] + rows_per_person = len(tasks) * 6 * (2 if cot else 1) + starts = set() + for split in ("dev", "test"): + person_index = next(i for i, p in enumerate(eligible) if p["split"] == split) + starts.add((person_index * rows_per_person // batch_size) * batch_size) + return sorted(starts) + + +def read_selected_batches(path, starts, batch_size): + batches = {s: [] for s in starts} + with Path(path).open() as stream: + for i, line in enumerate(stream): + for s in starts: + if s <= i < s + batch_size: + batches[s].append(dict(load_json_line=json.loads(line), source_row=i)) + if i >= max(starts) + batch_size - 1: + break + if any(len(rows) != batch_size for rows in batches.values()): + raise ValueError("Incomplete historical physical batch") + return [dict(start=s, rows=rows) for s, rows in batches.items()] + + +def prepare(config_path, root=DEFAULT_ROOT, count=24): + root = Path(root) + if (root / "plan.json").exists(): + raise FileExistsError("Diagnostic inputs already frozen") + cfg = load_json(config_path) + source_files = [ + "src/llm_memory_editability/bios_original_diagnostics.py", + "scripts/run_bios_original_diagnostics.py", + "src/llm_memory_editability/bios_original_data.py", + "src/llm_memory_editability/bios_original_model.py", + "src/llm_memory_editability/bios_original_train.py", + ] + # Loading current implementations is valid only if original implementations match. + frozen = Path(cfg["result_root"]) / "execution-source" + for file in source_files[2:]: + if digest(file) != digest(frozen / file): + raise ValueError(f"Original source changed: {file}") + plan = dict( + version=1, + created_unix=time.time(), + config_path=str(config_path), + config_sha256=digest(config_path), + config=cfg, + count=count, + views=[0, 1], + diagnostic_batch_size=16, + audit_batch_size=cfg["evaluation"]["batch_size"], + max_new_tokens=cfg["evaluation"]["max_new_tokens"], + source_sha256={f: digest(f) for f in source_files}, + tokenizer_sha256=digest(Path(cfg["data_root"]) / "tokenizer/tokenizer.json"), + worlds={}, + endpoints=[], + ) + for world in cfg["world_seeds"]: + data_path = Path(cfg["data_root"]) / f"world-{world}/people.json" + people = load_json(data_path) + plan["worlds"][str(world)] = dict( + person_ids=select_people(people, world, count), + people_path=str(data_path), + sha256=digest(data_path), + ) + for init in cfg["initialization_seeds"]: + for condition in cfg["task"]["conditions"]: + stages = ["adapt", "task"] if condition in ("S", "M", "MP") else ["task"] + for stage in stages: + path = ( + Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" + ) + complete = load_json(path / "complete.json") + evaluation = load_json(path / "evaluation/evaluation-complete.json") + if complete["checkpoint_sha256"] != evaluation["checkpoint_sha256"]: + raise ValueError("Checkpoint/evaluation hash disagreement") + endpoint_id = f"world-{world}-{condition}-{stage}" + tasks = ATTRS if stage == "adapt" else TASKS + cot = stage == "task" and condition == "MP-CoT" + selected = read_selected_batches( + path / "evaluation/predictions.jsonl", + audit_batches(people, tasks, cot, plan["audit_batch_size"]), + plan["audit_batch_size"], + ) + sample = root / "audit-inputs" / f"{endpoint_id}.json" + write_json(sample, selected) + plan["endpoints"].append( + dict( + id=endpoint_id, + world=world, + init=init, + condition=condition, + stage=stage, + checkpoint=str(path / "final.pt"), + checkpoint_sha256=complete["checkpoint_sha256"], + audit_sample=str(sample), + audit_sample_sha256=digest(sample), + ) + ) + write_json(root / "plan.json", plan) + return plan + + +def verify_plan(plan): + for path, sha in plan["source_sha256"].items(): + if digest(path) != sha: + raise ValueError(f"Frozen diagnostic source changed: {path}") + for data in plan["worlds"].values(): + if digest(data["people_path"]) != data["sha256"]: + raise ValueError("People data changed") + + +def run_audit(model, tok, endpoint, plan, output, device): + sample = Path(endpoint["audit_sample"]) + if digest(sample) != endpoint["audit_sample_sha256"]: + raise ValueError("Audit inputs changed") + report = [] + for batch in load_json(sample): + rows = [r["load_json_line"] for r in batch["rows"]] + encoded = [encode_row(tok, r["prompt"], r["answer"]) for r in rows] + with torch.no_grad(), amp(device): + avg, full = sequence_scores(model, encoded, device) + generated, ended = generate( + model, tok, [r["prompt"] for r in rows], device, plan["max_new_tokens"] + ) + for original, text, eos, mean_lp, full_lp in zip( + batch["rows"], generated, ended, avg.tolist(), full.tolist(), strict=True + ): + old = original["load_json_line"] + extracted = text.rsplit("Answer:", 1)[-1].strip() if old["cot"] else text + report.append( + dict( + source_row=original["source_row"], + physical_batch_start=batch["start"], + original=old, + reloaded_generated=text, + reloaded_eos=eos, + generated_identical=text == old["generated"], + eos_identical=eos == old["eos"], + correctness_identical=(normalize(extracted) == normalize(old["answer"])) + == old["correct"], + mean_logp_difference=mean_lp - old["answer_mean_logp"], + full_logp_difference=full_lp - old["answer_full_logp"], + ) + ) + write_json(output / "audit-rows.json", report) + summary = dict( + rows=len(report), + generation_mismatches=sum(not r["generated_identical"] for r in report), + eos_mismatches=sum(not r["eos_identical"] for r in report), + correctness_mismatches=sum(not r["correctness_identical"] for r in report), + max_abs_full_logp_difference=max(abs(r["full_logp_difference"]) for r in report), + exact_original_batch=True, + precision="FP32 parameters, BF16 autocast, TF32 enabled", + ) + summary["status"] = ( + "passed" + if all( + summary[k] == 0 + for k in ("generation_mismatches", "eos_mismatches", "correctness_mismatches") + ) + and summary["max_abs_full_logp_difference"] <= 1e-4 + else "discrepancy" + ) + write_json(output / "audit-summary.json", summary) + return summary + + +def generate_rows(model, tok, rows, plan, device): + for start in range(0, len(rows), plan["diagnostic_batch_size"]): + batch = rows[start : start + plan["diagnostic_batch_size"]] + outputs, ended = generate( + model, tok, [r["prompt"] for r in batch], device, plan["max_new_tokens"] + ) + for row, text, eos in zip(batch, outputs, ended, strict=True): + row.update(generated=text, eos=eos) + print( + json.dumps( + dict(generation_done=min(start + len(batch), len(rows)), generation_total=len(rows)) + ), + flush=True, + ) + + +def run_diagnostics(model, tok, endpoint, plan, output, device): + world = plan["worlds"][str(endpoint["world"])] + people = load_json(world["people_path"]) + selected = [people[i] for i in world["person_ids"]] + extraction = [ + dict(person_id=p["id"], view=v, prompt=question(p, "date", v), target=date(p)) + for p in selected + for v in plan["views"] + ] + generate_rows(model, tok, extraction, plan, device) + lookup = {} + for row in extraction: + row.update( + parseable=parse_date(row["generated"]) is not None, + correct=normalize(row["generated"]) == normalize(row["target"]), + ) + lookup[row["person_id"], row["view"]] = row + write_json(output / "extractions.json", extraction) + rows = [] + for p in selected: + other = people[p["partner"]] + for task in TASK_PAIR: + for view in plan["views"]: + base = dict( + person_id=p["id"], + partner=other["id"], + view=view, + task=task, + target=answer(p, task, other), + ) + for cot in (False, True): + rows.append( + dict( + base, + mode="cot" if cot else "direct", + prompt=question(p, task, view, other, cot), + cot_trained=endpoint["condition"] == "MP-CoT", + ) + ) + for mode in ("oracle_rule", "autonomous_rule"): + a = date(p) if mode == "oracle_rule" else lookup[p["id"], view]["generated"] + b = ( + date(other) + if mode == "oracle_rule" + else lookup[other["id"], view]["generated"] + ) + parsed = parse_date(a) is not None and ( + task != "comparison" or parse_date(b) is not None + ) + valid = normalize(a) == normalize(date(p)) and ( + task != "comparison" or normalize(b) == normalize(date(other)) + ) + symbolic = symbolic_operation(task, a, b, (p["name"], other["name"])) + rows.append( + dict( + base, + mode=mode, + prompt=operation_prompt(task, a, b), + supplied_dates=[a, b] if task == "comparison" else [a], + inputs_parseable=parsed, + inputs_correct=valid, + symbolic_prediction=symbolic, + symbolic_correct=symbolic is not None + and normalize(symbolic) == normalize(base["target"]), + ) + ) + generate_rows(model, tok, rows, plan, device) + totals = defaultdict(lambda: defaultdict(int)) + for row in rows: + p, other = people[row["person_id"]], people[row["partner"]] + if row["mode"] in ("direct", "cot"): + pred = ( + row["generated"].rsplit("Answer:", 1)[-1].strip() + if row["mode"] == "cot" + else row["generated"] + ) + else: + dates = row["supplied_dates"] + pred = decode_operation( + row["task"], + row["generated"], + dates[0], + dates[1] if len(dates) == 2 else None, + (p["name"], other["name"]), + ) + row["prediction"] = pred + row["output_in_question_pair"] = ( + pred is not None and normalize(pred) in (normalize(p["name"]), normalize(other["name"])) + if row["task"] == "comparison" + else None + ) + if row["task"] == "comparison" and row["mode"] in ("oracle_rule", "autonomous_rule"): + row["output_is_supplied_date"] = normalize(row["generated"]) in { + normalize(value) for value in row["supplied_dates"] + } + row["correct"] = pred is not None and normalize(pred) == normalize(row["target"]) + row["correct_with_eos"] = row["correct"] and row["eos"] + key = f"{row['task']}/view-{row['view']}/{row['mode']}" + total = totals[key] + total["n"] += 1 + total["correct"] += row["correct"] + total["correct_with_eos"] += row["correct_with_eos"] + if row["task"] == "comparison": + total["output_in_question_pair"] += row["output_in_question_pair"] + if "output_is_supplied_date" in row: + total["output_is_supplied_date"] += row["output_is_supplied_date"] + if row["mode"] == "autonomous_rule": + for condition in ("inputs_parseable", "inputs_correct"): + total[condition + "_n"] += row[condition] + total[condition + "_correct"] += row[condition] and row["correct"] + total["symbolic_correct"] += row["symbolic_correct"] + with (output / "diagnostics.jsonl").open("w") as stream: + for row in rows: + stream.write(json.dumps(row) + "\n") + summary = dict( + rows=len(rows), + extraction_rows=len(extraction), + extraction_correct=sum(r["correct"] for r in extraction), + extraction_parseable=sum(r["parseable"] for r in extraction), + totals=dict(totals), + people=len(selected), + independent_partner_pairs=len(selected) // 2, + split="development", + no_training=True, + limitations=[ + "Oracle and autonomous rules use externally supplied text and a changed prompt.", + "Non-MP-CoT models did not train on the CoT instruction.", + "Host date-to-name mapping and symbolic ceilings are not model reasoning.", + "Twenty-four people are a fixed diagnostic subset, not population estimates.", + ], + ) + write_json(output / "diagnostic-summary.json", summary) + return summary + + +def run_endpoint(root, endpoint_id, device="cuda:0", memory_fraction=0.045): + root = Path(root) + plan = load_json(root / "plan.json") + verify_plan(plan) + endpoint = next(e for e in plan["endpoints"] if e["id"] == endpoint_id) + output = root / "endpoints" / endpoint_id + if (output / "complete.json").exists(): + return load_json(output / "complete.json") + output.mkdir(parents=True, exist_ok=True) + if digest(endpoint["checkpoint"]) != endpoint["checkpoint_sha256"]: + raise ValueError("Checkpoint changed") + cfg = plan["config"] + setup(endpoint["init"], device) + if str(device).startswith("cuda"): + torch.cuda.set_per_process_memory_fraction(memory_fraction, device) + torch.cuda.reset_peak_memory_stats(device) + tok_path = Path(cfg["data_root"]) / "tokenizer/tokenizer.json" + if digest(tok_path) != plan["tokenizer_sha256"]: + raise ValueError("Tokenizer changed") + tok = Tokenizer.from_file(str(tok_path)) + start = time.monotonic() + model = load_model(endpoint["checkpoint"], cfg, device, adapters=True).eval() + model.requires_grad_(False) + write_json( + output / "running.json", + dict( + endpoint=endpoint_id, + started_unix=time.time(), + pid=os.getpid(), + device=device, + cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), + memory_fraction=memory_fraction, + shared_gpu=True, + torch_version=torch.__version__, + ), + ) + audit = run_audit(model, tok, endpoint, plan, output, device) + diagnostics = ( + run_diagnostics(model, tok, endpoint, plan, output, device) + if endpoint["stage"] == "task" + else None + ) + result = dict( + endpoint=endpoint, + seconds=time.monotonic() - start, + audit=audit, + diagnostics=diagnostics, + shared_gpu=True, + memory_fraction=memory_fraction, + cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), + peak_allocated_bytes=torch.cuda.max_memory_allocated(device) + if str(device).startswith("cuda") + else None, + ) + write_json(output / "complete.json", result) + return result diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_model.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_model.py new file mode 100644 index 0000000000000000000000000000000000000000..039ceaef72cf7fefa38bb094dbefbe9f7e88d651 --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_model.py @@ -0,0 +1,130 @@ +"""GPT-2 blocks, quarter-head NeoX RoPE, tied vocabulary, explicit Q/V/embedding LoRA.""" + +from __future__ import annotations + +import math + +import torch +from torch import nn +from torch.nn import functional as F + + +class Attention(nn.Module): + def __init__(self, cfg): + super().__init__() + width = cfg["width"] + self.heads = cfg["heads"] + self.dim = width // self.heads + self.rotary_dim = int(self.dim * cfg["rotary_fraction"]) + assert self.rotary_dim % 2 == 0 and self.rotary_dim > 0 + self.qkv = nn.Linear(width, 3 * width) + self.out = nn.Linear(width, width) + freq = 1.0 / ( + cfg["rotary_base"] ** (torch.arange(0, self.rotary_dim, 2).float() / self.rotary_dim) + ) + angle = torch.outer(torch.arange(cfg["context"]).float(), freq) + angle = torch.cat((angle, angle), dim=-1)[None, None] + self.register_buffer("cos", angle.cos(), persistent=False) + self.register_buffer("sin", angle.sin(), persistent=False) + self.dropout = cfg["dropout"] + self.rank = 0 + + def add_lora(self, rank): + self.rank = rank + width = self.heads * self.dim + self.q_a = nn.Parameter(torch.randn(rank, width) * 0.02) + self.q_b = nn.Parameter(torch.zeros(width, rank)) + self.v_a = nn.Parameter(torch.randn(rank, width) * 0.02) + self.v_b = nn.Parameter(torch.zeros(width, rank)) + + def rotate(self, x): + z, tail = x[..., : self.rotary_dim], x[..., self.rotary_dim :] + half = self.rotary_dim // 2 + swapped = torch.cat((-z[..., half:], z[..., :half]), dim=-1) + size = x.shape[-2] + z = z * self.cos[:, :, :size].to(x.dtype) + swapped * self.sin[:, :, :size].to(x.dtype) + return torch.cat((z, tail), dim=-1) + + def forward(self, x): + b, t, width = x.shape + q, k, v = self.qkv(x).chunk(3, dim=-1) + if self.rank: + q = q + F.linear(F.linear(x, self.q_a), self.q_b) + v = v + F.linear(F.linear(x, self.v_a), self.v_b) + q, k, v = [z.view(b, t, self.heads, self.dim).transpose(1, 2) for z in (q, k, v)] + y = F.scaled_dot_product_attention( + self.rotate(q), + self.rotate(k), + v, + is_causal=True, + dropout_p=self.dropout if self.training else 0, + ) + return self.out(y.transpose(1, 2).contiguous().view(b, t, width)) + + +class Block(nn.Module): + def __init__(self, cfg): + super().__init__() + width = cfg["width"] + self.ln1, self.ln2 = nn.LayerNorm(width), nn.LayerNorm(width) + self.attn = Attention(cfg) + self.up, self.down = nn.Linear(width, 4 * width), nn.Linear(4 * width, width) + self.dropout = nn.Dropout(cfg["dropout"]) + + def forward(self, x): + x = x + self.dropout(self.attn(self.ln1(x))) + return x + self.dropout(self.down(F.gelu(self.up(self.ln2(x)), approximate="tanh"))) + + +class GPT(nn.Module): + def __init__(self, cfg): + super().__init__() + self.cfg = cfg + self.embedding = nn.Embedding(cfg["vocab_size"], cfg["width"]) + self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg["layers"])]) + self.norm = nn.LayerNorm(cfg["width"]) + self.dropout = nn.Dropout(cfg["dropout"]) + self.embedding_rank = 0 + self.apply(self._init) + for block in self.blocks: + nn.init.normal_(block.attn.out.weight, std=0.02 / math.sqrt(2 * cfg["layers"])) + nn.init.normal_(block.down.weight, std=0.02 / math.sqrt(2 * cfg["layers"])) + + @staticmethod + def _init(module): + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, std=0.02) + if isinstance(module, nn.Linear): + nn.init.zeros_(module.bias) + + def add_lora(self, qv_rank, embedding_rank): + self.requires_grad_(False) + for b in self.blocks: + b.attn.add_lora(qv_rank) + self.embedding_rank = embedding_rank + self.emb_a = nn.Parameter(torch.randn(self.cfg["vocab_size"], embedding_rank) * 0.02) + self.emb_b = nn.Parameter(torch.zeros(embedding_rank, self.cfg["width"])) + + def hidden(self, ids): + x = self.embedding(ids) + if self.embedding_rank: + x = x + F.embedding(ids, self.emb_a) @ self.emb_b + x = self.dropout(x) + for block in self.blocks: + x = block(x) + return self.norm(x) + + def logits(self, hidden): + # Preserve input/output tying also for the embedding update. + logits = F.linear(hidden, self.embedding.weight) + if self.embedding_rank: + logits = logits + F.linear(F.linear(hidden, self.emb_b), self.emb_a) + return logits + + def forward(self, ids, targets=None): + h = self.hidden(ids) + if targets is None: + return self.logits(h) + # Avoid materializing logits at padded/unsupervised positions. + valid = targets != -100 + return F.cross_entropy(self.logits(h[valid]).float(), targets[valid], reduction="mean") diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_report.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_report.py new file mode 100644 index 0000000000000000000000000000000000000000..8aace2494390c65045a2d379beb42695d3b84c8e --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_report.py @@ -0,0 +1,685 @@ +"""Read-only, CPU aggregation of the completed original bioS development run.""" + +from __future__ import annotations + +import csv +import hashlib +import json +import math +import re +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +from llm_memory_editability.bios_original_data import ( + ATTRS, + MONTHS, + TASKS, + answer, + question, +) + +DATE_PATTERN = re.compile( + "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}" +) +DIMENSIONS = ("world", "initialization", "condition", "stage", "split", "task", "view", "cot") +COUNTS = ( + "n", + "correct", + "eos", + "format_recognized", + "correct_eos", + "correct_unrecognized", + "wrong_recognized", + "wrong_unrecognized", + "terminal_answer_match", + "target_text_present", + "city_swap", + "comparison_outside_pair", + "sum_full_logp", + "sum_mean_logp", + "sum_answer_probability", +) + + +def normalize(text): + """Independently reproduce the historical frozen evaluator's normalization.""" + return " ".join(text.strip().rstrip(".").casefold().split()) + + +def extract(row): + text = row["generated"] + return text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text + + +def recognized(text, task, vocabulary): + value = normalize(text) + if task == "parity": + return value in ("yes", "no") + if task == "year": + return bool(re.fullmatch(r"\d{4}", value)) + if task == "date": + return bool(DATE_PATTERN.fullmatch(value)) + if task in ("company_city", "city_company"): + fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") + parts = value.split(";") + return len(parts) == 2 and all( + part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) + ) + return value in vocabulary["name" if task == "comparison" else task] + + +def review_flags(row, person, vocabulary, partner=None): + """Mechanical error labels only; these do not replace the frozen score.""" + text, target = extract(row), normalize(row["answer"]) + correct = normalize(text) == target + form = recognized(text, row["task"], vocabulary) + suffix = row["generated"].rsplit("Answer:", 1)[-1] + terminal = not correct and "Answer:" in row["generated"] and normalize(suffix) == target + # A literal occurrence is an inspection cue, not a semantic-correctness claim. + present = not correct and bool( + re.search(r"(? 1e-5: + raise ValueError(f"Invalid log probability: {path}:{line_number}") + cell[target] += value + cell["sum_answer_probability"] += math.exp(row["answer_full_logp"]) + for category in ( + "terminal_answer_match", + "target_text_present", + "city_swap", + "comparison_outside_pair", + "wrong_recognized", + "wrong_unrecognized", + "correct_unrecognized", + ): + sample_key = (row["task"], row["view"] == 0, row["cot"], category) + if flags[category] and sample_counts[sample_key] < 2: + sample_counts[sample_key] += 1 + examples.append( + dict( + **meta, + category=category, + source=str(path), + line=line_number, + **row, + review_status="deterministic inspection sample; not human-labelled", + ) + ) + expected_cells = len(cfg["evaluation"]["splits"]) * len(tasks) * 6 * len(modes) + if len(cells) != expected_cells or len(completion["totals"]) != expected_cells: + raise ValueError(f"Incomplete evaluation cell matrix: {path}") + counts = Counter(p["split"] for p in people) + for (split, task, view, cot), cell in cells.items(): + if cell["n"] != counts[split]: + raise ValueError(f"Incomplete population: {path}: {split}/{task}/{view}/{cot}") + old = completion["totals"][f"{split}/{task}/view-{view}/cot-{cot}"] + if any(cell[k] != old[k] for k in ("n", "correct", "format_recognized")): + raise ValueError(f"Historical totals mismatch: {path}") + if not math.isclose(cell["sum_full_logp"], old["sum_full_logp"], abs_tol=1e-8): + raise ValueError(f"Historical logp total mismatch: {path}") + checks["cells_population_and_historical_totals_verified"] += 1 + provenance = dict( + **meta, + path=str(path), + sha256=digest.hexdigest(), + bytes=path.stat().st_size, + checkpoint_sha256=completion["checkpoint_sha256"], + checks=dict(checks), + completion_sha256=hashlib.sha256(completion_path.read_bytes()).hexdigest(), + ) + conditional = conditional_rows(seen, people, meta, modes) if meta["stage"] == "task" else [] + return [finalized(v) for v in cells.values()], examples, provenance, conditional + + +def pretrain_rows(cfg): + curves, inventory = [], [] + for world in cfg["world_seeds"]: + for init in cfg["initialization_seeds"]: + for condition in cfg["pretrain"]["conditions"]: + root = Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/pretrain" + path = root / "metrics.jsonl" + metrics = [json.loads(line) for line in path.read_text().splitlines()] + expected = list(range(1, cfg["pretrain"]["passes"] + 1)) + if [r["passes"] for r in metrics] != expected: + raise ValueError(f"Incomplete pretraining curve: {path}") + for row in metrics: + curves.append( + dict(world=world, initialization=init, condition=condition, **row) + ) + inventory.append( + dict( + world=world, + initialization=init, + condition=condition, + path=str(path), + sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + passes=len(metrics), + final_nll=metrics[-1]["nll"], + nodes=[ + dict(passes=n, checkpoint_exists=(root / f"pass-{n:03d}.pt").exists()) + for n in cfg["pretrain"]["nodes"] + ], + ) + ) + return curves, inventory + + +def paired_differences(groups): + pairs = [("S", "M"), ("M", "MP"), ("MP", "MP-R"), ("MP-R", "MP-Random"), ("MP", "MP-CoT")] + lookup = {} + for row in groups: + key = tuple( + row[k] + for k in ("world", "initialization", "stage", "split", "task", "view_group", "cot") + ) + lookup.setdefault(key, {})[row["condition"]] = row + rows = [] + for key, conditions in lookup.items(): + for left, right in pairs: + if left not in conditions or right not in conditions: + continue + a, b = conditions[left], conditions[right] + if a["n"] != b["n"]: + raise ValueError("Unequal paired populations") + rows.append( + dict( + **dict( + zip( + ( + "world", + "initialization", + "stage", + "split", + "task", + "view_group", + "cot", + ), + key, + strict=True, + ) + ), + left=left, + right=right, + n_each=a["n"], + left_accuracy=a["correct_rate"], + right_accuracy=b["correct_rate"], + difference_pp=100 * (b["correct_rate"] - a["correct_rate"]), + ) + ) + return rows + + +def make_plots(output, curves, groups): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, axes = plt.subplots(1, 2, figsize=(11, 4)) + for world in sorted({r["world"] for r in curves}): + for c, color in zip(("S", "M", "MP"), ("#9b5f1b", "#4477aa", "#228833"), strict=True): + subset = [r for r in curves if r["world"] == world and r["condition"] == c] + axes[0].plot( + [r["passes"] for r in subset], + [r["nll"] for r in subset], + color=color, + alpha=0.8, + label=f"{c}, world {world}", + ) + axes[0].set(xlabel="Biography exposures per person", ylabel="Training NLL", yscale="log") + axes[0].legend(fontsize=7) + for offset, view, color in [(-0.17, "canonical", "#4477aa"), (0.17, "heldout", "#cc6677")]: + means = [] + for c in ("S", "M", "MP"): + data = [ + r["correct_rate"] + for r in groups + if r["stage"] == "adapt" + and r["split"] == "test" + and r["condition"] == c + and r["view_group"] == view + and r["family"] == "six_attributes" + ] + means.append(100 * sum(data) / len(data)) + axes[1].bar([i + offset for i in range(3)], means, width=0.32, label=view, color=color) + axes[1].set( + xticks=range(3), + xticklabels=("S", "M", "MP"), + ylabel="QA extraction accuracy (%)", + ylim=(0, 105), + ) + axes[1].legend() + fig.suptitle("Original bioS development: training fit and later QA extraction") + fig.tight_layout() + for suffix in ("png", "pdf"): + fig.savefig(output / f"bios-pretrain-and-extraction.{suffix}", dpi=160) + plt.close(fig) + + +def report_text(overall, groups, endpoints): + def mean(rows, field="correct_rate"): + # Exactly one initialization per world in this development configuration. + per_world = {} + for row in rows: + per_world.setdefault(row["world"], []).append(row[field]) + values = [sum(v) / len(v) for v in per_world.values()] + return 100 * sum(values) / len(values) if values else float("nan") + + def select(rows, **conditions): + return [r for r in rows if all(r[k] == v for k, v in conditions.items())] + + lines = [ + "# 原版 bioS 开发预测复盘", + "", + "本报告独立复算两开发世界的 570 万条既有预测、18 个评价端点与全部 3240 个预训练" + "日志节点。没有新增训练、GPU 前向或更改历史预测。原始评分与完成文件逐单元一致。", + "", + "表中百分比先在每个世界内汇总,再对两个世界等权;这是开发结果,无新增独立确认。" + "同一人物的五个留出问法,以及同一比较人物对的两个问序,属于重复测量。", + "", + "## 六属性 QA 提取", + "", + "| BIO 条件 | 规范问法 | 五个留出问法均值 |", + "| --- | ---: | ---: |", + ] + for condition in ("S", "M", "MP"): + values = [ + mean( + select( + overall, + stage="adapt", + split="test", + condition=condition, + family="six_attributes", + view_group=v, + cot=False, + ) + ) + for v in ("canonical", "heldout") + ] + lines.append(f"| {condition} | {values[0]:.2f}% | {values[1]:.2f}% |") + lines += [ + "", + "S/M/MP 使用相同人物与语义事实曝光;M 增加表述,MP 再重排句序。" + "QA 适配使用训练人物,测试人物只参加 BIO 预训练。这里测的是经共同 QA 适配后的提取," + "不能称为预训练终点未经适配的问答表现。工作城市已出现于传记,属于提取任务。", + "", + "## 任务适配后的规范问法", + "", + "| 模型 / 推理方式 | 日期 | 年份 | 月份奇偶 | 出生早晚比较 |", + "| --- | ---: | ---: | ---: | ---: |", + ] + for condition, cot in [ + ("MP", False), + ("MP-R", False), + ("MP-Random", False), + ("MP-CoT", False), + ("MP-CoT", True), + ]: + values = [ + mean( + select( + groups, + stage="task", + split="test", + condition=condition, + view_group="canonical", + cot=cot, + task=task, + ) + ) + for task in ("date", "year", "parity", "comparison") + ] + mode = "CoT" if cot else "直接" + lines.append(f"| {condition} / {mode} | " + " | ".join(f"{v:.2f}%" for v in values) + " |") + lines += [ + "", + "年份和奇偶需要从已知属性执行操作,不能与六属性提取的平均值混为一项。" + "MP-CoT 的两种推理方式使用同一适配端点,但解释提示、监督格式及输出计算不同。" + "MP-R 的收益须与匹配的 MP-Random 同时检查。", + "", + "## 错误与计分审阅", + "", + ] + for condition, cot in (("MP", False), ("MP-CoT", True)): + value = mean( + select( + groups, + stage="task", + split="test", + condition=condition, + view_group="canonical", + cot=cot, + task="comparison", + ), + "comparison_outside_pair_rate", + ) + lines.append( + f"- {condition} / {'CoT' if cot else '直接'} 的比较输出中," + f"{value:.2f}% 未精确返回问题中任一人的名字;这不能只解释为日期运算错误。" + ) + suffix = mean( + select( + groups, + stage="task", + split="test", + condition="MP-CoT", + view_group="heldout", + cot=False, + task="date", + ), + "terminal_answer_match_rate", + ) + lines += [ + f"- MP-CoT 直接作答的留出日期问法中,{suffix:.2f}% 的全量输出虽未通过冻结评分," + "最后一个 `Answer:` 后恰为目标日期。这是可复核的格式失分,保留为事后辅助统计;" + "没有改写主分数。", + "- `wrong_recognized` 只表示输出满足原格式规则但不等于标签;" + "`target_text_present` 只表示原输出出现目标文字,不认定语义正确。" + "城市互换与问题外人名由已知人物表确定。", + "- `error-review-samples.jsonl` 按任务、问法组、模式、错误标签保存最先两条," + "是确定性审阅样本,不是错误率的随机估计,也不是全量人工语义标注。", + "- CoT 的历史 `answer_full_logp` 是解释提示后直接接短答案的概率," + "不是所生成推理链或最终答案的概率,不用于判断 CoT 是否掌握知识。", + "- `conditional-task-scores.csv` 在同一人物、相同问法和输出模式下检查源属性是否答对;" + "比较题要求两个人的日期都答对。它是条件子集分析,覆盖率与全量分数同时保留," + "不等同于把模型自产属性重新输入后的两次调用实验。", + "", + "## 预训练曲线与剩余工作", + "", + "`pretrain-curves.csv` 与图保留六条各 540 次曝光的训练 NLL。不同数据条件的文本" + "可预测性不同,NLL 不能当作统一知识量刻度。已保存权重节点存在不等于已测出各节点的" + "知识/推理能力;当前没有这样的语义学习曲线。", + "", + "本 CPU 报告没有完成独立权重重载、oracle 属性输入或自主提取后运算;" + "100k 正式矩阵与日期编辑也未执行。它们的后续结果应写入独立产物。", + "", + "复现:`PYTHONPATH=src .venv/bin/python scripts/report_bios_original.py`。" + "原预测、配置、数据及报告源码哈希见 `audit.json`。", + "", + f"已核验端点:{len(endpoints)};完整单元表 `cells.csv`,按任务与问法组汇总" + " `task-view-groups.csv`,世界内配对差 `paired-world-differences.csv`。", + ] + return "\n".join(lines) + "\n" + + +def run_report(config_path, output): + cfg = json.loads(config_path.read_text()) + output.mkdir(parents=True, exist_ok=True) + cells, examples, endpoints, conditional = [], [], [], [] + for world in cfg["world_seeds"]: + people_path = Path(cfg["data_root"]) / f"world-{world}/people.json" + people = json.loads(people_path.read_text()) + if [p["id"] for p in people] != list(range(cfg["people"])): + raise ValueError("People index contract changed") + for init in cfg["initialization_seeds"]: + for stage, conditions in ( + ("adapt", cfg["pretrain"]["conditions"]), + ("task", cfg["task"]["conditions"]), + ): + for condition in conditions: + meta = dict(world=world, initialization=init, condition=condition, stage=stage) + root = ( + Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" + ) + a, b, c, d = read_endpoint(root, meta, cfg, people) + cells.extend(a) + examples.extend(b) + endpoints.append(c) + conditional.extend(d) + print( + json.dumps(dict(**meta, rows=sum(r["n"] for r in a), status="verified")), + flush=True, + ) + groups = rollup(cells, views=True) + overall = overall_rows(groups) + curves, inventory = pretrain_rows(cfg) + write_csv(output / "cells.csv", cells) + write_csv(output / "task-view-groups.csv", groups) + write_csv(output / "overall.csv", overall) + write_csv(output / "paired-world-differences.csv", paired_differences(groups)) + write_csv(output / "conditional-task-scores.csv", conditional) + write_csv(output / "pretrain-curves.csv", curves) + with (output / "error-review-samples.jsonl").open("w") as stream: + for example in examples: + stream.write(json.dumps(example, ensure_ascii=False) + "\n") + save_json( + output / "audit.json", + dict( + created_at_utc=datetime.now(timezone.utc).isoformat(), + scope="CPU predictions/logs audit; no checkpoint reload or GPU inference", + config=str(config_path), + config_sha256=hashlib.sha256(config_path.read_bytes()).hexdigest(), + raw_prediction_rows=sum(r["n"] for r in cells), + endpoint_count=len(endpoints), + cells=len(cells), + pretraining_runs=len(inventory), + pretrain_nodes=len(curves), + endpoints=endpoints, + pretrain=inventory, + failures=[], + sources=[ + dict(path=str(p), sha256=hashlib.sha256(p.read_bytes()).hexdigest()) + for p in ( + Path(__file__), + Path("scripts/report_bios_original.py"), + Path("src/llm_memory_editability/bios_original_data.py"), + Path("src/llm_memory_editability/bios_original_train.py"), + *[ + Path(cfg["data_root"]) / f"world-{w}/people.json" + for w in cfg["world_seeds"] + ], + ) + ], + missing_scientific_deliverables=[ + "Independent GPU checkpoint reload remains unverified by this CPU report", + "Oracle-input and extract-then-operate inference are absent from these inputs", + "Pretraining semantic trajectories absent; existing curve is training NLL only", + "Sampled output inspection is separate from exhaustive human semantic adjudication", + ], + ), + ) + save_json( + output / "summary.json", + dict( + development_worlds=cfg["world_seeds"], + independent_worlds=len(cfg["world_seeds"]), + test_overall=[r for r in overall if r["split"] == "test"], + probability_caveat=( + "CoT logp scores the short gold answer immediately after the explanation prompt; " + "it is not the probability of the generated CoT or its final answer." + ), + scoring=( + "Historical answer EM; EOS is reported independently. Views and paired " + "comparison orientations are repeated measurements, not independent worlds." + ), + ), + ) + make_plots(output, curves, overall) + (output / "report.md").write_text(report_text(overall, groups, endpoints)) + return overall diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_train.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_train.py new file mode 100644 index 0000000000000000000000000000000000000000..eea8f0449758025224fd3bb37444cc7e54e7ef7c --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_original_train.py @@ -0,0 +1,669 @@ +"""Restartable development execution for the original bioS experiment, plan 14.27.""" + +from __future__ import annotations + +import contextlib +import json +import math +import os +import random +import re +import time +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_original_data import ( + ATTRS, + MATERIAL, + MONTHS, + TASKS, + BioStream, + answer, + date, + digest, + load_json, + question, + reasoning, + write_json, +) +from .bios_original_model import GPT + + +def setup(seed, device): + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + torch.set_num_threads(4) + torch.manual_seed(seed) + random.seed(seed) + np.random.seed(seed) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.use_deterministic_algorithms(True) + if str(device).startswith("cuda"): + torch.cuda.set_device(device) + + +def amp(device): + return ( + torch.autocast("cuda", dtype=torch.bfloat16) + if str(device).startswith("cuda") + else contextlib.nullcontext() + ) + + +def append(path, record): + with Path(path).open("a") as out: + out.write(json.dumps(record) + "\n") + + +def atomic_save(path, obj): + path = Path(path) + tmp = path.with_suffix(".tmp") + torch.save(obj, tmp) + tmp.replace(path) + + +def pack_tokens(tokens, context=512): + """Adjacent chunks overlap by the context token only; every target is scored once.""" + n = len(tokens) - 1 + rows = math.ceil(n / context) + x = np.full((rows, context), 50256, dtype=np.int64) + y = np.full((rows, context), -100, dtype=np.int64) + x.flat[:n] = tokens[:-1] + y.flat[:n] = tokens[1:] + return torch.from_numpy(x), torch.from_numpy(y) + + +def optimizer_for(model, settings): + params = [p for p in model.parameters() if p.requires_grad] + groups = [ + dict(params=[p for p in params if p.ndim >= 2], weight_decay=settings["weight_decay"]), + dict(params=[p for p in params if p.ndim < 2], weight_decay=0.0), + ] + return torch.optim.AdamW( + groups, + lr=settings["learning_rate"], + betas=tuple(settings.get("adam_betas", [0.9, 0.999])), + eps=settings.get("adam_epsilon", 1e-6), + fused=next(model.parameters()).is_cuda, + ) + + +def parameter_count(model): + return sum(p.numel() for p in model.parameters()) + + +def pretrain(cfg, world, init, condition, device, stop_after_pass=None): + setup(init, device) + root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / "pretrain" + root.mkdir(parents=True, exist_ok=True) + settings = cfg["pretrain"] + data_root = Path(cfg["data_root"]) / f"world-{world}" + stream = BioStream(data_root, world, condition) + contract = dict( + config=cfg, + world=world, + init=init, + condition=condition, + data_audit_sha256=digest(data_root / "audit.json"), + ) + if (root / "contract.json").exists(): + if load_json(root / "contract.json") != contract: + raise ValueError("Run contract changed; use a new run directory") + else: + write_json(root / "contract.json", contract) + model = GPT(cfg["model"]).to(device) + opt = optimizer_for(model, settings) + start, step, seen, elapsed = 0, 0, 0, 0.0 + latest = root / "latest.pt" + 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"]) + start, step, seen, elapsed = [state[k] for k in ("passes", "step", "tokens", "elapsed")] + del state + elif (root / "metrics.jsonl").exists(): + raise ValueError("Metrics without a resumable checkpoint require investigation") + if (root / "metrics.jsonl").exists(): + kept = [ + line + for line in (root / "metrics.jsonl").read_text().splitlines() + if json.loads(line)["passes"] <= start + ] + (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) + if start == 0 and not (root / "pass-000.pt").exists(): + atomic_save(root / "pass-000.pt", dict(model=model.state_dict(), config=cfg["model"])) + if not latest.exists(): + atomic_save( + latest, + dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + passes=0, + step=0, + tokens=0, + elapsed=0.0, + ), + ) + count = parameter_count(model) + write_json( + root / "model.json", + dict( + parameters=count, + trainable=count, + device=str(device), + gpu=torch.cuda.get_device_name(device) if "cuda" in str(device) else "cpu", + torch=torch.__version__, + resume_pass=start, + ), + ) + model.train() + runner = torch.compile(model) if settings.get("compile") else model + wall = time.monotonic() + for epoch in range(start, min(settings["passes"], stop_after_pass or settings["passes"])): + pass_start = time.monotonic() + tokens, order_hash = stream.pass_tokens(epoch) + xs, ys = pack_tokens(tokens, cfg["model"]["context"]) + total_loss, valid_tokens = 0.0, 0 + batch = settings["batch_size"] + micro = settings["micro_batch_size"] + for i in range(0, len(xs), batch): + # Learning rate follows complete-person exposure; no outcome-based stopping. + progress = (epoch + i / len(xs)) / settings["passes"] + cosine = ( + settings["minimum_lr_ratio"] + + (1 - settings["minimum_lr_ratio"]) * (1 + math.cos(math.pi * progress)) / 2 + ) + lr = ( + settings["learning_rate"] + * cosine + * min(1, (step + 1) / max(1, settings["warmup_steps"])) + ) + for group in opt.param_groups: + group["lr"] = lr + opt.zero_grad(set_to_none=True) + end = min(i + batch, len(xs)) + denom = int((ys[i:end] != -100).sum()) + batch_loss = 0.0 + for j in range(i, end, micro): + x, y = ( + xs[j : min(j + micro, end)].to(device), + ys[j : min(j + micro, end)].to(device), + ) + n = int((y != -100).sum()) + with amp(device): + loss = runner(x, y) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite loss at pass {epoch}, step {step}") + (loss * (n / denom)).backward() + batch_loss += loss.detach().item() * n + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), settings["gradient_clip"]) + if not torch.isfinite(norm): + raise FloatingPointError(f"Nonfinite gradient at step {step}") + opt.step() + step += 1 + total_loss += batch_loss + valid_tokens += denom + if step % 10 == 0: + write_json( + root / "status.json", + dict( + state="running", + passes_completed=epoch, + pass_fraction=end / len(xs), + step=step, + learning_rate=lr, + last_batch_nll=batch_loss / denom, + tokens=seen + valid_tokens, + elapsed=elapsed + time.monotonic() - wall, + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + assert valid_tokens == len(tokens) - 1 + seen += valid_tokens + duration = time.monotonic() - pass_start + record = dict( + passes=epoch + 1, + people_presented=(epoch + 1) * stream.count, + tokens=seen, + pass_tokens=valid_tokens, + nll=total_loss / valid_tokens, + seconds=duration, + tokens_per_second=valid_tokens / duration, + step=step, + learning_rate=lr, + presentation_sha256=order_hash, + estimated_training_flops=6 * count * seen, + elapsed=elapsed + time.monotonic() - wall, + ) + append(root / "metrics.jsonl", record) + print(json.dumps(record), flush=True) + if epoch + 1 in settings["nodes"]: + atomic_save( + root / f"pass-{epoch + 1:03d}.pt", + dict(model=model.state_dict(), config=cfg["model"], metrics=record), + ) + if (epoch + 1) % 10 == 0 or epoch + 1 == stop_after_pass or epoch + 1 == settings["passes"]: + atomic_save( + latest, + dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + passes=epoch + 1, + step=step, + tokens=seen, + elapsed=elapsed + time.monotonic() - wall, + ), + ) + write_json( + root / "status.json", + dict( + state="complete" if epoch + 1 == settings["passes"] else "running", + passes_completed=epoch + 1, + **record, + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + return root / f"pass-{settings['passes']:03d}.pt" + + +def encode_row(tokenizer, prompt, target): + prefix = tokenizer.encode(prompt).ids + suffix = tokenizer.encode(" " + target).ids + [50256] + return dict(ids=prefix + suffix, answer_start=len(prefix)) + + +def supervised_batch(rows, device): + width = max(len(r["ids"]) for r in rows) - 1 + x = torch.full((len(rows), width), 50256, dtype=torch.long, device=device) + y = torch.full_like(x, -100) + for i, r in enumerate(rows): + ids = torch.tensor(r["ids"], device=device) + x[i, : len(ids) - 1] = ids[:-1] + y[i, r["answer_start"] - 1 : len(ids) - 1] = ids[r["answer_start"] :] + return x, y + + +def sequence_scores(model, rows, device): + x, y = supervised_batch(rows, device) + h = model.hidden(x) + b, t = torch.where(y != -100) + losses = F.cross_entropy(model.logits(h[b, t]).float(), y[b, t], reduction="none") + sums = torch.zeros(len(rows), device=device).scatter_add_(0, b, losses) + sizes = torch.bincount(b, minlength=len(rows)) + return -sums / sizes, -sums + + +def task_rows(people, tokenizer, tasks, condition, epoch, seed): + rng = random.Random(seed) + # Use the published label vocabulary, independent of held-out person attributes. + cities = sorted( + set((MATERIAL / "fields/city.txt").read_text().splitlines()) + | { + line.split(";", 1)[1].strip() + for line in (MATERIAL / "fields/company.txt").read_text().splitlines() + } + ) + bins = defaultdict(list) + for city in cities: + bins[len(tokenizer.encode(" " + city).ids)].append(city) + rows = [] + for p in people: + if p["split"] != "train": + continue + other = people[p["partner"]] + for j, task in enumerate(tasks): + cot = condition == "MP-CoT" and (p["id"] + j + epoch) % 2 == 0 + prompt = question(p, task, other=other, cot=cot) + target = reasoning(p, task, other) if cot else answer(p, task, other) + row = encode_row(tokenizer, prompt, target) + row.update(person_id=p["id"], task=task, cot=cot) + if task in ("birthcity", "workcity") and p["birthcity"] != p["workcity"]: + competing = p["workcity"] if task == "birthcity" else p["birthcity"] + candidates = [ + c + for c in bins[len(tokenizer.encode(" " + competing).ids)] + if c not in (p["birthcity"], p["workcity"]) + ] + if not candidates: + raise ValueError( + "No length-matched random city; cannot silently relax matching" + ) + negative = rng.choice(candidates) if condition == "MP-Random" else competing + row["negative"] = encode_row(tokenizer, prompt, negative) + rows.append(row) + return rows + + +def rule_rows(tokenizer): + rows = [] + for m, name in enumerate(MONTHS, 1): + rows.append( + encode_row( + tokenizer, + f"Question: Is {name} an even-numbered month?\nAnswer:", + "yes" if m % 2 == 0 else "no", + ) + ) + rng = random.Random(14270000) + for i in range(24): + a, b = [ + dict( + year=rng.randrange(1900, 2100), month=rng.randrange(1, 13), day=rng.randrange(1, 29) + ) + for _ in range(2) + ] + if i % 2: + a, b = ( + max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + ) + else: + a, b = ( + min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + ) + rows.append( + encode_row( + tokenizer, + f"Question: Which date is earlier, {date(a)} or {date(b)}?\nAnswer:", + date(b if i % 2 else a), + ) + ) + return rows + + +def load_model(path, cfg, device, adapters=False): + model = GPT(cfg["model"]) + if adapters: + model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) + state = torch.load(path, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + return model.to(device) + + +def finetune(cfg, world, init, condition, stage, parent, device, tokenizer): + setup(init + 1, device) + root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / stage + root.mkdir(parents=True, exist_ok=True) + people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") + contract = dict( + config=cfg, + world=world, + init=init, + condition=condition, + stage=stage, + parent=str(parent), + parent_sha256=digest(parent), + ) + if (root / "contract.json").exists() and load_json(root / "contract.json") != contract: + raise ValueError("Finetuning contract changed") + write_json(root / "contract.json", contract) + if (root / "complete.json").exists(): + return root / "final.pt" + model = load_model(parent, cfg, device, adapters=stage == "task") + if stage == "adapt": + model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) + model.to(device) + opt = optimizer_for(model, cfg["adapt"]) + start, step = 0, 0 + if (root / "latest.pt").exists(): + ck = torch.load(root / "latest.pt", map_location=device, weights_only=False) + model.load_state_dict(ck["model"]) + opt.load_state_dict(ck["optimizer"]) + start, step = ck["epoch"], ck["step"] + del ck + if (root / "metrics.jsonl").exists(): + kept = [ + line + for line in (root / "metrics.jsonl").read_text().splitlines() + if json.loads(line)["epoch"] <= start + ] + (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) + write_json( + root / "parameters.json", + dict( + total=parameter_count(model), + trainable=sum(p.numel() for p in model.parameters() if p.requires_grad), + trainable_names=[n for n, p in model.named_parameters() if p.requires_grad], + ), + ) + epochs = cfg[stage]["epochs"] + model.train() + for epoch in range(start, epochs): + rows = task_rows( + people, + tokenizer, + ATTRS if stage == "adapt" else TASKS, + condition if stage == "task" else "MP", + epoch, + world + 1427, + ) + if stage == "task": + rows += rule_rows(tokenizer) * cfg["task"]["rule_repetitions_per_epoch"] + random.Random(world + epoch + 20000000).shuffle(rows) + batch, micro = cfg["adapt"]["batch_size"], cfg["adapt"]["micro_batch_size"] + ce_sum, ranking_sum, candidates, target_tokens = 0.0, 0.0, 0, 0 + wall = time.monotonic() + for i in range(0, len(rows), batch): + group = rows[i : i + batch] + lr = cfg["adapt"]["learning_rate"] * ( + 0.1 + 0.9 * (1 + math.cos(math.pi * (epoch + i / len(rows)) / epochs)) / 2 + ) + for pg in opt.param_groups: + pg["lr"] = lr + opt.zero_grad(set_to_none=True) + for j in range(0, len(group), micro): + part = group[j : j + micro] + with amp(device): + scores, _ = sequence_scores(model, part, device) + ce = -scores.mean() + neg_pairs = [(k, r["negative"]) for k, r in enumerate(part) if "negative" in r] + rank = scores.sum() * 0 + if stage == "task" and neg_pairs: + neg, _ = sequence_scores(model, [r for _, r in neg_pairs], device) + pos = scores[[k for k, _ in neg_pairs]] + # Normalize by all positive rows, including zero collision/non-city terms. + rank = F.softplus(cfg["task"]["margin"] - (pos - neg)).sum() / len(part) + candidates += len(neg_pairs) + coefficient = ( + cfg["task"]["ranking_coefficient"] + if condition in ("MP-R", "MP-Random") and stage == "task" + else 0.0 + ) + loss = ce + coefficient * rank + if not torch.isfinite(loss): + raise FloatingPointError("Nonfinite finetuning loss") + (loss * len(part) / len(group)).backward() + ce_sum += ce.item() * len(part) + ranking_sum += rank.item() * len(part) + target_tokens += sum(len(r["ids"]) - r["answer_start"] for r in part) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(norm): + raise FloatingPointError("Nonfinite finetuning gradient") + opt.step() + step += 1 + if step % 25 == 0: + write_json( + root / "status.json", + dict( + state="running", + epoch=epoch, + fraction=min(i + batch, len(rows)) / len(rows), + step=step, + last_ce=ce.item(), + pid=os.getpid(), + updated_unix=time.time(), + ), + ) + rec = dict( + epoch=epoch + 1, + rows=len(rows), + ce=ce_sum / len(rows), + rank=ranking_sum / len(rows), + scored_negative_candidates=candidates, + target_tokens=target_tokens, + seconds=time.monotonic() - wall, + ) + append(root / "metrics.jsonl", rec) + print(json.dumps(rec), flush=True) + atomic_save( + root / "latest.pt", + dict(model=model.state_dict(), optimizer=opt.state_dict(), epoch=epoch + 1, step=step), + ) + atomic_save(root / "final.pt", dict(model=model.state_dict(), config=cfg["model"])) + write_json( + root / "complete.json", + dict(epochs=epochs, step=step, checkpoint_sha256=digest(root / "final.pt")), + ) + return root / "final.pt" + + +@torch.no_grad() +def generate(model, tokenizer, prompts, device, max_tokens): + # Right padding; each row's final real position supplies its own next token. + sequences = [tokenizer.encode(p).ids for p in prompts] + outputs, finished = [[] for _ in prompts], [False] * len(prompts) + for _ in range(max_tokens): + width = max(map(len, sequences)) + if width > model.cfg["context"]: + break + ids = torch.full((len(prompts), width), 50256, dtype=torch.long, device=device) + for i, seq in enumerate(sequences): + ids[i, : len(seq)] = torch.tensor(seq, device=device) + with amp(device): + h = model.hidden(ids) + last = h[ + torch.arange(len(prompts), device=device), + torch.tensor([len(s) - 1 for s in sequences], device=device), + ] + pred = model.logits(last).argmax(-1).tolist() + for i, token in enumerate(pred): + if not finished[i]: + outputs[i].append(token) + sequences[i].append(token) + finished[i] = token == 50256 + if all(finished): + break + return [tokenizer.decode(ids, skip_special_tokens=True).strip() for ids in outputs], finished + + +def normalize(text): + return " ".join(text.strip().rstrip(".").casefold().split()) + + +def recognized_format(text, task, vocabulary): + value = normalize(text) + if task == "parity": + return value in ("yes", "no") + if task == "year": + return bool(re.fullmatch(r"\d{4}", value)) + if task == "date": + return bool( + re.fullmatch( + "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}", + value, + ) + ) + if task in ("company_city", "city_company"): + parts = value.split(";") + fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") + return len(parts) == 2 and all( + part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) + ) + return value in vocabulary["name" if task == "comparison" else task] + + +@torch.no_grad() +def evaluate(cfg, world, checkpoint, output, device, tokenizer, tasks=TASKS, cot=False): + output = Path(output) + if (output / "evaluation-complete.json").exists(): + if load_json(output / "evaluation-complete.json")["checkpoint_sha256"] != digest( + checkpoint + ): + raise ValueError("Evaluated checkpoint changed") + return + output.mkdir(parents=True, exist_ok=True) + people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") + vocabulary = {field: {normalize(p[field]) for p in people} for field in ("name", *ATTRS[1:])} + model = load_model(checkpoint, cfg, device, adapters=True).eval() + totals = defaultdict(lambda: defaultdict(float)) + batch = [] + with (output / "predictions.jsonl").open("w") as out: + + def flush(): + if not batch: + return + enc = [encode_row(tokenizer, r["prompt"], r["answer"]) for r in batch] + with amp(device): + avg, full = sequence_scores(model, enc, device) + generated, ended = generate( + model, + tokenizer, + [r["prompt"] for r in batch], + device, + cfg["evaluation"]["max_new_tokens"], + ) + for row, text, stop, av, lp in zip( + batch, generated, ended, avg.tolist(), full.tolist(), strict=True + ): + extracted = text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text + correct = normalize(extracted) == normalize(row["answer"]) + # Syntactic recognition is distinct from correctness; retain raw output. + recognized = recognized_format(extracted, row["task"], vocabulary) + row.update( + generated=text, + eos=stop, + correct=correct, + format_recognized=recognized, + answer_mean_logp=av, + answer_full_logp=lp, + ) + out.write(json.dumps(row) + "\n") + key = f"{row['split']}/{row['task']}/view-{row['view']}/cot-{row['cot']}" + t = totals[key] + t["n"] += 1 + t["correct"] += correct + t["format_recognized"] += recognized + t["sum_full_logp"] += lp + batch.clear() + write_json( + output / "evaluation-status.json", + dict( + rows=sum(t["n"] for t in totals.values()), + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + + for p in people: + if p["split"] not in cfg["evaluation"]["splits"]: + continue + other = people[p["partner"]] + for task in tasks: + for view in cfg["evaluation"]["views"]: + for use_cot in [False, True] if cot else [False]: + batch.append( + dict( + person_id=p["id"], + split=p["split"], + task=task, + view=view, + cot=use_cot, + partner=other["id"] if task == "comparison" else None, + prompt=question(p, task, view, other, use_cot), + answer=answer(p, task, other), + ) + ) + if len(batch) == cfg["evaluation"]["batch_size"]: + flush() + flush() + write_json( + output / "evaluation-complete.json", + dict(checkpoint_sha256=digest(checkpoint), totals=dict(totals)), + ) diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_path_diagnostics.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_path_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..219336bcde27c897b81d6c253255dca79eb11d1c --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_path_diagnostics.py @@ -0,0 +1,727 @@ +"""Read-only answer-source diagnostics for the frozen two-chain experiments. + +Matching an answer to a candidate is a behavioral description, not evidence that +the model used that internal path. Multiple matching roles are never tie-broken. +""" + +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, write_json + +LEARNING_ROLES = ("default", "actual", "other_default", "other_actual") +EDIT_ROLES = ( + "new_default", + "new_actual", + "old_default", + "old_actual", + "other_default", + "other_actual", +) +# Codes are shared across files. Role names differ between learning and editing. +NOT_APPLICABLE, TERMINATION_ERROR, OTHER, INDISTINGUISHABLE = -1, 0, 1, 2 +ROLE_CODE_START = 3 + + +def file_sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def classify_answers(prediction, ended, candidates): + """Return exclusive categories plus *all* matched role bits, including overlaps. + + An unfinished generation is a termination error even if its value matches. + Correctness is deliberately separate: a correct answer can have ambiguous roles. + """ + prediction, ended, candidates = map(np.asarray, (prediction, ended, candidates)) + if ( + candidates.ndim != 2 + or prediction.shape != ended.shape + or candidates.shape[0] != len(prediction) + ): + raise ValueError("Incompatible prediction/candidate shapes") + if not 1 <= candidates.shape[1] <= 8: + raise ValueError("Candidate role bitset requires one to eight roles") + matched = prediction[:, None] == candidates + n_matches = matched.sum(axis=1) + bits = (matched.astype(np.uint8) * (1 << np.arange(candidates.shape[1]))).sum(axis=1) + category = np.full(len(prediction), OTHER, dtype=np.int8) + unique = n_matches == 1 + category[unique] = ROLE_CODE_START + matched[unique].argmax(axis=1) + category[n_matches > 1] = INDISTINGUISHABLE + category[~ended.astype(bool)] = TERMINATION_ERROR + return category, bits.astype(np.uint8) + + +def candidate_answers(world, chain, target=None): + """Candidate values for all people, with no dependence on model predictions.""" + other = 1 - chain + old_default = world.answers[world.root_ids[chain, world.memberships[chain]]] + old_actual = world.answers[world.actual_ids[chain]] + current = world.answers if target is None else target + other_default = current[world.root_ids[other, world.memberships[other]]] + other_actual = current[world.actual_ids[other]] + if target is None: + roles = LEARNING_ROLES + values = (old_default, old_actual, other_default, other_actual) + else: + roles = EDIT_ROLES + values = ( + target[world.root_ids[chain, world.memberships[chain]]], + target[world.actual_ids[chain]], + old_default, + old_actual, + other_default, + other_actual, + ) + return roles, np.column_stack(values) + + +def score_saved_arrays(arrays, answers): + prediction, ended = arrays["prediction"], arrays["ended"] + if prediction.shape != answers.shape or ended.shape != answers.shape: + raise ValueError("Saved prediction length differs from truth") + if not np.isin(ended, [False, True]).all(): + raise ValueError("Invalid termination flags") + correct = (prediction == answers) & ended.astype(bool) + if not np.array_equal(correct, arrays["correct"]): + raise ValueError("Saved correctness differs from value-plus-EOS scoring") + return correct + + +def annotate_predictions(world, arrays, target=None): + """Full-query arrays plus candidate matrices aligned with derived_query_ids.""" + answers = world.answers if target is None else target + correct = score_saved_arrays(arrays, answers) + category = np.full(len(answers), NOT_APPLICABLE, dtype=np.int8) + bits = np.zeros(len(answers), dtype=np.uint8) + candidates = [] + for chain in range(2): + roles, values = candidate_answers(world, chain, target) + ids = world.derived_ids[chain] + category[ids], bits[ids] = classify_answers( + arrays["prediction"][ids], arrays["ended"][ids], values + ) + candidates.append(values) + return { + "query_id": np.arange(len(answers), dtype=np.int32), + "prediction": np.asarray(arrays["prediction"], dtype=np.int32), + "ended": np.asarray(arrays["ended"], dtype=bool), + "correct": correct, + "class_code": category, + "matched_role_bits": bits, + "derived_query_ids": world.derived_ids.astype(np.int32), + "candidate_tokens": np.stack(candidates).astype(np.int32), + "candidate_roles": np.array(roles), + } + + +def learning_subsets(world): + """Overlapping diagnostic groups; every row retains its own denominator.""" + yield "all_queries", np.arange(len(world.answers)) + yield "base", np.arange(world.n_base) + yield "independent_attributes", np.flatnonzero(np.isin(world.relation, [3, 4, 5, 6])) + for chain, name in enumerate(CHAINS): + for relation, ids in ( + ("membership", world.membership_ids[chain]), + ("default", world.root_ids[chain]), + ("actual", world.actual_ids[chain]), + ): + yield f"{name}/base/{relation}", ids + for split, ids in ( + ("all", world.derived_ids[chain]), + ("trained", world.train_ids[chain]), + ("heldout", world.heldout_ids[chain]), + ): + yield f"{name}/qa/{split}/all", ids + for label, mask in ( + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + yield ( + f"{name}/qa/{split}/{label}", + np.intersect1d(ids, world.derived_ids[chain, mask]), + ) + + +def editing_subsets(world, pair, chain, target): + yield "E/all", pair["E"] + yield "E/default", np.intersect1d(pair["E"], world.root_ids[chain]) + yield "E/actual", np.intersect1d(pair["E"], world.actual_ids[chain]) + # Membership in the 45-person manipulated cohort differs from factual conflict: + # six old exceptions can also conflict; coherent edits have no *new* conflicts. + actual_conflict = target[world.derived_ids[chain]] != target[world.actual_ids[chain]] + for split, ids in ( + ("all", pair["D"]), + ("trained", np.intersect1d(pair["D"], world.train_ids[chain])), + ("heldout", np.intersect1d(pair["D"], world.heldout_ids[chain])), + ): + yield f"D/{split}/all", ids + for label, group in ( + ("manipulated_conflict_cohort", pair["conflict_D"]), + ("factual_conflict", world.derived_ids[chain, actual_conflict]), + ("no_factual_conflict", world.derived_ids[chain, ~actual_conflict]), + ("old_exception", world.derived_ids[chain, world.exceptions[chain]]), + ("ordinary", world.derived_ids[chain, ~world.exceptions[chain]]), + ): + yield f"D/{split}/{label}", np.intersect1d(ids, group) + for pool_name, pool in ( + ("full", np.flatnonzero(pair["strata"] >= 0)), + ("editor_heldout", pair["heldout"]), + ): + yield f"U/{pool_name}/all", pool + for stratum in range(4): + yield ( + f"U/{pool_name}/stratum_{stratum}", + np.intersect1d(pool, np.flatnonzero(pair["strata"] == stratum)), + ) + + +def summary_rows(world, annotations, subsets, identity, old_correct=None): + """Counts are sufficient to reaggregate without hiding empty or ambiguous cells.""" + classes, bits = annotations["class_code"], annotations["matched_role_bits"] + for label, ids in subsets: + ids = np.asarray(ids) + correct = annotations["correct"][ids] + row = { + **identity, + "subset": label, + "n": len(ids), + "correct": int(correct.sum()), + "accuracy": float(correct.mean()) if len(ids) else None, + "termination_error": int((~annotations["ended"][ids]).sum()), + "role_not_applicable": int((classes[ids] == NOT_APPLICABLE).sum()), + "other_answer": int((classes[ids] == OTHER).sum()), + "indistinguishable": int((classes[ids] == INDISTINGUISHABLE).sum()), + "indistinguishable_wrong": int(((classes[ids] == INDISTINGUISHABLE) & ~correct).sum()), + } + # Stable CSV schema, even though learning uses only four roles. + for role in dict.fromkeys((*LEARNING_ROLES, *EDIT_ROLES)): + role_names = list(annotations["candidate_roles"]) + if role in role_names: + index = role_names.index(role) + row[f"unique_{role}"] = int((classes[ids] == ROLE_CODE_START + index).sum()) + row[f"matches_{role}"] = int( + (((bits[ids] & (1 << index)) != 0) & annotations["ended"][ids]).sum() + ) + else: + row[f"unique_{role}"] = row[f"matches_{role}"] = 0 + if old_correct is not None: + known = old_correct[ids] + row["old_known"] = int(known.sum()) + row["old_known_coverage"] = float(known.mean()) if len(ids) else None + row["old_known_now_wrong"] = int((known & ~correct).sum()) + row["damage_rate"] = ( + (float((known & ~correct).sum() / known.sum()) if known.any() else None) + if label.startswith("U/") + else None + ) + else: + row.update( + old_known=None, old_known_coverage=None, old_known_now_wrong=None, damage_rate=None + ) + yield row + + +def _write_csv(path, rows): + with Path(path).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def _safe_output(output, source_roots): + output = Path(output).resolve() + if any(output == root or root in output.parents for root in source_roots): + raise ValueError("Diagnostics must not be written into source experiment directories") + output.mkdir(parents=True, exist_ok=True) + return output + + +def analyze_saved(repository, output, manifest_path="configs/bios-cross-scale-development-v1.json"): + """Re-score the complete matrix using CPU arrays; never invoke old summary writers.""" + repository = Path(repository).resolve() + manifest_path = repository / manifest_path + manifest = json.loads(manifest_path.read_text()) + source_roots = [(repository / size["output"]).resolve() for size in manifest["sizes"]] + output = _safe_output(output, source_roots) + ledger = {} + + def record(path): + path = Path(path).resolve() + key = str(path.relative_to(repository)) if repository in path.parents else str(path) + digest = file_sha256(path) + if key in ledger and ledger[key] != digest: + raise ValueError(f"Source changed during analysis: {path}") + ledger[key] = digest + + record(manifest_path) + worlds, pairs = {}, {} + learning_rows, editing_rows, error_rows = [], [], [] + counts = { + "models": 0, + "learning_checkpoints": 0, + "edit_cases": 0, + "edit_checkpoints": 0, + "scored_query_predictions": 0, + "classified_derived_predictions": 0, + } + for size, root in zip(manifest["sizes"], source_roots, strict=True): + contract_path = root / "launch-contract.json" + record(contract_path) + contract = json.loads(contract_path.read_text()) + study = contract["study"] + expected_runs = { + (w, seed, condition) + for w in study["worlds"] + for seed in study["seeds"] + for condition in CONDITIONS + } + seen_runs = set() + for config_path in sorted(root.glob("world-*/config.json")): + record(config_path) + config = json.loads(config_path.read_text()) + if config["sources"] != contract["sources"] or config["study"] != study: + raise ValueError(f"Run contract mismatch: {config_path}") + for name, digest in config["sources"].items(): + path = repository / "src/llm_memory_editability" / name + if file_sha256(path) != digest: + raise ValueError(f"Frozen source changed: {name}") + record(path) + run = config_path.parent + key = (config["world"], config["seed"], config["condition"]) + if key in seen_runs: + raise ValueError("Duplicate model") + seen_runs.add(key) + if not (run / "complete.json").exists(): + raise ValueError(f"Incomplete run: {run}") + record(run / "complete.json") + world_seed = config["world"] + if world_seed not in worlds: + worlds[world_seed] = make_cross_world( + world_seed, repository / "data/bios-organization-v1" + ) + world = worlds[world_seed] + if config["truth_sha256"] != array_hash(world.answers) or config[ + "prompts_sha256" + ] != array_hash(world.prompts): + raise ValueError("Generated data mismatch") + common = { + "width": size["width"], + "parameters": config["parameters"], + "world": world_seed, + "seed": config["seed"], + "condition": config["condition"], + } + out_run = output / "queries" / f"width-{size['width']}" / run.name + out_run.mkdir(parents=True, exist_ok=True) + baseline = None + for step in study["checkpoints"]: + prediction_path = run / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {name: loaded[name] for name in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays) + np.savez_compressed(out_run / f"learning-{step}.npz", **annotated) + identity = { + **common, + "phase": "learning", + "chain": "", + "kind": "", + "scope": "", + "step": step, + } + learning_rows.extend( + summary_rows(world, annotated, learning_subsets(world), identity) + ) + counts["learning_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + if step == study["steps"]: + baseline = arrays["correct"] + if baseline is None: + raise ValueError("Missing learning endpoint") + for chain, name in enumerate(CHAINS): + pair_key = (world_seed, chain) + if pair_key not in pairs: + pairs[pair_key] = edit_pair(world, chain) + pair = pairs[pair_key] + for kind in ("coherent", "exception"): + target = pair[kind] + for scope in ("mlp", "all"): + case = f"{name}-{kind}-{scope}" + dest = run / "edits" / case + record(dest / "complete.json") + record(dest / "sets.npz") + with np.load(dest / "sets.npz", allow_pickle=False) as loaded: + for field, expected in pair.items(): + if not np.array_equal(loaded[field], expected): + raise ValueError(f"Edit set mismatch: {dest}/{field}") + if not np.array_equal(loaded["old_correct"], baseline): + raise ValueError(f"Edit baseline mismatch: {dest}") + for step in study["edit_checkpoints"]: + prediction_path = dest / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {k: loaded[k] for k in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays, target) + np.savez_compressed(out_run / f"{case}-{step}.npz", **annotated) + identity = { + **common, + "phase": "editing", + "chain": name, + "kind": kind, + "scope": scope, + "step": step, + } + editing_rows.extend( + summary_rows( + world, + annotated, + editing_subsets(world, pair, chain, target), + identity, + baseline, + ) + ) + # Readable per-D query ledger, with every ambiguity explicitly retained. + roles, values = candidate_answers(world, chain, target) + for query in pair["D"]: + person = world.person[query] + matches = [ + role + for i, role in enumerate(roles) + if annotated["matched_role_bits"][query] & (1 << i) + ] + code = int(annotated["class_code"][query]) + category = { + TERMINATION_ERROR: "termination_error", + OTHER: "other", + INDISTINGUISHABLE: "indistinguishable", + } + error_rows.append( + { + **identity, + "query": int(query), + "person": int(person), + "heldout": bool(query in world.heldout_ids[chain]), + "old_exception": bool(world.exceptions[chain, person]), + "manipulated_conflict_cohort": bool( + query in pair["conflict_D"] + ), + "factual_conflict": bool( + values[person, 0] != values[person, 1] + ), + "prediction": int(arrays["prediction"][query]), + "ended": bool(arrays["ended"][query]), + "correct": bool(arrays["correct"][query]), + "class": category.get( + code, + roles[code - ROLE_CODE_START] + if code >= ROLE_CODE_START + else "", + ), + "matched_roles": "|".join(matches), + **{ + role: int(values[person, i]) + for i, role in enumerate(roles) + }, + } + ) + counts["edit_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + counts["edit_cases"] += 1 + counts["models"] += 1 + print(json.dumps({"event": "p0_model_scored", **common, **counts}), flush=True) + if seen_runs != expected_runs: + raise ValueError(f"Incomplete or unexpected model grid: width {size['width']}") + if ( + counts["models"] != manifest["learning_runs"] + or counts["edit_cases"] != manifest["edit_cases"] + ): + raise ValueError("Incomplete matrix") + _write_csv(output / "learning-strata.csv", learning_rows) + _write_csv(output / "editing-strata.csv", editing_rows) + _write_csv(output / "propagation-queries.csv", error_rows) + # Verify that reading/analysis did not mutate any source and that no parallel + # process changed this historical input batch while it was being analyzed. + for name, digest in ledger.items(): + if file_sha256(repository / name) != digest: + raise ValueError(f"Source changed during analysis: {name}") + write_json(output / "sources.json", ledger) + write_json( + output / "schema.json", + { + "class_codes": { + "not_applicable_to_base_query": -1, + "termination_error": 0, + "other": 1, + "indistinguishable": 2, + "unique_role_start": 3, + }, + "learning_roles": LEARNING_ROLES, + "editing_roles": EDIT_ROLES, + "matched_role_bits": "bit i indicates value matches role i; EOS checked separately", + "candidate_tokens_shape": "chain, person, role; " + "maps to derived_query_ids[chain, person]", + "interpretation": "Candidate answer agreement is not causal evidence for a path. " + "Overlapping roles are never assigned a preferred interpretation.", + "subset_rows_overlap": True, + "manipulated_conflict_cohort": "Original 45 people, also tagged in coherent controls; " + "factual_conflict is measured from actual target answers.", + }, + ) + code_hashes = { + str(path.relative_to(repository)): file_sha256(path) + for path in (Path(__file__).resolve(), repository / "scripts/analyze_bios_paths.py") + } + audit = { + "complete": True, + **counts, + "source_files": len(ledger), + "sources_sha256": file_sha256(output / "sources.json"), + "analysis_sources": code_hashes, + "errors": [], + "source_data_modified": False, + "source_hashes_rechecked_after_analysis": True, + } + write_json(output / "audit.json", audit) + _report(output, audit, learning_rows, editing_rows) + return audit + + +def _report(output, audit, learning_rows, editing_rows): + lines = [ + "# P0:已有预测的行为诊断", + "", + f"完成{audit['models']}个模型、{audit['edit_cases']}个编辑;" + f"重计分{audit['learning_checkpoints']}个学习和{audit['edit_checkpoints']}个编辑检查点。", + "", + "候选答案相同的角色记为不可区分;答案重合不能证明内部路径。" + "终止失败独立于答案值记录。下表为案例等权均值,非独立查询推断。", + "", + "| 宽度 | 编辑 | 案例 | 冲突留出D | 新实际城市匹配 | 不可区分 | 终止失败 |", + "|---:|---|---:|---:|---:|---:|---:|", + ] + grouped = defaultdict(list) + for row in editing_rows: + if ( + row["kind"] == "exception" + and row["step"] == 512 + and row["subset"] == "D/heldout/manipulated_conflict_cohort" + ): + grouped[row["width"], row["scope"]].append(row) + for (width, scope), rows in sorted(grouped.items()): + rates = [ + np.mean([r[key] / r["n"] for r in rows]) + for key in ("correct", "matches_new_actual", "indistinguishable", "termination_error") + ] + lines.append( + f"| {width} | {scope} | {len(rows)} | " + + " | ".join(f"{100 * rate:.2f}%" for rate in rates) + + " |" + ) + lines += [ + "", + "新实际城市匹配是允许与旧实际/另一条链答案重合的描述性比例;" + "唯一匹配和全部角色位图均另存,不能据此宣称捷径已证实。", + "", + "学习分层见 learning-strata.csv;编辑分层见 editing-strata.csv;" + "每条传播查询见 propagation-queries.csv;全部逐查询数组见 queries/。", + "自主两步前向诊断尚须单独执行并记录模型权重来源。", + "", + ] + (output / "report.md").write_text("\n".join(lines)) + + +def free_generate_values(model, prompts, lengths, device, batch_size=512): + """Exactly the frozen value-plus-EOS generation convention, without targets.""" + import torch + + from .bios_train import precision + + predictions, ended = [], [] + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[begin : begin + batch_size], device=device) + n = torch.as_tensor(lengths[begin : begin + batch_size], device=device) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)} + + +def autonomous_two_step(model, world, chain, device, batch_size=512, answers=None): + """Generate bridge identity, then query that predicted identity, never the true one. + + Truth is accessed only for scoring after both model calls. A wrong but valid + bridge may coincidentally lead to a correct city; keep that outcome and the + first-hop correctness separately. Invalid/unterminated bridges fail outright. + """ + membership_ids = world.membership_ids[chain] + first = free_generate_values( + model, world.prompts[membership_ids], world.lengths[membership_ids], device, batch_size + ) + allowed_subjects = world.prompts[world.root_ids[chain], 1] + valid = first["ended"] & np.isin(first["prediction"], allowed_subjects) + second_prediction = np.full(len(membership_ids), -1, dtype=np.int64) + second_ended = np.zeros(len(membership_ids), dtype=bool) + if valid.any(): + # Root queries have the same grammar and relation token. Do not choose a + # template using true membership; replace the subject using generated data. + root_template = world.prompts[world.root_ids[chain, 0]] + prompts = np.broadcast_to(root_template, (int(valid.sum()), 5)).copy() + prompts[:, 1] = first["prediction"][valid] + lengths = np.full(len(prompts), world.lengths[world.root_ids[chain, 0]], dtype=np.int64) + second = free_generate_values(model, prompts, lengths, device, batch_size) + second_prediction[valid], second_ended[valid] = second["prediction"], second["ended"] + target = world.answers if answers is None else answers + return { + "query_id": world.derived_ids[chain], + "bridge_prediction": first["prediction"], + "bridge_ended": first["ended"], + "bridge_valid": valid, + "bridge_correct": (first["prediction"] == target[membership_ids]) & first["ended"], + "prediction": second_prediction, + "ended": second_ended, + "correct": valid & second_ended & (second_prediction == target[world.derived_ids[chain]]), + } + + +def diagnose_two_step_run( + run, output, device="cuda", learning_steps=(15360,), include_edits=False, batch_size=512 +): + """Independent, resumable forward-only jobs; no optimizer or training mutations.""" + import torch + + from .bios_model import CausalLM, ModelConfig + + run, output = Path(run).resolve(), Path(output).resolve() + repository = Path(__file__).resolve().parents[2] + output = _safe_output(output, [run]) + config = json.loads((run / "config.json").read_text()) + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if array_hash(world.answers) != config["truth_sha256"]: + raise ValueError("Two-step world differs from trained world") + device = torch.device(device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + jobs = [ + ( + f"learning-{step}", + run / f"model-{step}.pt", + world.answers, + run / f"predictions-{step}.npz", + ) + for step in learning_steps + ] + if include_edits: + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + for kind in ("coherent", "exception"): + for scope in ("mlp", "all"): + dest = run / "edits" / f"{name}-{kind}-{scope}" + jobs.append( + ( + dest.name, + dest / "model-final.pt", + pair[kind], + dest / f"predictions-{config['study']['edit_steps']}.npz", + ) + ) + for label, checkpoint, answers, direct_path in jobs: + dest = output / label + dest.mkdir(parents=True, exist_ok=True) + identity = { + "run": str(run), + "checkpoint": str(checkpoint), + "checkpoint_sha256": file_sha256(checkpoint), + "direct_predictions_sha256": file_sha256(direct_path), + "config_sha256": file_sha256(run / "config.json"), + "diagnostic_source_sha256": file_sha256(__file__), + "answer_sha256": array_hash(answers), + "batch_size": batch_size, + "device_type": device.type, + "torch": torch.__version__, + "precision": "BF16 autocast; FP32 weights" if device.type == "cuda" else "FP32", + } + complete_path = dest / "complete.json" + if complete_path.exists(): + saved = json.loads(complete_path.read_text()) + if saved["identity"] != identity: + raise ValueError(f"Changed diagnostic identity: {dest}") + continue + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + with np.load(direct_path) as data: + direct = {k: data[k] for k in ("prediction", "ended", "correct")} + score_saved_arrays(direct, answers) + rows = [] + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device, batch_size, answers) + ids = world.derived_ids[chain] + arrays.update({f"direct_{k}": v[ids] for k, v in direct.items()}) + np.savez_compressed(dest / f"{name}.npz", **arrays) + for split, mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("trained", np.isin(ids, world.train_ids[chain])), + ("heldout", np.isin(ids, world.heldout_ids[chain])), + ): + for population, population_mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + selected = mask & population_mask + n = int(selected.sum()) + rows.append( + { + "chain": name, + "split": split, + "population": population, + "n": n, + **{ + key: int(arrays[key][selected].sum()) + for key in ( + "correct", + "direct_correct", + "bridge_valid", + "bridge_correct", + ) + }, + } + ) + _write_csv(dest / "summary.csv", rows) + write_json( + complete_path, + { + "identity": identity, + "complete": True, + "queries": int(world.derived_ids.size), + "oracle_bridging": False, + }, + ) + del model, saved + if device.type == "cuda": + torch.cuda.empty_cache() + print( + json.dumps({"event": "two_step_complete", "run": str(run), "case": label}), flush=True + ) diff --git a/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_path_minimal.py b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_path_minimal.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2ed53451de1a88abe78ee5e58cb49745597c2b --- /dev/null +++ b/docs/development-artifacts/write-target-development-v1/source/src/llm_memory_editability/bios_path_minimal.py @@ -0,0 +1,379 @@ +"""Two-layer follow-up: common-error removal versus competing new answers.""" + +import argparse +import fcntl +import itertools +import json +import os +import subprocess +import sys +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig +from .bios_path_transfer import ROOT, inner, norm, path_mode, sha, stamp, tensor_sha + +CONFIG = ROOT / "configs/bios-path-minimal-v1.json" + + +def toy_data(config, device): + people = config["people"] + person = torch.arange(people, device=device).repeat_interleave(3) + relation = torch.arange(3, device=device).repeat(people) + value_start = 3 + people + 3 + tokens = torch.stack( + (torch.ones_like(person), 3 + person, 3 + people + relation, torch.full_like(person, 2)), -1 + ) + labels = value_start + (person + (relation == 2)) % 3 + return tokens, labels, value_start + + +def probe_data(config, person, kind, device): + tokens, old, values = toy_data(config, device) + ids = torch.arange(person * 3, person * 3 + 3, device=device) + a, b, c = values + (person + 1) % 3, values + (person + 2) % 3, values + person % 3 + labels = old[ids].clone() + labels[0], labels[1] = a if kind == "coherent" else b, a + return tokens[ids], labels, (a, b, c) + + +def gradients(model, tokens, labels, arm): + projection = model.blocks[0].mlp.down + captured = {} + + def hook(module, inputs, output): + captured["z"], captured["h"] = inputs[0], output + + handle = projection.register_forward_hook(hook) + try: + with path_mode(model, 0, arm): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits.double(), labels, reduction="none") + actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) + z, delta = captured["z"].detach(), delta.detach() + g = torch.einsum("btd,btk->btdk", delta, z).sum(1) + if norm(g.sum(0) - actual) / max(norm(actual), 1e-30) > 5e-5: + raise ValueError("Minimal-model gradient reconstruction failed") + return {"logits": logits.detach(), "loss": loss.detach(), "g": g, "z": z, "delta": delta} + finally: + handle.remove() + + +@torch.no_grad() +def evaluate(model, tokens, labels, values): + logits = model(tokens)[:, -1].double() + p = logits.softmax(-1) + a, b, c = values + return { + "loss": F.cross_entropy(logits, labels, reduction="none").cpu().tolist(), + "prediction": logits.argmax(-1).cpu().tolist(), + "probabilities_abc": p[:, [a, b, c]].cpu().tolist(), + "source_target_probability": p[0, labels[0]].item(), + "derived_margin_ab": (logits[1, a] - logits[1, b]).item(), + "isotropic_same_probability_reference": (p[1].square().sum() - p[1, a] - p[1, b]).item(), + } + + +def freeze(config): + directory = ROOT / config["artifacts"] + directory.mkdir(parents=True, exist_ok=True) + path = directory / "preregistration-lock.json" + if path.exists(): + raise FileExistsError("Cannot replace minimal-model prospective lock") + section = ( + "### 18.7 " + (ROOT / "docs/experimental-protocol.md").read_text().split("### 18.7 ", 1)[1] + ) + (directory / "preregistration.md").write_text(section) + files = [ + CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_path_minimal.py", + ROOT / "scripts/analyze_bios_path_margin.py", + ROOT / "tests/test_bios_path_minimal.py", + ROOT / "src/llm_memory_editability/bios_path_transfer.py", + ROOT / "src/llm_memory_editability/bios_model.py", + ROOT / "docs/development-artifacts/path-transfer-v1/audit.json", + ] + sources = {} + for file in files: + relative = file.relative_to(ROOT) + sources[str(relative)] = sha(file) + destination = directory / "frozen-files" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(file.read_bytes()) + write_json( + path, + { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(directory / "preregistration.md"), + "torch": torch.__version__, + }, + ) + return {"lock": str(path), "sha256": sha(path)} + + +def verify(config): + directory = ROOT / config["artifacts"] + path = directory / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Minimal config/runtime changed") + for name, digest in lock["sources"].items(): + if sha(ROOT / name) != digest: + raise ValueError("Minimal frozen source changed: " + name) + if sha(directory / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Minimal protocol changed") + return sha(path) + + +def learn(config, seed, device, out): + torch.manual_seed(seed) + tokens, labels, values = toy_data(config, device) + model = CausalLM(ModelConfig(values + 3, config["width"], 2, config["heads"], context=8)).to( + device + ) + if (out / "parent.pt").exists(): + saved = torch.load(out / "parent.pt", map_location=device, weights_only=False) + model.load_state_dict(saved["model"]) + return model + optimizer = torch.optim.AdamW( + model.parameters(), lr=config["train_lr"], weight_decay=config["train_weight_decay"] + ) + trajectory = [] + for step in range(config["train_steps"] + 1): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits, labels) + if step in (0, 128, 512, config["train_steps"]): + trajectory.append( + { + "step": step, + "loss": loss.item(), + "accuracy": logits.argmax(-1).eq(labels).float().mean().item(), + } + ) + if step == config["train_steps"]: + break + optimizer.zero_grad(set_to_none=True) + loss.backward() + optimizer.step() + torch.save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": config["train_steps"], + }, + out / "parent.pt", + ) + write_json(out / "learning.json", trajectory) + return model + + +def trajectory(model, parent, config, person, kind, arm, device, directory): + model.load_state_dict(parent) + model.eval() + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name == config["target_parameter"]) + tokens, labels, values = probe_data(config, person, kind, device) + w = model.blocks[0].mlp.down.weight + timeline, steps, factors = [], [], [] + for step in range(config["edit_steps"] + 1): + measure = step % config["measure_every"] == 0 or step == config["edit_steps"] + full = gradients( + model, tokens if measure else tokens[:1], labels if measure else labels[:1], "full" + ) + source = full if arm == "full" else gradients(model, tokens[:1], labels[:1], arm) + if not torch.equal(full["logits"][:1], source["logits"][:1]): + # Different batch sizes allow only normal FP32 GEMM rounding. + if (full["logits"][:1] - source["logits"][:1]).abs().max().item() > 3e-5: + raise ValueError("Minimal forward mismatch") + raw, original = source["g"][0], full["g"][0] + direction = raw * (norm(original) / norm(raw)) if norm(raw) else raw + if measure: + row = { + "step": step, + **evaluate(model, tokens, labels, values), + "source_gradient_norm": norm(original), + "intervened_gradient_norm": norm(raw), + "kernel_source": inner(full["g"][0], direction), + "kernel_derived": inner(full["g"][1], direction), + "kernel_retention": inner(full["g"][2], direction), + "kernel_derived_full": inner(full["g"][1], original), + } + timeline.append(row) + factors.append( + { + key: value.detach().cpu().numpy() + for key, value in { + "z": full["z"], + "delta": full["delta"], + "source_z": source["z"][:1], + "source_delta": source["delta"][:1], + }.items() + } + ) + if step == config["edit_steps"]: + break + before_weight = w.detach().clone() if measure else None + with torch.no_grad(): + w.add_(direction, alpha=-config["edit_lr"]) + if measure: + after = evaluate(model, tokens, labels, values) + actual_delta = w.detach() - before_weight + row["one_step_observed_derived"] = after["loss"][1] - row["loss"][1] + row["one_step_predicted_derived"] = inner(full["g"][1], actual_delta) + row["one_step_margin_change"] = after["derived_margin_ab"] - row["derived_margin_ab"] + steps.append( + { + "step": step, + "source_loss": full["loss"][0].item(), + "direction_norm": norm(direction), + "source_gradient_norm": norm(original), + } + ) + for name, value in model.state_dict().items(): + if name != config["target_parameter"] and not torch.equal(value, parent[name]): + raise ValueError("Minimal frozen parameter changed") + directory.mkdir(parents=True, exist_ok=True) + write_json( + directory / "trajectory.json", + { + "person": person, + "kind": kind, + "arm": arm, + "values_abc": values, + "labels": labels.cpu().tolist(), + "timeline": timeline, + "steps": steps, + }, + ) + np.savez_compressed( + directory / "factors.npz", + **{key: np.stack([factor[key] for factor in factors]) for key in factors[0]}, + ) + torch.save(w.detach().cpu(), directory / "edited-weight.pt") + write_json( + directory / "complete.json", + { + "finished_at": stamp(), + "steps": len(steps), + "weight_sha256": tensor_sha(w), + "frozen_parameters_unchanged": True, + "files": { + name: sha(directory / name) + for name in ("trajectory.json", "factors.npz", "edited-weight.pt") + }, + }, + ) + + +def run(config, seed, device): + lock_hash = verify(config) + if seed not in config["seeds"]: + raise ValueError("Unknown seed") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + out = ROOT / config["output"] / f"seed-{seed}" + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + write_json( + out / "runtime.json", + { + "started_at": stamp(), + "lock_sha256": lock_hash, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + ) + model = learn(config, seed, device, out) + parent = {k: v.detach().clone() for k, v in model.state_dict().items()} + for person, kind, arm in itertools.product( + config["people_to_edit"], config["kinds"], config["arms"] + ): + directory = out / f"person-{person}-{kind}-{arm}" + if not (directory / "complete.json").exists(): + trajectory(model, parent, config, person, kind, arm, device, directory) + print( + json.dumps( + { + "event": "trajectory", + "seed": seed, + "person": person, + "kind": kind, + "arm": arm, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "finished_at": stamp(), + "lock_sha256": lock_hash, + "files": { + str(path.relative_to(out)): sha(path) + for path in out.rglob("*") + if path.is_file() and path != out / "complete.json" and path.name != ".lock" + }, + }, + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("freeze", "worker", "dispatch")) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--gpus", nargs="+", type=int, default=[5, 8]) + args = parser.parse_args() + config = json.loads(CONFIG.read_text()) + if args.command == "freeze": + print(json.dumps(freeze(config))) + elif args.command == "worker": + run(config, args.seed, torch.device(args.device)) + else: + verify(config) + output = ROOT / config["output"] + output.mkdir(parents=True, exist_ok=True) + workers = [] + for index, seed in enumerate(config["seeds"]): + log = (output / f"seed-{seed}.log").open("a") + env = { + **os.environ, + "CUDA_VISIBLE_DEVICES": str(args.gpus[index % len(args.gpus)]), + "PYTHONPATH": str(ROOT / "src"), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + proc = subprocess.Popen( + [ + sys.executable, + str(ROOT / "scripts/run_bios_path_minimal.py"), + "worker", + "--seed", + str(seed), + ], + env=env, + cwd=ROOT, + stdout=log, + stderr=subprocess.STDOUT, + ) + workers.append((proc, log)) + codes = [] + for proc, log in workers: + codes.append(proc.wait()) + log.close() + write_json(output / "dispatch.json", {"finished_at": stamp(), "returncodes": codes}) + if any(codes): + raise RuntimeError("Minimal worker failed; see retained logs") + + +if __name__ == "__main__": + main()