diff --git a/.gitattributes b/.gitattributes index 01e79bd9302241a1a98dde6f10639058dc3f3a69..df71d9d43f30a27b64b50aa67b4db9b4b5e2b5a9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -210,3 +210,5 @@ docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/container/wh docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/container/wheels/xxhash-4.0.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl filter=lfs diff=lfs merge=lfs -text docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/container/wheels/yarl-1.25.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl filter=lfs diff=lfs merge=lfs -text docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/paper.pdf filter=lfs diff=lfs merge=lfs -text +docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.pdf filter=lfs diff=lfs merge=lfs -text +docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.pdf filter=lfs diff=lfs merge=lfs -text diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/slow_documentation_tests.txt b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/slow_documentation_tests.txt new file mode 100644 index 0000000000000000000000000000000000000000..302778c73200395cbde6390a7d6178cf02ce5e12 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/slow_documentation_tests.txt @@ -0,0 +1,11 @@ +docs/source/en/generation_strategies.md +docs/source/en/model_doc/ctrl.md +docs/source/en/model_doc/kosmos-2.md +docs/source/en/model_doc/seamless_m4t.md +docs/source/en/model_doc/seamless_m4t_v2.md +docs/source/en/task_summary.md +docs/source/en/tasks/prompting.md +src/transformers/models/blip_2/modeling_blip_2.py +src/transformers/models/ctrl/modeling_ctrl.py +src/transformers/models/fuyu/modeling_fuyu.py +src/transformers/models/kosmos2/modeling_kosmos2.py \ No newline at end of file diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/sort_auto_mappings.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/sort_auto_mappings.py new file mode 100644 index 0000000000000000000000000000000000000000..8871b6807dfcc52dcaa2481fbdf96ffe58669470 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/sort_auto_mappings.py @@ -0,0 +1,124 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Utility that sorts the names in the auto mappings defines in the auto modules in alphabetical order. + +Use from the root of the repo with: + +```bash +python utils/sort_auto_mappings.py +``` + +to auto-fix all the auto mappings (used in `make style`). + +To only check if the mappings are properly sorted (as used in `make quality`), do: + +```bash +python utils/sort_auto_mappings.py --check_only +``` +""" +import argparse +import os +import re +from typing import Optional + + +# Path are set with the intent you should run this script from the root of the repo. +PATH_TO_AUTO_MODULE = "src/transformers/models/auto" + + +# re pattern that matches mapping introductions: +# SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict +_re_intro_mapping = re.compile(r"[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict") +# re pattern that matches identifiers in mappings +_re_identifier = re.compile(r'\s*\(\s*"(\S[^"]+)"') + + +def sort_auto_mapping(fname: str, overwrite: bool = False) -> Optional[bool]: + """ + Sort all auto mappings in a file. + + Args: + fname (`str`): The name of the file where we want to sort auto-mappings. + overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file. + + Returns: + `Optional[bool]`: Returns `None` if `overwrite=True`. Otherwise returns `True` if the file has an auto-mapping + improperly sorted, `False` if the file is okay. + """ + with open(fname, "r", encoding="utf-8") as f: + content = f.read() + + lines = content.split("\n") + new_lines = [] + line_idx = 0 + while line_idx < len(lines): + if _re_intro_mapping.search(lines[line_idx]) is not None: + # Start of a new mapping! + indent = len(re.search(r"^(\s*)\S", lines[line_idx]).groups()[0]) + 8 + while not lines[line_idx].startswith(" " * indent + "("): + new_lines.append(lines[line_idx]) + line_idx += 1 + + blocks = [] + while lines[line_idx].strip() != "]": + # Blocks either fit in one line or not + if lines[line_idx].strip() == "(": + start_idx = line_idx + while not lines[line_idx].startswith(" " * indent + ")"): + line_idx += 1 + blocks.append("\n".join(lines[start_idx : line_idx + 1])) + else: + blocks.append(lines[line_idx]) + line_idx += 1 + + # Sort blocks by their identifiers + blocks = sorted(blocks, key=lambda x: _re_identifier.search(x).groups()[0]) + new_lines += blocks + else: + new_lines.append(lines[line_idx]) + line_idx += 1 + + if overwrite: + with open(fname, "w", encoding="utf-8") as f: + f.write("\n".join(new_lines)) + else: + return "\n".join(new_lines) != content + + +def sort_all_auto_mappings(overwrite: bool = False): + """ + Sort all auto mappings in the library. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file. + """ + fnames = [os.path.join(PATH_TO_AUTO_MODULE, f) for f in os.listdir(PATH_TO_AUTO_MODULE) if f.endswith(".py")] + diffs = [sort_auto_mapping(fname, overwrite=overwrite) for fname in fnames] + + if not overwrite and any(diffs): + failures = [f for f, d in zip(fnames, diffs) if d] + raise ValueError( + f"The following files have auto mappings that need sorting: {', '.join(failures)}. Run `make style` to fix" + " this." + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") + args = parser.parse_args() + + sort_all_auto_mappings(not args.check_only) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_configuration.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..676486fc517132d5ceb6eb69fb15fac2de2a03c8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_configuration.py @@ -0,0 +1,16 @@ +from transformers import PretrainedConfig + + +class CustomConfig(PretrainedConfig): + model_type = "custom" + + def __init__(self, attribute=1, **kwargs): + self.attribute = attribute + super().__init__(**kwargs) + + +class NoSuperInitConfig(PretrainedConfig): + model_type = "custom" + + def __init__(self, attribute=1, **kwargs): + self.attribute = attribute diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_feature_extraction.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_feature_extraction.py new file mode 100644 index 0000000000000000000000000000000000000000..de367032d8fe8e73fc1b5f3d281eb21506af7b66 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_feature_extraction.py @@ -0,0 +1,5 @@ +from transformers import Wav2Vec2FeatureExtractor + + +class CustomFeatureExtractor(Wav2Vec2FeatureExtractor): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_image_processing.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_image_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..e4984854adc600678c12c156bac7264c481952e0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_image_processing.py @@ -0,0 +1,5 @@ +from transformers import CLIPImageProcessor + + +class CustomImageProcessor(CLIPImageProcessor): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_modeling.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_modeling.py new file mode 100644 index 0000000000000000000000000000000000000000..4b64b4a3df770346c3a5532fa290aa971af7133e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_modeling.py @@ -0,0 +1,33 @@ +import torch + +from transformers import PreTrainedModel + +from .custom_configuration import CustomConfig, NoSuperInitConfig + + +class CustomModel(PreTrainedModel): + config_class = CustomConfig + + def __init__(self, config): + super().__init__(config) + self.linear = torch.nn.Linear(config.hidden_size, config.hidden_size) + + def forward(self, x): + return self.linear(x) + + def _init_weights(self, module): + pass + + +class NoSuperInitModel(PreTrainedModel): + config_class = NoSuperInitConfig + + def __init__(self, config): + super().__init__(config) + self.linear = torch.nn.Linear(config.attribute, config.attribute) + + def forward(self, x): + return self.linear(x) + + def _init_weights(self, module): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_pipeline.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7928b1ccd145fb8ea51c32554dc0b19567ce0c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_pipeline.py @@ -0,0 +1,33 @@ +import numpy as np + +from transformers import Pipeline + + +def softmax(outputs): + maxes = np.max(outputs, axis=-1, keepdims=True) + shifted_exp = np.exp(outputs - maxes) + return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) + + +class PairClassificationPipeline(Pipeline): + def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "second_text" in kwargs: + preprocess_kwargs["second_text"] = kwargs["second_text"] + return preprocess_kwargs, {}, {} + + def preprocess(self, text, second_text=None): + return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework) + + def _forward(self, model_inputs): + return self.model(**model_inputs) + + def postprocess(self, model_outputs): + logits = model_outputs.logits[0].numpy() + probabilities = softmax(logits) + + best_class = np.argmax(probabilities) + label = self.model.config.id2label[best_class] + score = probabilities[best_class].item() + logits = logits.tolist() + return {"label": label, "score": score, "logits": logits} diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_processing.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..196fc511b65b3bd589a5456a965b630f2c8be91b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_processing.py @@ -0,0 +1,6 @@ +from transformers import ProcessorMixin + + +class CustomProcessor(ProcessorMixin): + feature_extractor_class = "AutoFeatureExtractor" + tokenizer_class = "AutoTokenizer" diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_tokenization.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_tokenization.py new file mode 100644 index 0000000000000000000000000000000000000000..d67b1373041e7c8b6682300cf507ffbaa0143211 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_tokenization.py @@ -0,0 +1,5 @@ +from transformers import BertTokenizer + + +class CustomTokenizer(BertTokenizer): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_tokenization_fast.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_tokenization_fast.py new file mode 100644 index 0000000000000000000000000000000000000000..ace94fdd1a5d1a726c3840db2b66e4f0a053e05c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_tokenization_fast.py @@ -0,0 +1,8 @@ +from transformers import BertTokenizerFast + +from .custom_tokenization import CustomTokenizer + + +class CustomTokenizerFast(BertTokenizerFast): + slow_tokenizer_class = CustomTokenizer + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/tests_fetcher.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/tests_fetcher.py new file mode 100644 index 0000000000000000000000000000000000000000..1aae59e4b33602bebdbd7b1bff338080515f14e1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/tests_fetcher.py @@ -0,0 +1,1260 @@ +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Welcome to tests_fetcher V2. + +This util is designed to fetch tests to run on a PR so that only the tests impacted by the modifications are run, and +when too many models are being impacted, only run the tests of a subset of core models. It works like this. + +Stage 1: Identify the modified files. For jobs that run on the main branch, it's just the diff with the last commit. +On a PR, this takes all the files from the branching point to the current commit (so all modifications in a PR, not +just the last commit) but excludes modifications that are on docstrings or comments only. + +Stage 2: Extract the tests to run. This is done by looking at the imports in each module and test file: if module A +imports module B, then changing module B impacts module A, so the tests using module A should be run. We thus get the +dependencies of each model and then recursively builds the 'reverse' map of dependencies to get all modules and tests +impacted by a given file. We then only keep the tests (and only the core models tests if there are too many modules). + +Caveats: + - This module only filters tests by files (not individual tests) so it's better to have tests for different things + in different files. + - This module assumes inits are just importing things, not really building objects, so it's better to structure + them this way and move objects building in separate submodules. + +Usage: + +Base use to fetch the tests in a pull request + +```bash +python utils/tests_fetcher.py +``` + +Base use to fetch the tests on a the main branch (with diff from the last commit): + +```bash +python utils/tests_fetcher.py --diff_with_last_commit +``` +""" + +import argparse +import collections +import importlib.util +import json +import os +import re +import tempfile +from contextlib import contextmanager +from pathlib import Path +from typing import Dict, List, Optional, Tuple, Union + +from git import Repo + + +PATH_TO_REPO = Path(__file__).parent.parent.resolve() +PATH_TO_EXAMPLES = PATH_TO_REPO / "examples" +PATH_TO_TRANFORMERS = PATH_TO_REPO / "src/transformers" +PATH_TO_TESTS = PATH_TO_REPO / "tests" + +# List here the models to always test. +IMPORTANT_MODELS = [ + "auto", + # Most downloaded models + "bert", + "clip", + "t5", + "xlm-roberta", + "gpt2", + "bart", + "mpnet", + "gpt-j", + "wav2vec2", + "deberta-v2", + "layoutlm", + "opt", + "longformer", + "vit", + # Pipeline-specific model (to be sure each pipeline has one model in this list) + "tapas", + "vilt", + "clap", + "detr", + "owlvit", + "dpt", + "videomae", +] + + +@contextmanager +def checkout_commit(repo: Repo, commit_id: str): + """ + Context manager that checks out a given commit when entered, but gets back to the reference it was at on exit. + + Args: + repo (`git.Repo`): A git repository (for instance the Transformers repo). + commit_id (`str`): The commit reference to checkout inside the context manager. + """ + current_head = repo.head.commit if repo.head.is_detached else repo.head.ref + + try: + repo.git.checkout(commit_id) + yield + + finally: + repo.git.checkout(current_head) + + +def clean_code(content: str) -> str: + """ + Remove docstrings, empty line or comments from some code (used to detect if a diff is real or only concern + comments or docstings). + + Args: + content (`str`): The code to clean + + Returns: + `str`: The cleaned code. + """ + # We need to deactivate autoformatting here to write escaped triple quotes (we cannot use real triple quotes or + # this would mess up the result if this function applied to this particular file). + # fmt: off + # Remove docstrings by splitting on triple " then triple ': + splits = content.split('\"\"\"') + content = "".join(splits[::2]) + splits = content.split("\'\'\'") + # fmt: on + content = "".join(splits[::2]) + + # Remove empty lines and comments + lines_to_keep = [] + for line in content.split("\n"): + # remove anything that is after a # sign. + line = re.sub("#.*$", "", line) + # remove white lines + if len(line) != 0 and not line.isspace(): + lines_to_keep.append(line) + return "\n".join(lines_to_keep) + + +def keep_doc_examples_only(content: str) -> str: + """ + Remove everything from the code content except the doc examples (used to determined if a diff should trigger doc + tests or not). + + Args: + content (`str`): The code to clean + + Returns: + `str`: The cleaned code. + """ + # Keep doc examples only by splitting on triple "`" + splits = content.split("```") + # Add leading and trailing "```" so the navigation is easier when compared to the original input `content` + content = "```" + "```".join(splits[1::2]) + "```" + + # Remove empty lines and comments + lines_to_keep = [] + for line in content.split("\n"): + # remove anything that is after a # sign. + line = re.sub("#.*$", "", line) + # remove white lines + if len(line) != 0 and not line.isspace(): + lines_to_keep.append(line) + return "\n".join(lines_to_keep) + + +def get_all_tests() -> List[str]: + """ + Walks the `tests` folder to return a list of files/subfolders. This is used to split the tests to run when using + paralellism. The split is: + + - folders under `tests`: (`tokenization`, `pipelines`, etc) except the subfolder `models` is excluded. + - folders under `tests/models`: `bert`, `gpt2`, etc. + - test files under `tests`: `test_modeling_common.py`, `test_tokenization_common.py`, etc. + """ + + # test folders/files directly under `tests` folder + tests = os.listdir(PATH_TO_TESTS) + tests = [f"tests/{f}" for f in tests if "__pycache__" not in f] + tests = sorted([f for f in tests if (PATH_TO_REPO / f).is_dir() or f.startswith("tests/test_")]) + + # model specific test folders + model_test_folders = os.listdir(PATH_TO_TESTS / "models") + model_test_folders = [f"tests/models/{f}" for f in model_test_folders if "__pycache__" not in f] + model_test_folders = sorted([f for f in model_test_folders if (PATH_TO_REPO / f).is_dir()]) + + tests.remove("tests/models") + # Sagemaker tests are not meant to be run on the CI. + if "tests/sagemaker" in tests: + tests.remove("tests/sagemaker") + tests = model_test_folders + tests + + return tests + + +def diff_is_docstring_only(repo: Repo, branching_point: str, filename: str) -> bool: + """ + Check if the diff is only in docstrings (or comments and whitespace) in a filename. + + Args: + repo (`git.Repo`): A git repository (for instance the Transformers repo). + branching_point (`str`): The commit reference of where to compare for the diff. + filename (`str`): The filename where we want to know if the diff isonly in docstrings/comments. + + Returns: + `bool`: Whether the diff is docstring/comments only or not. + """ + folder = Path(repo.working_dir) + with checkout_commit(repo, branching_point): + with open(folder / filename, "r", encoding="utf-8") as f: + old_content = f.read() + + with open(folder / filename, "r", encoding="utf-8") as f: + new_content = f.read() + + old_content_clean = clean_code(old_content) + new_content_clean = clean_code(new_content) + + return old_content_clean == new_content_clean + + +def diff_contains_doc_examples(repo: Repo, branching_point: str, filename: str) -> bool: + """ + Check if the diff is only in code examples of the doc in a filename. + + Args: + repo (`git.Repo`): A git repository (for instance the Transformers repo). + branching_point (`str`): The commit reference of where to compare for the diff. + filename (`str`): The filename where we want to know if the diff is only in codes examples. + + Returns: + `bool`: Whether the diff is only in code examples of the doc or not. + """ + folder = Path(repo.working_dir) + with checkout_commit(repo, branching_point): + with open(folder / filename, "r", encoding="utf-8") as f: + old_content = f.read() + + with open(folder / filename, "r", encoding="utf-8") as f: + new_content = f.read() + + old_content_clean = keep_doc_examples_only(old_content) + new_content_clean = keep_doc_examples_only(new_content) + + return old_content_clean != new_content_clean + + +def get_impacted_files_from_tiny_model_summary(diff_with_last_commit: bool = False) -> List[str]: + """ + Return a list of python modeling files that are impacted by the changes of `tiny_model_summary.json` in between: + + - the current head and the main branch if `diff_with_last_commit=False` (default) + - the current head and its parent commit otherwise. + + Returns: + `List[str]`: The list of Python modeling files that are impacted by the changes of `tiny_model_summary.json`. + """ + repo = Repo(PATH_TO_REPO) + + folder = Path(repo.working_dir) + + if not diff_with_last_commit: + print(f"main is at {repo.refs.main.commit}") + print(f"Current head is at {repo.head.commit}") + + commits = repo.merge_base(repo.refs.main, repo.head) + for commit in commits: + print(f"Branching commit: {commit}") + else: + print(f"main is at {repo.head.commit}") + commits = repo.head.commit.parents + for commit in commits: + print(f"Parent commit: {commit}") + + if not os.path.isfile(folder / "tests/utils/tiny_model_summary.json"): + return [] + + files = set() + for commit in commits: + with checkout_commit(repo, commit): + with open(folder / "tests/utils/tiny_model_summary.json", "r", encoding="utf-8") as f: + old_content = f.read() + + with open(folder / "tests/utils/tiny_model_summary.json", "r", encoding="utf-8") as f: + new_content = f.read() + + # get the content as json object + old_content = json.loads(old_content) + new_content = json.loads(new_content) + + old_keys = set(old_content.keys()) + new_keys = set(new_content.keys()) + + # get the difference + keys_with_diff = old_keys.symmetric_difference(new_keys) + common_keys = old_keys.intersection(new_keys) + # if both have the same key, check its content + for key in common_keys: + if old_content[key] != new_content[key]: + keys_with_diff.add(key) + + # get the model classes + impacted_model_classes = [] + for key in keys_with_diff: + if key in new_keys: + impacted_model_classes.extend(new_content[key]["model_classes"]) + + # get the module where the model classes are defined. We want to use the main `__init__` file, but it requires + # all the framework being installed, which is not ideal for a simple script like test fetcher. + # So we create a temporary and modified main `__init__` and access its `_import_structure`. + with open(folder / "src/transformers/__init__.py") as fp: + lines = fp.readlines() + new_lines = [] + # Get all the code related to `_import_structure` + for line in lines: + if line == "_import_structure = {\n": + new_lines.append(line) + elif line == "# Direct imports for type-checking\n": + break + elif len(new_lines) > 0: + # bypass the framework check so we can get all the information even if frameworks are not available + line = re.sub(r"is_.+_available\(\)", "True", line) + line = line.replace("OptionalDependencyNotAvailable", "Exception") + line = line.replace("Exception()", "Exception") + new_lines.append(line) + + # create and load the temporary module + with tempfile.TemporaryDirectory() as tmpdirname: + with open(os.path.join(tmpdirname, "temp_init.py"), "w") as fp: + fp.write("".join(new_lines)) + + spec = importlib.util.spec_from_file_location("temp_init", os.path.join(tmpdirname, "temp_init.py")) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + # Finally, get `_import_structure` that we need + import_structure = module._import_structure + + # map model classes to their defined module + reversed_structure = {} + for key, values in import_structure.items(): + for value in values: + reversed_structure[value] = key + + # Get the corresponding modeling file path + for model_class in impacted_model_classes: + module = reversed_structure[model_class] + framework = "" + if model_class.startswith("TF"): + framework = "tf" + elif model_class.startswith("Flax"): + framework = "flax" + fn = ( + f"modeling_{module.split('.')[-1]}.py" + if framework == "" + else f"modeling_{framework}_{module.split('.')[-1]}.py" + ) + files.add( + f"src.transformers.{module}.{fn}".replace(".", os.path.sep).replace(f"{os.path.sep}py", ".py") + ) + + return sorted(files) + + +def get_diff(repo: Repo, base_commit: str, commits: List[str]) -> List[str]: + """ + Get the diff between a base commit and one or several commits. + + Args: + repo (`git.Repo`): + A git repository (for instance the Transformers repo). + base_commit (`str`): + The commit reference of where to compare for the diff. This is the current commit, not the branching point! + commits (`List[str]`): + The list of commits with which to compare the repo at `base_commit` (so the branching point). + + Returns: + `List[str]`: The list of Python files with a diff (files added, renamed or deleted are always returned, files + modified are returned if the diff in the file is not only in docstrings or comments, see + `diff_is_docstring_only`). + """ + print("\n### DIFF ###\n") + code_diff = [] + for commit in commits: + for diff_obj in commit.diff(base_commit): + # We always add new python files + if diff_obj.change_type == "A" and diff_obj.b_path.endswith(".py"): + code_diff.append(diff_obj.b_path) + # We check that deleted python files won't break corresponding tests. + elif diff_obj.change_type == "D" and diff_obj.a_path.endswith(".py"): + code_diff.append(diff_obj.a_path) + # Now for modified files + elif diff_obj.change_type in ["M", "R"] and diff_obj.b_path.endswith(".py"): + # In case of renames, we'll look at the tests using both the old and new name. + if diff_obj.a_path != diff_obj.b_path: + code_diff.extend([diff_obj.a_path, diff_obj.b_path]) + else: + # Otherwise, we check modifications are in code and not docstrings. + if diff_is_docstring_only(repo, commit, diff_obj.b_path): + print(f"Ignoring diff in {diff_obj.b_path} as it only concerns docstrings or comments.") + else: + code_diff.append(diff_obj.a_path) + + return code_diff + + +def get_modified_python_files(diff_with_last_commit: bool = False) -> List[str]: + """ + Return a list of python files that have been modified between: + + - the current head and the main branch if `diff_with_last_commit=False` (default) + - the current head and its parent commit otherwise. + + Returns: + `List[str]`: The list of Python files with a diff (files added, renamed or deleted are always returned, files + modified are returned if the diff in the file is not only in docstrings or comments, see + `diff_is_docstring_only`). + """ + repo = Repo(PATH_TO_REPO) + + if not diff_with_last_commit: + print(f"main is at {repo.refs.main.commit}") + print(f"Current head is at {repo.head.commit}") + + branching_commits = repo.merge_base(repo.refs.main, repo.head) + for commit in branching_commits: + print(f"Branching commit: {commit}") + return get_diff(repo, repo.head.commit, branching_commits) + else: + print(f"main is at {repo.head.commit}") + parent_commits = repo.head.commit.parents + for commit in parent_commits: + print(f"Parent commit: {commit}") + return get_diff(repo, repo.head.commit, parent_commits) + + +def get_diff_for_doctesting(repo: Repo, base_commit: str, commits: List[str]) -> List[str]: + """ + Get the diff in doc examples between a base commit and one or several commits. + + Args: + repo (`git.Repo`): + A git repository (for instance the Transformers repo). + base_commit (`str`): + The commit reference of where to compare for the diff. This is the current commit, not the branching point! + commits (`List[str]`): + The list of commits with which to compare the repo at `base_commit` (so the branching point). + + Returns: + `List[str]`: The list of Python and Markdown files with a diff (files added or renamed are always returned, files + modified are returned if the diff in the file is only in doctest examples). + """ + print("\n### DIFF ###\n") + code_diff = [] + for commit in commits: + for diff_obj in commit.diff(base_commit): + # We only consider Python files and doc files. + if not diff_obj.b_path.endswith(".py") and not diff_obj.b_path.endswith(".md"): + continue + # We always add new python/md files + if diff_obj.change_type in ["A"]: + code_diff.append(diff_obj.b_path) + # Now for modified files + elif diff_obj.change_type in ["M", "R"]: + # In case of renames, we'll look at the tests using both the old and new name. + if diff_obj.a_path != diff_obj.b_path: + code_diff.extend([diff_obj.a_path, diff_obj.b_path]) + else: + # Otherwise, we check modifications contain some doc example(s). + if diff_contains_doc_examples(repo, commit, diff_obj.b_path): + code_diff.append(diff_obj.a_path) + else: + print(f"Ignoring diff in {diff_obj.b_path} as it doesn't contain any doc example.") + + return code_diff + + +def get_all_doctest_files() -> List[str]: + """ + Return the complete list of python and Markdown files on which we run doctest. + + At this moment, we restrict this to only take files from `src/` or `docs/source/en/` that are not in `utils/not_doctested.txt`. + + Returns: + `List[str]`: The complete list of Python and Markdown files on which we run doctest. + """ + py_files = [str(x.relative_to(PATH_TO_REPO)) for x in PATH_TO_REPO.glob("**/*.py")] + md_files = [str(x.relative_to(PATH_TO_REPO)) for x in PATH_TO_REPO.glob("**/*.md")] + test_files_to_run = py_files + md_files + + # only include files in `src` or `docs/source/en/` + test_files_to_run = [x for x in test_files_to_run if x.startswith(("src/", "docs/source/en/"))] + # not include init files + test_files_to_run = [x for x in test_files_to_run if not x.endswith(("__init__.py",))] + + # These are files not doctested yet. + with open("utils/not_doctested.txt") as fp: + not_doctested = {x.split(" ")[0] for x in fp.read().strip().split("\n")} + + # So far we don't have 100% coverage for doctest. This line will be removed once we achieve 100%. + test_files_to_run = [x for x in test_files_to_run if x not in not_doctested] + + return sorted(test_files_to_run) + + +def get_new_doctest_files(repo, base_commit, branching_commit) -> List[str]: + """ + Get the list of files that were removed from "utils/not_doctested.txt", between `base_commit` and + `branching_commit`. + + Returns: + `List[str]`: List of files that were removed from "utils/not_doctested.txt". + """ + for diff_obj in branching_commit.diff(base_commit): + # Ignores all but the "utils/not_doctested.txt" file. + if diff_obj.a_path != "utils/not_doctested.txt": + continue + # Loads the two versions + folder = Path(repo.working_dir) + with checkout_commit(repo, branching_commit): + with open(folder / "utils/not_doctested.txt", "r", encoding="utf-8") as f: + old_content = f.read() + with open(folder / "utils/not_doctested.txt", "r", encoding="utf-8") as f: + new_content = f.read() + # Compute the removed lines and return them + removed_content = {x.split(" ")[0] for x in old_content.split("\n")} - { + x.split(" ")[0] for x in new_content.split("\n") + } + return sorted(removed_content) + return [] + + +def get_doctest_files(diff_with_last_commit: bool = False) -> List[str]: + """ + Return a list of python and Markdown files where doc example have been modified between: + + - the current head and the main branch if `diff_with_last_commit=False` (default) + - the current head and its parent commit otherwise. + + Returns: + `List[str]`: The list of Python and Markdown files with a diff (files added or renamed are always returned, files + modified are returned if the diff in the file is only in doctest examples). + """ + repo = Repo(PATH_TO_REPO) + + test_files_to_run = [] # noqa + if not diff_with_last_commit: + print(f"main is at {repo.refs.main.commit}") + print(f"Current head is at {repo.head.commit}") + + branching_commits = repo.merge_base(repo.refs.main, repo.head) + for commit in branching_commits: + print(f"Branching commit: {commit}") + test_files_to_run = get_diff_for_doctesting(repo, repo.head.commit, branching_commits) + else: + print(f"main is at {repo.head.commit}") + parent_commits = repo.head.commit.parents + for commit in parent_commits: + print(f"Parent commit: {commit}") + test_files_to_run = get_diff_for_doctesting(repo, repo.head.commit, parent_commits) + + all_test_files_to_run = get_all_doctest_files() + + # Add to the test files to run any removed entry from "utils/not_doctested.txt". + new_test_files = get_new_doctest_files(repo, repo.head.commit, repo.refs.main.commit) + test_files_to_run = list(set(test_files_to_run + new_test_files)) + + # Do not run slow doctest tests on CircleCI + with open("utils/slow_documentation_tests.txt") as fp: + slow_documentation_tests = set(fp.read().strip().split("\n")) + test_files_to_run = [ + x for x in test_files_to_run if x in all_test_files_to_run and x not in slow_documentation_tests + ] + + # Make sure we did not end up with a test file that was removed + test_files_to_run = [f for f in test_files_to_run if (PATH_TO_REPO / f).exists()] + + return sorted(test_files_to_run) + + +# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. +# \s*from\s+(\.+\S+)\s+import\s+([^\n]+) -> Line only contains from .xxx import yyy and we catch .xxx and yyy +# (?=\n) -> Look-ahead to a new line. We can't just put \n here or using find_all on this re will only catch every +# other import. +_re_single_line_relative_imports = re.compile(r"(?:^|\n)\s*from\s+(\.+\S+)\s+import\s+([^\n]+)(?=\n)") +# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. +# \s*from\s+(\.+\S+)\s+import\s+\(([^\)]+)\) -> Line continues with from .xxx import (yyy) and we catch .xxx and yyy +# yyy will take multiple lines otherwise there wouldn't be parenthesis. +_re_multi_line_relative_imports = re.compile(r"(?:^|\n)\s*from\s+(\.+\S+)\s+import\s+\(([^\)]+)\)") +# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. +# \s*from\s+transformers(\S*)\s+import\s+([^\n]+) -> Line only contains from transformers.xxx import yyy and we catch +# .xxx and yyy +# (?=\n) -> Look-ahead to a new line. We can't just put \n here or using find_all on this re will only catch every +# other import. +_re_single_line_direct_imports = re.compile(r"(?:^|\n)\s*from\s+transformers(\S*)\s+import\s+([^\n]+)(?=\n)") +# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. +# \s*from\s+transformers(\S*)\s+import\s+\(([^\)]+)\) -> Line continues with from transformers.xxx import (yyy) and we +# catch .xxx and yyy. yyy will take multiple lines otherwise there wouldn't be parenthesis. +_re_multi_line_direct_imports = re.compile(r"(?:^|\n)\s*from\s+transformers(\S*)\s+import\s+\(([^\)]+)\)") + + +def extract_imports(module_fname: str, cache: Dict[str, List[str]] = None) -> List[str]: + """ + Get the imports a given module makes. + + Args: + module_fname (`str`): + The name of the file of the module where we want to look at the imports (given relative to the root of + the repo). + cache (Dictionary `str` to `List[str]`, *optional*): + To speed up this function if it was previously called on `module_fname`, the cache of all previously + computed results. + + Returns: + `List[str]`: The list of module filenames imported in the input `module_fname` (a submodule we import from that + is a subfolder will give its init file). + """ + if cache is not None and module_fname in cache: + return cache[module_fname] + + with open(PATH_TO_REPO / module_fname, "r", encoding="utf-8") as f: + content = f.read() + + # Filter out all docstrings to not get imports in code examples. As before we need to deactivate formatting to + # keep this as escaped quotes and avoid this function failing on this file. + splits = content.split('\"\"\"') # fmt: skip + content = "".join(splits[::2]) + + module_parts = str(module_fname).split(os.path.sep) + imported_modules = [] + + # Let's start with relative imports + relative_imports = _re_single_line_relative_imports.findall(content) + relative_imports = [ + (mod, imp) for mod, imp in relative_imports if "# tests_ignore" not in imp and imp.strip() != "(" + ] + multiline_relative_imports = _re_multi_line_relative_imports.findall(content) + relative_imports += [(mod, imp) for mod, imp in multiline_relative_imports if "# tests_ignore" not in imp] + + # We need to remove parts of the module name depending on the depth of the relative imports. + for module, imports in relative_imports: + level = 0 + while module.startswith("."): + module = module[1:] + level += 1 + + if len(module) > 0: + dep_parts = module_parts[: len(module_parts) - level] + module.split(".") + else: + dep_parts = module_parts[: len(module_parts) - level] + imported_module = os.path.sep.join(dep_parts) + imported_modules.append((imported_module, [imp.strip() for imp in imports.split(",")])) + + # Let's continue with direct imports + direct_imports = _re_single_line_direct_imports.findall(content) + direct_imports = [(mod, imp) for mod, imp in direct_imports if "# tests_ignore" not in imp and imp.strip() != "("] + multiline_direct_imports = _re_multi_line_direct_imports.findall(content) + direct_imports += [(mod, imp) for mod, imp in multiline_direct_imports if "# tests_ignore" not in imp] + + # We need to find the relative path of those imports. + for module, imports in direct_imports: + import_parts = module.split(".")[1:] # ignore the name of the repo since we add it below. + dep_parts = ["src", "transformers"] + import_parts + imported_module = os.path.sep.join(dep_parts) + imported_modules.append((imported_module, [imp.strip() for imp in imports.split(",")])) + + result = [] + # Double check we get proper modules (either a python file or a folder with an init). + for module_file, imports in imported_modules: + if (PATH_TO_REPO / f"{module_file}.py").is_file(): + module_file = f"{module_file}.py" + elif (PATH_TO_REPO / module_file).is_dir() and (PATH_TO_REPO / module_file / "__init__.py").is_file(): + module_file = os.path.sep.join([module_file, "__init__.py"]) + imports = [imp for imp in imports if len(imp) > 0 and re.match("^[A-Za-z0-9_]*$", imp)] + if len(imports) > 0: + result.append((module_file, imports)) + + if cache is not None: + cache[module_fname] = result + + return result + + +def get_module_dependencies(module_fname: str, cache: Dict[str, List[str]] = None) -> List[str]: + """ + Refines the result of `extract_imports` to remove subfolders and get a proper list of module filenames: if a file + as an import `from utils import Foo, Bar`, with `utils` being a subfolder containing many files, this will traverse + the `utils` init file to check where those dependencies come from: for instance the files utils/foo.py and utils/bar.py. + + Warning: This presupposes that all intermediate inits are properly built (with imports from the respective + submodules) and work better if objects are defined in submodules and not the intermediate init (otherwise the + intermediate init is added, and inits usually have a lot of dependencies). + + Args: + module_fname (`str`): + The name of the file of the module where we want to look at the imports (given relative to the root of + the repo). + cache (Dictionary `str` to `List[str]`, *optional*): + To speed up this function if it was previously called on `module_fname`, the cache of all previously + computed results. + + Returns: + `List[str]`: The list of module filenames imported in the input `module_fname` (with submodule imports refined). + """ + dependencies = [] + imported_modules = extract_imports(module_fname, cache=cache) + # The while loop is to recursively traverse all inits we may encounter: we will add things as we go. + while len(imported_modules) > 0: + new_modules = [] + for module, imports in imported_modules: + # If we end up in an __init__ we are often not actually importing from this init (except in the case where + # the object is fully defined in the __init__) + if module.endswith("__init__.py"): + # So we get the imports from that init then try to find where our objects come from. + new_imported_modules = extract_imports(module, cache=cache) + for new_module, new_imports in new_imported_modules: + if any(i in new_imports for i in imports): + if new_module not in dependencies: + new_modules.append((new_module, [i for i in new_imports if i in imports])) + imports = [i for i in imports if i not in new_imports] + if len(imports) > 0: + # If there are any objects lefts, they may be a submodule + path_to_module = PATH_TO_REPO / module.replace("__init__.py", "") + dependencies.extend( + [ + os.path.join(module.replace("__init__.py", ""), f"{i}.py") + for i in imports + if (path_to_module / f"{i}.py").is_file() + ] + ) + imports = [i for i in imports if not (path_to_module / f"{i}.py").is_file()] + if len(imports) > 0: + # Then if there are still objects left, they are fully defined in the init, so we keep it as a + # dependency. + dependencies.append(module) + else: + dependencies.append(module) + + imported_modules = new_modules + return dependencies + + +def create_reverse_dependency_tree() -> List[Tuple[str, str]]: + """ + Create a list of all edges (a, b) which mean that modifying a impacts b with a going over all module and test files. + """ + cache = {} + all_modules = list(PATH_TO_TRANFORMERS.glob("**/*.py")) + list(PATH_TO_TESTS.glob("**/*.py")) + all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules] + edges = [(dep, mod) for mod in all_modules for dep in get_module_dependencies(mod, cache=cache)] + + return list(set(edges)) + + +def get_tree_starting_at(module: str, edges: List[Tuple[str, str]]) -> List[Union[str, List[str]]]: + """ + Returns the tree starting at a given module following all edges. + + Args: + module (`str`): The module that will be the root of the subtree we want. + eges (`List[Tuple[str, str]]`): The list of all edges of the tree. + + Returns: + `List[Union[str, List[str]]]`: The tree to print in the following format: [module, [list of edges + starting at module], [list of edges starting at the preceding level], ...] + """ + vertices_seen = [module] + new_edges = [edge for edge in edges if edge[0] == module and edge[1] != module and "__init__.py" not in edge[1]] + tree = [module] + while len(new_edges) > 0: + tree.append(new_edges) + final_vertices = list({edge[1] for edge in new_edges}) + vertices_seen.extend(final_vertices) + new_edges = [ + edge + for edge in edges + if edge[0] in final_vertices and edge[1] not in vertices_seen and "__init__.py" not in edge[1] + ] + + return tree + + +def print_tree_deps_of(module, all_edges=None): + """ + Prints the tree of modules depending on a given module. + + Args: + module (`str`): The module that will be the root of the subtree we want. + all_eges (`List[Tuple[str, str]]`, *optional*): + The list of all edges of the tree. Will be set to `create_reverse_dependency_tree()` if not passed. + """ + if all_edges is None: + all_edges = create_reverse_dependency_tree() + tree = get_tree_starting_at(module, all_edges) + + # The list of lines is a list of tuples (line_to_be_printed, module) + # Keeping the modules lets us know where to insert each new lines in the list. + lines = [(tree[0], tree[0])] + for index in range(1, len(tree)): + edges = tree[index] + start_edges = {edge[0] for edge in edges} + + for start in start_edges: + end_edges = {edge[1] for edge in edges if edge[0] == start} + # We will insert all those edges just after the line showing start. + pos = 0 + while lines[pos][1] != start: + pos += 1 + lines = lines[: pos + 1] + [(" " * (2 * index) + end, end) for end in end_edges] + lines[pos + 1 :] + + for line in lines: + # We don't print the refs that where just here to help build lines. + print(line[0]) + + +def init_test_examples_dependencies() -> Tuple[Dict[str, List[str]], List[str]]: + """ + The test examples do not import from the examples (which are just scripts, not modules) so we need som extra + care initializing the dependency map, which is the goal of this function. It initializes the dependency map for + example files by linking each example to the example test file for the example framework. + + Returns: + `Tuple[Dict[str, List[str]], List[str]]`: A tuple with two elements: the initialized dependency map which is a + dict test example file to list of example files potentially tested by that test file, and the list of all + example files (to avoid recomputing it later). + """ + test_example_deps = {} + all_examples = [] + for framework in ["flax", "pytorch", "tensorflow"]: + test_files = list((PATH_TO_EXAMPLES / framework).glob("test_*.py")) + all_examples.extend(test_files) + # Remove the files at the root of examples/framework since they are not proper examples (they are eith utils + # or example test files). + examples = [ + f for f in (PATH_TO_EXAMPLES / framework).glob("**/*.py") if f.parent != PATH_TO_EXAMPLES / framework + ] + all_examples.extend(examples) + for test_file in test_files: + with open(test_file, "r", encoding="utf-8") as f: + content = f.read() + # Map all examples to the test files found in examples/framework. + test_example_deps[str(test_file.relative_to(PATH_TO_REPO))] = [ + str(e.relative_to(PATH_TO_REPO)) for e in examples if e.name in content + ] + # Also map the test files to themselves. + test_example_deps[str(test_file.relative_to(PATH_TO_REPO))].append( + str(test_file.relative_to(PATH_TO_REPO)) + ) + return test_example_deps, all_examples + + +def create_reverse_dependency_map() -> Dict[str, List[str]]: + """ + Create the dependency map from module/test filename to the list of modules/tests that depend on it recursively. + + Returns: + `Dict[str, List[str]]`: The reverse dependency map as a dictionary mapping filenames to all the filenames + depending on it recursively. This way the tests impacted by a change in file A are the test files in the list + corresponding to key A in this result. + """ + cache = {} + # Start from the example deps init. + example_deps, examples = init_test_examples_dependencies() + # Add all modules and all tests to all examples + all_modules = list(PATH_TO_TRANFORMERS.glob("**/*.py")) + list(PATH_TO_TESTS.glob("**/*.py")) + examples + all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules] + # Compute the direct dependencies of all modules. + direct_deps = {m: get_module_dependencies(m, cache=cache) for m in all_modules} + direct_deps.update(example_deps) + + # This recurses the dependencies + something_changed = True + while something_changed: + something_changed = False + for m in all_modules: + for d in direct_deps[m]: + # We stop recursing at an init (cause we always end up in the main init and we don't want to add all + # files which the main init imports) + if d.endswith("__init__.py"): + continue + if d not in direct_deps: + raise ValueError(f"KeyError:{d}. From {m}") + new_deps = set(direct_deps[d]) - set(direct_deps[m]) + if len(new_deps) > 0: + direct_deps[m].extend(list(new_deps)) + something_changed = True + + # Finally we can build the reverse map. + reverse_map = collections.defaultdict(list) + for m in all_modules: + for d in direct_deps[m]: + reverse_map[d].append(m) + + # For inits, we don't do the reverse deps but the direct deps: if modifying an init, we want to make sure we test + # all the modules impacted by that init. + for m in [f for f in all_modules if f.endswith("__init__.py")]: + direct_deps = get_module_dependencies(m, cache=cache) + deps = sum([reverse_map[d] for d in direct_deps if not d.endswith("__init__.py")], direct_deps) + reverse_map[m] = list(set(deps) - {m}) + + return reverse_map + + +def create_module_to_test_map( + reverse_map: Dict[str, List[str]] = None, filter_models: bool = False +) -> Dict[str, List[str]]: + """ + Extract the tests from the reverse_dependency_map and potentially filters the model tests. + + Args: + reverse_map (`Dict[str, List[str]]`, *optional*): + The reverse dependency map as created by `create_reverse_dependency_map`. Will default to the result of + that function if not provided. + filter_models (`bool`, *optional*, defaults to `False`): + Whether or not to filter model tests to only include core models if a file impacts a lot of models. + + Returns: + `Dict[str, List[str]]`: A dictionary that maps each file to the tests to execute if that file was modified. + """ + if reverse_map is None: + reverse_map = create_reverse_dependency_map() + + # Utility that tells us if a given file is a test (taking test examples into account) + def is_test(fname): + if fname.startswith("tests"): + return True + if fname.startswith("examples") and fname.split(os.path.sep)[-1].startswith("test"): + return True + return False + + # Build the test map + test_map = {module: [f for f in deps if is_test(f)] for module, deps in reverse_map.items()} + + if not filter_models: + return test_map + + # Now we deal with the filtering if `filter_models` is True. + num_model_tests = len(list(PATH_TO_TESTS.glob("models/*"))) + + def has_many_models(tests): + # We filter to core models when a given file impacts more than half the model tests. + model_tests = {Path(t).parts[2] for t in tests if t.startswith("tests/models/")} + return len(model_tests) > num_model_tests // 2 + + def filter_tests(tests): + return [t for t in tests if not t.startswith("tests/models/") or Path(t).parts[2] in IMPORTANT_MODELS] + + return {module: (filter_tests(tests) if has_many_models(tests) else tests) for module, tests in test_map.items()} + + +def check_imports_all_exist(): + """ + Isn't used per se by the test fetcher but might be used later as a quality check. Putting this here for now so the + code is not lost. This checks all imports in a given file do exist. + """ + cache = {} + all_modules = list(PATH_TO_TRANFORMERS.glob("**/*.py")) + list(PATH_TO_TESTS.glob("**/*.py")) + all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules] + direct_deps = {m: get_module_dependencies(m, cache=cache) for m in all_modules} + + for module, deps in direct_deps.items(): + for dep in deps: + if not (PATH_TO_REPO / dep).is_file(): + print(f"{module} has dependency on {dep} which does not exist.") + + +def _print_list(l) -> str: + """ + Pretty print a list of elements with one line per element and a - starting each line. + """ + return "\n".join([f"- {f}" for f in l]) + + +def create_json_map(test_files_to_run: List[str], json_output_file: str): + """ + Creates a map from a list of tests to run to easily split them by category, when running parallelism of slow tests. + + Args: + test_files_to_run (`List[str]`): The list of tests to run. + json_output_file (`str`): The path where to store the built json map. + """ + if json_output_file is None: + return + + test_map = {} + for test_file in test_files_to_run: + # `test_file` is a path to a test folder/file, starting with `tests/`. For example, + # - `tests/models/bert/test_modeling_bert.py` or `tests/models/bert` + # - `tests/trainer/test_trainer.py` or `tests/trainer` + # - `tests/test_modeling_common.py` + names = test_file.split(os.path.sep) + if names[1] == "models": + # take the part like `models/bert` for modeling tests + key = os.path.sep.join(names[1:3]) + elif len(names) > 2 or not test_file.endswith(".py"): + # test folders under `tests` or python files under them + # take the part like tokenization, `pipeline`, etc. for other test categories + key = os.path.sep.join(names[1:2]) + else: + # common test files directly under `tests/` + key = "common" + + if key not in test_map: + test_map[key] = [] + test_map[key].append(test_file) + + # sort the keys & values + keys = sorted(test_map.keys()) + test_map = {k: " ".join(sorted(test_map[k])) for k in keys} + with open(json_output_file, "w", encoding="UTF-8") as fp: + json.dump(test_map, fp, ensure_ascii=False) + + +def infer_tests_to_run( + output_file: str, + diff_with_last_commit: bool = False, + filter_models: bool = True, + json_output_file: Optional[str] = None, +): + """ + The main function called by the test fetcher. Determines the tests to run from the diff. + + Args: + output_file (`str`): + The path where to store the summary of the test fetcher analysis. Other files will be stored in the same + folder: + + - examples_test_list.txt: The list of examples tests to run. + - test_repo_utils.txt: Will indicate if the repo utils tests should be run or not. + - doctest_list.txt: The list of doctests to run. + + diff_with_last_commit (`bool`, *optional*, defaults to `False`): + Whether to analyze the diff with the last commit (for use on the main branch after a PR is merged) or with + the branching point from main (for use on each PR). + filter_models (`bool`, *optional*, defaults to `True`): + Whether or not to filter the tests to core models only, when a file modified results in a lot of model + tests. + json_output_file (`str`, *optional*): + The path where to store the json file mapping categories of tests to tests to run (used for parallelism or + the slow tests). + """ + modified_files = get_modified_python_files(diff_with_last_commit=diff_with_last_commit) + print(f"\n### MODIFIED FILES ###\n{_print_list(modified_files)}") + + # Create the map that will give us all impacted modules. + reverse_map = create_reverse_dependency_map() + impacted_files = modified_files.copy() + for f in modified_files: + if f in reverse_map: + impacted_files.extend(reverse_map[f]) + + # Remove duplicates + impacted_files = sorted(set(impacted_files)) + print(f"\n### IMPACTED FILES ###\n{_print_list(impacted_files)}") + + # Grab the corresponding test files: + if any(x in modified_files for x in ["setup.py", ".circleci/create_circleci_config.py"]): + test_files_to_run = ["tests", "examples"] + repo_utils_launch = True + else: + # All modified tests need to be run. + test_files_to_run = [ + f for f in modified_files if f.startswith("tests") and f.split(os.path.sep)[-1].startswith("test") + ] + impacted_files = get_impacted_files_from_tiny_model_summary(diff_with_last_commit=diff_with_last_commit) + + # Then we grab the corresponding test files. + test_map = create_module_to_test_map(reverse_map=reverse_map, filter_models=filter_models) + for f in modified_files + impacted_files: + if f in test_map: + test_files_to_run.extend(test_map[f]) + test_files_to_run = sorted(set(test_files_to_run)) + # Remove repo utils tests + test_files_to_run = [f for f in test_files_to_run if not f.split(os.path.sep)[1] == "repo_utils"] + # Remove SageMaker tests + test_files_to_run = [f for f in test_files_to_run if not f.split(os.path.sep)[1] == "sagemaker"] + # Make sure we did not end up with a test file that was removed + test_files_to_run = [f for f in test_files_to_run if (PATH_TO_REPO / f).exists()] + + repo_utils_launch = any(f.split(os.path.sep)[0] == "utils" for f in modified_files) + + if repo_utils_launch: + repo_util_file = Path(output_file).parent / "test_repo_utils.txt" + with open(repo_util_file, "w", encoding="utf-8") as f: + f.write("tests/repo_utils") + + examples_tests_to_run = [f for f in test_files_to_run if f.startswith("examples")] + test_files_to_run = [f for f in test_files_to_run if not f.startswith("examples")] + print(f"\n### TEST TO RUN ###\n{_print_list(test_files_to_run)}") + if len(test_files_to_run) > 0: + with open(output_file, "w", encoding="utf-8") as f: + f.write(" ".join(test_files_to_run)) + + # Create a map that maps test categories to test files, i.e. `models/bert` -> [...test_modeling_bert.py, ...] + + # Get all test directories (and some common test files) under `tests` and `tests/models` if `test_files_to_run` + # contains `tests` (i.e. when `setup.py` is changed). + if "tests" in test_files_to_run: + test_files_to_run = get_all_tests() + + create_json_map(test_files_to_run, json_output_file) + + print(f"\n### EXAMPLES TEST TO RUN ###\n{_print_list(examples_tests_to_run)}") + if len(examples_tests_to_run) > 0: + # We use `all` in the case `commit_flags["test_all"]` as well as in `create_circleci_config.py` for processing + if examples_tests_to_run == ["examples"]: + examples_tests_to_run = ["all"] + example_file = Path(output_file).parent / "examples_test_list.txt" + with open(example_file, "w", encoding="utf-8") as f: + f.write(" ".join(examples_tests_to_run)) + + doctest_list = get_doctest_files() + + print(f"\n### DOCTEST TO RUN ###\n{_print_list(doctest_list)}") + if len(doctest_list) > 0: + doctest_file = Path(output_file).parent / "doctest_list.txt" + with open(doctest_file, "w", encoding="utf-8") as f: + f.write(" ".join(doctest_list)) + + +def filter_tests(output_file: str, filters: List[str]): + """ + Reads the content of the output file and filters out all the tests in a list of given folders. + + Args: + output_file (`str` or `os.PathLike`): The path to the output file of the tests fetcher. + filters (`List[str]`): A list of folders to filter. + """ + if not os.path.isfile(output_file): + print("No test file found.") + return + with open(output_file, "r", encoding="utf-8") as f: + test_files = f.read().split(" ") + + if len(test_files) == 0 or test_files == [""]: + print("No tests to filter.") + return + + if test_files == ["tests"]: + test_files = [os.path.join("tests", f) for f in os.listdir("tests") if f not in ["__init__.py"] + filters] + else: + test_files = [f for f in test_files if f.split(os.path.sep)[1] not in filters] + + with open(output_file, "w", encoding="utf-8") as f: + f.write(" ".join(test_files)) + + +def parse_commit_message(commit_message: str) -> Dict[str, bool]: + """ + Parses the commit message to detect if a command is there to skip, force all or part of the CI. + + Args: + commit_message (`str`): The commit message of the current commit. + + Returns: + `Dict[str, bool]`: A dictionary of strings to bools with keys the following keys: `"skip"`, + `"test_all_models"` and `"test_all"`. + """ + if commit_message is None: + return {"skip": False, "no_filter": False, "test_all": False} + + command_search = re.search(r"\[([^\]]*)\]", commit_message) + if command_search is not None: + command = command_search.groups()[0] + command = command.lower().replace("-", " ").replace("_", " ") + skip = command in ["ci skip", "skip ci", "circleci skip", "skip circleci"] + no_filter = set(command.split(" ")) == {"no", "filter"} + test_all = set(command.split(" ")) == {"test", "all"} + return {"skip": skip, "no_filter": no_filter, "test_all": test_all} + else: + return {"skip": False, "no_filter": False, "test_all": False} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--output_file", type=str, default="test_list.txt", help="Where to store the list of tests to run" + ) + parser.add_argument( + "--json_output_file", + type=str, + default="test_map.json", + help="Where to store the tests to run in a dictionary format mapping test categories to test files", + ) + parser.add_argument( + "--diff_with_last_commit", + action="store_true", + help="To fetch the tests between the current commit and the last commit", + ) + parser.add_argument( + "--filter_tests", + action="store_true", + help="Will filter the pipeline/repo utils tests outside of the generated list of tests.", + ) + parser.add_argument( + "--print_dependencies_of", + type=str, + help="Will only print the tree of modules depending on the file passed.", + default=None, + ) + parser.add_argument( + "--commit_message", + type=str, + help="The commit message (which could contain a command to force all tests or skip the CI).", + default=None, + ) + args = parser.parse_args() + if args.print_dependencies_of is not None: + print_tree_deps_of(args.print_dependencies_of) + elif args.filter_tests: + filter_tests(args.output_file, ["pipelines", "repo_utils"]) + else: + repo = Repo(PATH_TO_REPO) + commit_message = repo.head.commit.message + commit_flags = parse_commit_message(commit_message) + if commit_flags["skip"]: + print("Force-skipping the CI") + quit() + if commit_flags["no_filter"]: + print("Running all tests fetched without filtering.") + if commit_flags["test_all"]: + print("Force-launching all tests") + + diff_with_last_commit = args.diff_with_last_commit + if not diff_with_last_commit and not repo.head.is_detached and repo.head.ref == repo.refs.main: + print("main branch detected, fetching tests against last commit.") + diff_with_last_commit = True + + if not commit_flags["test_all"]: + try: + infer_tests_to_run( + args.output_file, + diff_with_last_commit=diff_with_last_commit, + json_output_file=args.json_output_file, + filter_models=not commit_flags["no_filter"], + ) + filter_tests(args.output_file, ["repo_utils"]) + except Exception as e: + print(f"\nError when trying to grab the relevant tests: {e}\n\nRunning all tests.") + commit_flags["test_all"] = True + + if commit_flags["test_all"]: + with open(args.output_file, "w", encoding="utf-8") as f: + f.write("tests") + example_file = Path(args.output_file).parent / "examples_test_list.txt" + with open(example_file, "w", encoding="utf-8") as f: + f.write("all") + + test_files_to_run = get_all_tests() + create_json_map(test_files_to_run, args.json_output_file) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/tf_ops/onnx.json b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/tf_ops/onnx.json new file mode 100644 index 0000000000000000000000000000000000000000..a468145d66eb541bd39ef57d25be6263500491d7 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/tf_ops/onnx.json @@ -0,0 +1,245 @@ +{ + "opsets": { + "1": [ + "Abs", + "Add", + "AddV2", + "ArgMax", + "ArgMin", + "AvgPool", + "AvgPool3D", + "BatchMatMul", + "BatchMatMulV2", + "BatchToSpaceND", + "BiasAdd", + "BiasAddV1", + "Cast", + "Ceil", + "CheckNumerics", + "ComplexAbs", + "Concat", + "ConcatV2", + "Const", + "ConstV2", + "Conv1D", + "Conv2D", + "Conv2DBackpropInput", + "Conv3D", + "Conv3DBackpropInputV2", + "DepthToSpace", + "DepthwiseConv2d", + "DepthwiseConv2dNative", + "Div", + "Dropout", + "Elu", + "Equal", + "Erf", + "Exp", + "ExpandDims", + "Flatten", + "Floor", + "Gather", + "GatherNd", + "GatherV2", + "Greater", + "Identity", + "IdentityN", + "If", + "LRN", + "LSTMBlockCell", + "LeakyRelu", + "Less", + "Log", + "LogSoftmax", + "LogicalAnd", + "LogicalNot", + "LogicalOr", + "LookupTableSizeV2", + "MatMul", + "Max", + "MaxPool", + "MaxPool3D", + "MaxPoolV2", + "Maximum", + "Mean", + "Min", + "Minimum", + "MirrorPad", + "Mul", + "Neg", + "NoOp", + "NotEqual", + "OneHot", + "Pack", + "Pad", + "PadV2", + "Placeholder", + "PlaceholderV2", + "PlaceholderWithDefault", + "Pow", + "Prod", + "RFFT", + "RandomNormal", + "RandomNormalLike", + "RandomUniform", + "RandomUniformLike", + "RealDiv", + "Reciprocal", + "Relu", + "Relu6", + "Reshape", + "Rsqrt", + "Selu", + "Shape", + "Sigmoid", + "Sign", + "Size", + "Slice", + "Softmax", + "Softplus", + "Softsign", + "SpaceToBatchND", + "SpaceToDepth", + "Split", + "SplitV", + "Sqrt", + "Square", + "SquaredDifference", + "Squeeze", + "StatelessIf", + "StopGradient", + "StridedSlice", + "StringJoin", + "Sub", + "Sum", + "Tanh", + "Tile", + "TopKV2", + "Transpose", + "TruncateDiv", + "Unpack", + "ZerosLike" + ], + "2": [], + "3": [], + "4": [], + "5": [], + "6": [ + "AddN", + "All", + "Any", + "FloorDiv", + "FusedBatchNorm", + "FusedBatchNormV2", + "FusedBatchNormV3" + ], + "7": [ + "Acos", + "Asin", + "Atan", + "Cos", + "Fill", + "FloorMod", + "GreaterEqual", + "LessEqual", + "Loop", + "MatrixBandPart", + "Multinomial", + "Range", + "ResizeBilinear", + "ResizeNearestNeighbor", + "Scan", + "Select", + "SelectV2", + "Sin", + "SoftmaxCrossEntropyWithLogits", + "SparseSoftmaxCrossEntropyWithLogits", + "StatelessWhile", + "Tan", + "TensorListFromTensor", + "TensorListGetItem", + "TensorListLength", + "TensorListReserve", + "TensorListResize", + "TensorListSetItem", + "TensorListStack", + "While" + ], + "8": [ + "BroadcastTo", + "ClipByValue", + "FIFOQueueV2", + "HashTableV2", + "IteratorGetNext", + "IteratorV2", + "LookupTableFindV2", + "MaxPoolWithArgmax", + "QueueDequeueManyV2", + "QueueDequeueUpToV2", + "QueueDequeueV2", + "ReverseSequence" + ], + "9": [ + "SegmentMax", + "SegmentMean", + "SegmentMin", + "SegmentProd", + "SegmentSum", + "Sinh", + "SparseSegmentMean", + "SparseSegmentMeanWithNumSegments", + "SparseSegmentSqrtN", + "SparseSegmentSqrtNWithNumSegments", + "SparseSegmentSum", + "SparseSegmentSumWithNumSegments", + "UnsortedSegmentMax", + "UnsortedSegmentMin", + "UnsortedSegmentProd", + "UnsortedSegmentSum", + "Where" + ], + "10": [ + "CropAndResize", + "CudnnRNN", + "DynamicStitch", + "FakeQuantWithMinMaxArgs", + "IsFinite", + "IsInf", + "NonMaxSuppressionV2", + "NonMaxSuppressionV3", + "NonMaxSuppressionV4", + "NonMaxSuppressionV5", + "ParallelDynamicStitch", + "ReverseV2", + "Roll" + ], + "11": [ + "Bincount", + "Cumsum", + "InvertPermutation", + "LeftShift", + "MatrixDeterminant", + "MatrixDiagPart", + "MatrixDiagPartV2", + "MatrixDiagPartV3", + "RaggedRange", + "RightShift", + "Round", + "ScatterNd", + "SparseFillEmptyRows", + "SparseReshape", + "SparseToDense", + "TensorScatterUpdate", + "Unique" + ], + "12": [ + "Einsum", + "MatrixDiag", + "MatrixDiagV2", + "MatrixDiagV3", + "MatrixSetDiagV3", + "SquaredDistance" + ], + "13": [] + } +} \ No newline at end of file diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/update_metadata.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/update_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..2104d53b6e6f2752d4a447fc50f734c2cd198de0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/update_metadata.py @@ -0,0 +1,339 @@ +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Utility that updates the metadata of the Transformers library in the repository `huggingface/transformers-metadata`. + +Usage for an update (as used by the GitHub action `update_metadata`): + +```bash +python utils/update_metadata.py --token --commit_sha +``` + +Usage to check all pipelines are properly defined in the constant `PIPELINE_TAGS_AND_AUTO_MODELS` of this script, so +that new pipelines are properly added as metadata (as used in `make repo-consistency`): + +```bash +python utils/update_metadata.py --check-only +``` +""" +import argparse +import collections +import os +import re +import tempfile +from typing import Dict, List, Tuple + +import pandas as pd +from datasets import Dataset +from huggingface_hub import hf_hub_download, upload_folder + +from transformers.utils import direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/update_metadata.py +TRANSFORMERS_PATH = "src/transformers" + + +# This is to make sure the transformers module imported is the one in the repo. +transformers_module = direct_transformers_import(TRANSFORMERS_PATH) + + +# Regexes that match TF/Flax/PT model names. +_re_tf_models = re.compile(r"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") +_re_flax_models = re.compile(r"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") +# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. +_re_pt_models = re.compile(r"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") + + +# Fill this with tuples (pipeline_tag, model_mapping, auto_model) +PIPELINE_TAGS_AND_AUTO_MODELS = [ + ("pretraining", "MODEL_FOR_PRETRAINING_MAPPING_NAMES", "AutoModelForPreTraining"), + ("feature-extraction", "MODEL_MAPPING_NAMES", "AutoModel"), + ("audio-classification", "MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES", "AutoModelForAudioClassification"), + ("text-generation", "MODEL_FOR_CAUSAL_LM_MAPPING_NAMES", "AutoModelForCausalLM"), + ("automatic-speech-recognition", "MODEL_FOR_CTC_MAPPING_NAMES", "AutoModelForCTC"), + ("image-classification", "MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES", "AutoModelForImageClassification"), + ("image-segmentation", "MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES", "AutoModelForImageSegmentation"), + ("image-to-image", "MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES", "AutoModelForImageToImage"), + ("fill-mask", "MODEL_FOR_MASKED_LM_MAPPING_NAMES", "AutoModelForMaskedLM"), + ("object-detection", "MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES", "AutoModelForObjectDetection"), + ( + "zero-shot-object-detection", + "MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES", + "AutoModelForZeroShotObjectDetection", + ), + ("question-answering", "MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES", "AutoModelForQuestionAnswering"), + ("text2text-generation", "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES", "AutoModelForSeq2SeqLM"), + ("text-classification", "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES", "AutoModelForSequenceClassification"), + ("automatic-speech-recognition", "MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES", "AutoModelForSpeechSeq2Seq"), + ( + "table-question-answering", + "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES", + "AutoModelForTableQuestionAnswering", + ), + ("token-classification", "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES", "AutoModelForTokenClassification"), + ("multiple-choice", "MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES", "AutoModelForMultipleChoice"), + ( + "next-sentence-prediction", + "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES", + "AutoModelForNextSentencePrediction", + ), + ( + "audio-frame-classification", + "MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES", + "AutoModelForAudioFrameClassification", + ), + ("audio-xvector", "MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES", "AutoModelForAudioXVector"), + ( + "document-question-answering", + "MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES", + "AutoModelForDocumentQuestionAnswering", + ), + ( + "visual-question-answering", + "MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES", + "AutoModelForVisualQuestionAnswering", + ), + ("image-to-text", "MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES", "AutoModelForVision2Seq"), + ( + "zero-shot-image-classification", + "MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES", + "AutoModelForZeroShotImageClassification", + ), + ("depth-estimation", "MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES", "AutoModelForDepthEstimation"), + ("video-classification", "MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES", "AutoModelForVideoClassification"), + ("mask-generation", "MODEL_FOR_MASK_GENERATION_MAPPING_NAMES", "AutoModelForMaskGeneration"), + ("text-to-audio", "MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES", "AutoModelForTextToSpectrogram"), + ("text-to-audio", "MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES", "AutoModelForTextToWaveform"), +] + + +def camel_case_split(identifier: str) -> List[str]: + """ + Split a camel-cased name into words. + + Args: + identifier (`str`): The camel-cased name to parse. + + Returns: + `List[str]`: The list of words in the identifier (as seprated by capital letters). + + Example: + + ```py + >>> camel_case_split("CamelCasedClass") + ["Camel", "Cased", "Class"] + ``` + """ + # Regex thanks to https://stackoverflow.com/questions/29916065/how-to-do-camelcase-split-in-python + matches = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)", identifier) + return [m.group(0) for m in matches] + + +def get_frameworks_table() -> pd.DataFrame: + """ + Generates a dataframe containing the supported auto classes for each model type, using the content of the auto + modules. + """ + # Dictionary model names to config. + config_maping_names = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES + model_prefix_to_model_type = { + config.replace("Config", ""): model_type for model_type, config in config_maping_names.items() + } + + # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. + pt_models = collections.defaultdict(bool) + tf_models = collections.defaultdict(bool) + flax_models = collections.defaultdict(bool) + + # Let's lookup through all transformers object (once) and find if models are supported by a given backend. + for attr_name in dir(transformers_module): + lookup_dict = None + if _re_tf_models.match(attr_name) is not None: + lookup_dict = tf_models + attr_name = _re_tf_models.match(attr_name).groups()[0] + elif _re_flax_models.match(attr_name) is not None: + lookup_dict = flax_models + attr_name = _re_flax_models.match(attr_name).groups()[0] + elif _re_pt_models.match(attr_name) is not None: + lookup_dict = pt_models + attr_name = _re_pt_models.match(attr_name).groups()[0] + + if lookup_dict is not None: + while len(attr_name) > 0: + if attr_name in model_prefix_to_model_type: + lookup_dict[model_prefix_to_model_type[attr_name]] = True + break + # Try again after removing the last word in the name + attr_name = "".join(camel_case_split(attr_name)[:-1]) + + all_models = set(list(pt_models.keys()) + list(tf_models.keys()) + list(flax_models.keys())) + all_models = list(all_models) + all_models.sort() + + data = {"model_type": all_models} + data["pytorch"] = [pt_models[t] for t in all_models] + data["tensorflow"] = [tf_models[t] for t in all_models] + data["flax"] = [flax_models[t] for t in all_models] + + # Now let's find the right processing class for each model. In order we check if there is a Processor, then a + # Tokenizer, then a FeatureExtractor, then an ImageProcessor + processors = {} + for t in all_models: + if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: + processors[t] = "AutoProcessor" + elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: + processors[t] = "AutoTokenizer" + elif t in transformers_module.models.auto.image_processing_auto.IMAGE_PROCESSOR_MAPPING_NAMES: + processors[t] = "AutoImageProcessor" + elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: + processors[t] = "AutoFeatureExtractor" + else: + # Default to AutoTokenizer if a model has nothing, for backward compatibility. + processors[t] = "AutoTokenizer" + + data["processor"] = [processors[t] for t in all_models] + + return pd.DataFrame(data) + + +def update_pipeline_and_auto_class_table(table: Dict[str, Tuple[str, str]]) -> Dict[str, Tuple[str, str]]: + """ + Update the table maping models to pipelines and auto classes without removing old keys if they don't exist anymore. + + Args: + table (`Dict[str, Tuple[str, str]]`): + The existing table mapping model names to a tuple containing the pipeline tag and the auto-class name with + which they should be used. + + Returns: + `Dict[str, Tuple[str, str]]`: The updated table in the same format. + """ + auto_modules = [ + transformers_module.models.auto.modeling_auto, + transformers_module.models.auto.modeling_tf_auto, + transformers_module.models.auto.modeling_flax_auto, + ] + for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: + model_mappings = [model_mapping, f"TF_{model_mapping}", f"FLAX_{model_mapping}"] + auto_classes = [auto_class, f"TF_{auto_class}", f"Flax_{auto_class}"] + # Loop through all three frameworks + for module, cls, mapping in zip(auto_modules, auto_classes, model_mappings): + # The type of pipeline may not exist in this framework + if not hasattr(module, mapping): + continue + # First extract all model_names + model_names = [] + for name in getattr(module, mapping).values(): + if isinstance(name, str): + model_names.append(name) + else: + model_names.extend(list(name)) + + # Add pipeline tag and auto model class for those models + table.update({model_name: (pipeline_tag, cls) for model_name in model_names}) + + return table + + +def update_metadata(token: str, commit_sha: str): + """ + Update the metadata for the Transformers repo in `huggingface/transformers-metadata`. + + Args: + token (`str`): A valid token giving write access to `huggingface/transformers-metadata`. + commit_sha (`str`): The commit SHA on Transformers corresponding to this update. + """ + frameworks_table = get_frameworks_table() + frameworks_dataset = Dataset.from_pandas(frameworks_table) + + resolved_tags_file = hf_hub_download( + "huggingface/transformers-metadata", "pipeline_tags.json", repo_type="dataset", token=token + ) + tags_dataset = Dataset.from_json(resolved_tags_file) + table = { + tags_dataset[i]["model_class"]: (tags_dataset[i]["pipeline_tag"], tags_dataset[i]["auto_class"]) + for i in range(len(tags_dataset)) + } + table = update_pipeline_and_auto_class_table(table) + + # Sort the model classes to avoid some nondeterministic updates to create false update commits. + model_classes = sorted(table.keys()) + tags_table = pd.DataFrame( + { + "model_class": model_classes, + "pipeline_tag": [table[m][0] for m in model_classes], + "auto_class": [table[m][1] for m in model_classes], + } + ) + tags_dataset = Dataset.from_pandas(tags_table) + + with tempfile.TemporaryDirectory() as tmp_dir: + frameworks_dataset.to_json(os.path.join(tmp_dir, "frameworks.json")) + tags_dataset.to_json(os.path.join(tmp_dir, "pipeline_tags.json")) + + if commit_sha is not None: + commit_message = ( + f"Update with commit {commit_sha}\n\nSee: " + f"https://github.com/huggingface/transformers/commit/{commit_sha}" + ) + else: + commit_message = "Update" + + upload_folder( + repo_id="huggingface/transformers-metadata", + folder_path=tmp_dir, + repo_type="dataset", + token=token, + commit_message=commit_message, + ) + + +def check_pipeline_tags(): + """ + Check all pipeline tags are properly defined in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant of this script. + """ + in_table = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} + pipeline_tasks = transformers_module.pipelines.SUPPORTED_TASKS + missing = [] + for key in pipeline_tasks: + if key not in in_table: + model = pipeline_tasks[key]["pt"] + if isinstance(model, (list, tuple)): + model = model[0] + model = model.__name__ + if model not in in_table.values(): + missing.append(key) + + if len(missing) > 0: + msg = ", ".join(missing) + raise ValueError( + "The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside " + f"`utils/update_metadata.py`: {msg}. Please add them!" + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--token", type=str, help="The token to use to push to the transformers-metadata dataset.") + parser.add_argument("--commit_sha", type=str, help="The sha of the commit going with this update.") + parser.add_argument("--check-only", action="store_true", help="Activate to just check all pipelines are present.") + args = parser.parse_args() + + if args.check_only: + check_pipeline_tags() + else: + update_metadata(args.token, args.commit_sha) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/update_tiny_models.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/update_tiny_models.py new file mode 100644 index 0000000000000000000000000000000000000000..2e40990691ad5fcf421d6598623c529067b1d7a2 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/update_tiny_models.py @@ -0,0 +1,200 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""A script running `create_dummy_models.py` with a pre-defined set of arguments. + +This file is intended to be used in a CI workflow file without the need of specifying arguments. It creates and uploads +tiny models for all model classes (if their tiny versions are not on the Hub yet), as well as produces an updated +version of `tests/utils/tiny_model_summary.json`. That updated file should be merged into the `main` branch of +`transformers` so the pipeline testing will use the latest created/updated tiny models. +""" + + +import argparse +import copy +import json +import multiprocessing +import os +import time + +from create_dummy_models import COMPOSITE_MODELS, create_tiny_models +from huggingface_hub import ModelFilter, hf_api + +import transformers +from transformers import AutoFeatureExtractor, AutoImageProcessor, AutoTokenizer +from transformers.image_processing_utils import BaseImageProcessor + + +def get_all_model_names(): + model_names = set() + # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way. + for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]: + module = getattr(transformers.models.auto, module_name, None) + if module is None: + continue + # all mappings in a single auto modeling file + mapping_names = [ + x + for x in dir(module) + if x.endswith("_MAPPING_NAMES") + and (x.startswith("MODEL_") or x.startswith("TF_MODEL_") or x.startswith("FLAX_MODEL_")) + ] + for name in mapping_names: + mapping = getattr(module, name) + if mapping is not None: + for v in mapping.values(): + if isinstance(v, (list, tuple)): + model_names.update(v) + elif isinstance(v, str): + model_names.add(v) + + return sorted(model_names) + + +def get_tiny_model_names_from_repo(): + # All model names defined in auto mappings + model_names = set(get_all_model_names()) + + with open("tests/utils/tiny_model_summary.json") as fp: + tiny_model_info = json.load(fp) + tiny_models_names = set() + for model_base_name in tiny_model_info: + tiny_models_names.update(tiny_model_info[model_base_name]["model_classes"]) + + # Remove a tiny model name if one of its framework implementation hasn't yet a tiny version on the Hub. + not_on_hub = model_names.difference(tiny_models_names) + for model_name in copy.copy(tiny_models_names): + if not model_name.startswith("TF") and f"TF{model_name}" in not_on_hub: + tiny_models_names.remove(model_name) + elif model_name.startswith("TF") and model_name[2:] in not_on_hub: + tiny_models_names.remove(model_name) + + return sorted(tiny_models_names) + + +def get_tiny_model_summary_from_hub(output_path): + special_models = COMPOSITE_MODELS.values() + + # All tiny model base names on Hub + model_names = get_all_model_names() + models = hf_api.list_models( + filter=ModelFilter( + author="hf-internal-testing", + ) + ) + _models = set() + for x in models: + model = x.modelId + org, model = model.split("/") + if not model.startswith("tiny-random-"): + continue + model = model.replace("tiny-random-", "") + if not model[0].isupper(): + continue + if model not in model_names and model not in special_models: + continue + _models.add(model) + + models = sorted(_models) + # All tiny model names on Hub + summary = {} + for model in models: + repo_id = f"hf-internal-testing/tiny-random-{model}" + model = model.split("-")[0] + try: + repo_info = hf_api.repo_info(repo_id) + content = { + "tokenizer_classes": set(), + "processor_classes": set(), + "model_classes": set(), + "sha": repo_info.sha, + } + except Exception: + continue + try: + time.sleep(1) + tokenizer_fast = AutoTokenizer.from_pretrained(repo_id) + content["tokenizer_classes"].add(tokenizer_fast.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + tokenizer_slow = AutoTokenizer.from_pretrained(repo_id, use_fast=False) + content["tokenizer_classes"].add(tokenizer_slow.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + img_p = AutoImageProcessor.from_pretrained(repo_id) + content["processor_classes"].add(img_p.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + feat_p = AutoFeatureExtractor.from_pretrained(repo_id) + if not isinstance(feat_p, BaseImageProcessor): + content["processor_classes"].add(feat_p.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + model_class = getattr(transformers, model) + m = model_class.from_pretrained(repo_id) + content["model_classes"].add(m.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + model_class = getattr(transformers, f"TF{model}") + m = model_class.from_pretrained(repo_id) + content["model_classes"].add(m.__class__.__name__) + except Exception: + pass + + content["tokenizer_classes"] = sorted(content["tokenizer_classes"]) + content["processor_classes"] = sorted(content["processor_classes"]) + content["model_classes"] = sorted(content["model_classes"]) + + summary[model] = content + with open(os.path.join(output_path, "hub_tiny_model_summary.json"), "w") as fp: + json.dump(summary, fp, ensure_ascii=False, indent=4) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--num_workers", default=1, type=int, help="The number of workers to run.") + args = parser.parse_args() + + # This has to be `spawn` to avoid hanging forever! + multiprocessing.set_start_method("spawn") + + output_path = "tiny_models" + all = True + model_types = None + models_to_skip = get_tiny_model_names_from_repo() + no_check = True + upload = True + organization = "hf-internal-testing" + + create_tiny_models( + output_path, + all, + model_types, + models_to_skip, + no_check, + upload, + organization, + token=os.environ.get("TOKEN", None), + num_workers=args.num_workers, + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5f237d99d1263024f7bd1e2040ed15fd9ed21eb3 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/utils.py @@ -0,0 +1,27 @@ +import pandas as pd +import json +import torch +import torch.nn as nn +import torch.nn.functional as F + + +def read_data_source_target(file_name, return_num=False, return_json=False): + """ + file_name: a .json file containing a list of items, each has 'input_text', 'target_text', as keys + """ + with open(file_name, 'r', encoding='utf-8') as f: + data = json.load(f) + + if return_json: + if return_num: + return data, len(data) + return data + + keys = list(data[0].keys()) + source_target_pair = [] + for item in data: + source_target_pair.append([item[key] for key in keys]) + + if return_num: + return pd.DataFrame(source_target_pair, columns=keys), len(data) + return pd.DataFrame(source_target_pair, columns=keys) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/visualization.ipynb b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/visualization.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..624dc567d48829ccc34f93bce701d9d03137adac --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/visualization.ipynb @@ -0,0 +1,170 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import json\n", + "import matplotlib.pyplot as plt\n", + "from eval_qa import eval_file\n", + "import matplotlib.colors as mcolors\n", + "import seaborn as sns" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "# replace with your actual training steps for the examined checkpoints\n", + "x = np.array([2000*i for i in range(1, 21)] + [50000 * (i+1) for i in range(100)])/1e5\n", + "x = x[:33]" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "with open(\"local_dir/counterfactual_comparison.json\", \"r\", encoding='utf-8') as f:\n", + " results = json.load(f)\n", + "\n", + "def flatten(d):\n", + " res = dict()\n", + " for item in d:\n", + " for key, val in item.items():\n", + " if key not in res:\n", + " res[key] = []\n", + " res[key].append(val)\n", + " return res\n", + "\n", + "result_list = []\n", + "for item in results:\n", + " temp = flatten(item)\n", + " for key, val in temp.items():\n", + " if \"rank\" in key:\n", + " temp[key] = np.mean(1/(np.array(val)+1)) # MRR\n", + " else:\n", + " temp[key] = 1 - np.mean(np.array(val)==0) # ACC\n", + " result_list.append(temp)\n", + "result_dict = flatten(result_list)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAASgAAAFsCAYAAAB/ziRjAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/SrBM8AAAACXBIWXMAAA9hAAAPYQGoP6dpAABDqUlEQVR4nO3de1wU973/8RdoAFl2QaKwoCgmJOIF7z8otrUXCHASU3xYa4wXFMFLjLFqjlTaRDFqUKPUYPVwWhSJl6o1iSdJPUbBEomxmtBgWrVGVBTDLdHKcgmwuvv7w+M2Gy4ysAxL+Dwfj3mEnf3OzGc2+OY7352Lg9lsNiOEEHbIsaMLEEKIpkhACSHslgSUEMJuSUAJIeyWBJQQwm5JQAkh7JYElBDCbklACSHslgSUEMJuSUAJIeyWBJQQwm5JQAkh7JYElLBy7do1FixYwIABA3BxcSEgIIBf//rXfP311x1dWqM6W71Cme4dXUBXcuvWLTZv3szRo0e5fPky1dXV9OvXj9jYWJYtW4ajY8f+vTh9+jSRkZG4u7sTGxuLr68vH3/8MRs2bKCwsJC9e/d2aH3f1tnqFa1gFqrZt2+fOTAw0Pziiy+at23bZt68ebM5NDTUDJjXr1/fobV99dVX5t69e5t/8pOfmKurq63eS0hIMAPmL774ooOqa6iz1StaR3pQKho/fjzPPPOM1bwFCxYQGBjIO++8Q0JCQgdVBq+++iq3b98mJSWFmpoaampqLO8NHToUgEuXLuHr69tRJVrpbPWK1pGAUpFGowHAbDZTWVlJfX09AF5eXtTV1XVYXWazmT/+8Y8YjUZGjhzZZDsPDw8ADhw4QGpqKvn5+fTq1YvCwkJ1Cv0/Suqtq6tj4cKFZGdn8+WXX+Lj48MLL7zACy+8oGLForUkoFR04MABtm3bxpkzZxoM4j777LMdVBWUl5dTUlJCTEwMM2bMaLLd4MGDAejZsycLFy6krKyM3/72t2qVaaGk3vr6evR6PUePHuWRRx7hs88+IzIyEm9vbyZPnqxi1aI1JKBUkpCQwGuvvcaTTz7Jpk2b8PPzw8XFhcuXLzN//vxmewLtraKiAoC+ffsSHh7+wPZPPPEEAIcOHWrPspqkpN6HHnqI1atXW16PGDGCn/3sZ3z44YcSUJ2AnGagghs3brBx40amTp3Kn//8Z5577jnGjx9PeHg4RUVFAIwaNarD6uvbty/Ozs68/fbb1NbWNnj/q6++4u7dux1QWePaUq/RaCQ3N5dhw4a1d5nCBqQHpYKioiLMZjOBgYFW83Nzc9m4cSPQsQHl6urKokWLeO211xg1ahQzZsygd+/efPHFF3z22Wf89a9/5Ysvvuiw+r6tLfUuXLgQrVZLTEyMylWL1pCAUsHQoUPx9PRk48aNmEwmvLy8OHPmDNnZ2Xh6euLs7EzPnj07tMZ169YxdOhQtm3bxsaNG/n666/x9vZm1KhRbN68uUNra0xr6l26dCmnTp3i+PHjODk5qVuwaJ2OPcuh6/joo4/MISEh5h49eph9fHzMc+fONd+4ccPs5uZmnjhxYkeX1ypvv/22uX///h1dRov88pe/NA8dOtRcXl7e0aUIBaQHpZLQ0FD++te/NphfWVnZAdW0zd27dzEajRiNRsxmM7W1tTg4OODs7NzRpTVq0aJFHD9+nL/85S/07t27o8sRCjiYzfLgTqHMzp07iY2NtZrXv39/1c+Haolr167h7++Ps7Mz3bv/++/xD3/4Q/73f/+3AysTLSEBJYSwW3KagRDCbklACSHslgSUEMJuSUAJIeyWBJQQwm5JQAkh7JYEVAeoq6sjKSmpQ+8BpYTU2/mcOHGCp59+Gl9fXxwcHFp054mcnBxGjRqFs7MzAQEB7Ny5s0GbrVu34u/vj4uLCyEhIZw5c8b2xX9Th57H3kVVVFSYAXNFRUVHl9IiUm/nc/jwYfNvfvMb81tvvWUGzG+//Xaz7a9cuWJ2dXU1L1261Hz+/Hnzli1bzN26dTMfOXLE0mbfvn1mJycn844dO8znzp0zz5kzx+zh4WEuKytrt/2QgOoAne0fkNTbubUkoBISEsxDhgyxmvfMM8+YIyMjLa+Dg4PNzz//vOX13bt3zb6+vubk5GSb1vtNcognhODUqVMNbv4XGRnJqVOnAKivrycvL8+qjaOjI+Hh4ZY27UEuFm6GyWSiuLgYrVaLg4ODzdZrMBis/mvvpN57zP93L3lfX99WPSKstrbWch/61m7/27+Hzs7ONrlIu7S0FG9vb6t53t7eGAwGvv76a/71r39x9+7dRtv885//bPP2myIB1Yzi4mL8/Pzabf3tue72IPXeU1RURN++fRUtU1tbS4/ePaCq9dt1c3Ojqsp6BStXriQpKan1K7VzElDN0Gq1AMzbPQ8n185xg7M+uj4dXcJ3Vm11LUnRSZbfCyXq6+uhChyWOkBrOjx1UJVSRVFRETqdzjLbVre40ev1lJWVWc0rKytDp9PRo0cPunXrRrdu3Rpto9frbVJDYySgmnG/O+3k6oSzxj7vdfRtLhqXji7hO68th/uOLo44uChf3uxg5i530el0VgFlK6GhoRw+fNhq3rFjxwgNDQXAycmJ0aNHk52dzYQJE4B7QyDZ2dksXLjQ5vXcJwElhIocHRxbFXD3A6qlqqqqKCgosLy+evUq+fn5eHp60q9fPxITE/niiy944403AJg/fz6/+93vSEhIYPbs2Rw/fpwDBw7w5z//2bKOpUuXMnPmTMaMGUNwcDCbN2+murq6wb3BbEkCSggVtSWglPjkk0/4yU9+Ynm9dOlSAGbOnMnOnTspKSnh+vXrlvcHDBjAn//8Z5YsWcLrr79O3759SU9PJzIy0tLmmWee4csvv2TFihWUlpYyYsQIjhw50mDg3JbkhnXNMBgMuLu788JbL3SaQ7y+OmWDt6LlaqtrWR6+nIqKCsWHWfd/l5xfcm7dIV6tmbo1da3admcmPSghVKRWD+q7QgJKCBVJQCkjASWEiiSglJGAEkJFElDKSEAJoSIJKGXkYmEhhN2SHpQQKnJwcMDRQXm/wORgaodq7J8ElBAqcnRwbFVAYbubaXQqElBCqEgCShkJKCFUJAGljASUECqSgFJG0Sc1a9Ysy60W7F1JSQlTp07l8ccfx9HRkcWLF3d0SUIIhTr9aQZN3UK1rq6O3r1789JLLzF8+HCVqxKicfd7UK2ZuiKb7nVKSgpBQUFoNBr8/PxYsGCB5Ral1dXV6HQ6Dh48aLXMoUOH0Gg0VFZWAvdupzp58mQ8PDzw9PQkOjqawsJCS/v7vbi1a9fi6+vLwIEDG63F39+f119/nZiYGNzd3W25m0K0mgSUMjbda0dHR1JTUzl37hyZmZkcP36chIQEADQaDVOmTCEjI8NqmYyMDCZNmoRWq8VoNBIZGYlWqyU3N5eTJ0/i5uZGVFSUVU8pOzubixcvcuzYMd577z1b7oIQ7UoCShmbDpJ/c5zH39+fNWvWMH/+fLZt2wZAfHw8Y8eOpaSkBB8fH8rLyzl8+DBZWVkA7N+/H5PJRHp6uuVygIyMDDw8PMjJySEiIgK4F3bp6ek4Odn2PuF1dXVWT6PtLE8xEZ2HI103bFrDpp9UVlYWYWFh9OnTB61Wy4wZM7h58yY1NTUABAcHM2TIEDIzMwHYvXs3/fv3Z9y4cQCcPXuWgoICtFotbm5uuLm54enpSW1tLZcvX7ZsJygoyObhBJCcnIy7u7tl6mxPMRH27/6Z5EonWz72rDOxWUAVFhYyfvx4hg0bxptvvkleXh5bt24FrAey4+PjLc98z8jIIDY21vLhV1VVMXr0aPLz862mzz//nKlTp1rWodFobFW2lcTERCoqKixTUVFRu2xHCNEyNjvEy8vLw2QysWnTJstDDQ8cONCg3fTp00lISCA1NZXz588zc+ZMy3ujRo1i//79eHl5dchtTW31EEQhmtLa8SS5m0ELVVRUNOjhFBUVERAQgNFoZMuWLVy5coVdu3aRlpbWYPmePXsyceJEli1bRkREhNUDEKdNm0avXr2Ijo4mNzeXq1evkpOTw6JFi7hx44binbtfX1VVFV9++SX5+fmcP39e8XqEsBUZJFdG8V7n5OQwcuRIq2nVqlUMHz6clJQU1q9fz9ChQ9mzZw/JycmNriMuLo76+npmz55tNd/V1ZUTJ07Qr18/Jk6cyKBBg4iLi6O2trZVPar79eXl5bF3715GjhzJk08+qXg9QtiKBJQyHfJUl127drFkyRKKi4vbZbDbVuSpLuKbbPFUlyEpQ+jWo5vibd/9+i7nlp6Tp7q0p5qaGkpKSli3bh3z5s2z63ASoj3IGJQyqvYbN2zYQGBgIHq9nsTERDU3LYTohFQNqKSkJIxGI9nZ2bi5uam5aSHsgoxBKSO3WxFCRXKIp4wElBAqkoBSRgJKCBXJQxOU6ZoHtkJ0EDXHoLZu3Yq/vz8uLi6EhIRw5syZJtv++Mc/xsHBocH01FNPWdrMmjWrwftRUVGt+hxaSnpQQnwH7d+/n6VLl5KWlkZISAibN28mMjKSixcv4uXl1aD9W2+9ZXXN7M2bNxk+fDi/+MUvrNpFRUVZ3TKpvS8Nkx6UECpSqweVkpLCnDlziI2NZfDgwaSlpeHq6sqOHTsabe/p6Yler7dMx44dw9XVtUFAOTs7W7Xr2bNnqz+LlpCAEkJFbQ0og8FgNX3z/mX31dfXk5eXR3h4+L+36+hIeHg4p06dalGd27dvZ8qUKQ3uHJKTk4OXlxcDBw7kueee4+bNm234NB5MAkoIFbU1oPz8/KzuWdbY9a5fffUVd+/exdvb22q+t7c3paWlD6zxzJkz/OMf/yA+Pt5qflRUFG+88QbZ2dmsX7+eDz74gP/4j//g7t27bfhEmidjUEKoqLUD3veXKSoqsroWrz3GgLZv305QUBDBwcFW86dMmWL5OSgoiGHDhvHoo4+Sk5NDWFiYzesA6UEJoaq29qB0Op3V1FhA9erVi27dulFWVmY1v6ysDL1e32x91dXV7Nu3j7i4uAfuyyOPPEKvXr0oKChQ8AkoIwElxHeMk5MTo0ePJjs72zLPZDKRnZ1NaGhos8v+6U9/oq6ujunTpz9wOzdu3ODmzZv4+Pi0ueamSEAJoSK1vsVbunQpf/jDH8jMzOTChQs899xzVFdXExsbC0BMTEyjF+xv376dCRMm8PDDD1vNr6qqYtmyZfz1r3+lsLCQ7OxsoqOjCQgIIDIysvUfyAPIGFQLZF3JatU9fDrCCP2Iji5BkTG+Yzq6BFU5tvKpLo4K+xLPPPMMX375JStWrKC0tJQRI0Zw5MgRy8D59evXLbfmvu/ixYt8+OGHHD16tMH6unXrxmeffUZmZia3b9/G19eXiIgIVq9e3a7nQklACaGi1l7q0pqnuixcuJCFCxc2+l5OTk6DeQMHDqSp+1f26NGD999/X3ENbSUBJYSK2votXlcjASWEiiSglOmaey2E6BSkByWEiqQHpYwElBAqkoBSRgJKCBVJQCkjASWEiiSglJGAEkJFElDKdM29FkJ0CtKDEkJF0oNSRgJKCBWpeanLd4EElBAqkh6UMhJQQqhIAkoZCSghVCQBpUzX3GshRKcgPSghVCQ9KGUU7fWsWbOYMGFCO5ViW2+99RZPPPEEvXv3RqfTERoa2iE33BLim9S65e93Raff628+rvmbTpw4wRNPPMHhw4fJy8vjJz/5CU8//TSffvqpyhUK8W8SUMrYdK9TUlIICgpCo9Hg5+fHggULqKqqAu49zkan03Hw4EGrZQ4dOoRGo6GyshK499yvyZMn4+HhgaenJ9HR0RQWFlra3+/FrV27Fl9fXwYOHNhoLZs3byYhIYH/9//+H4899hivvvoqjz32GO+++64td1kIRSSglLHpXjs6OpKamsq5c+fIzMzk+PHjJCQkAKDRaJgyZQoZGRlWy2RkZDBp0iS0Wi1Go5HIyEi0Wi25ubmcPHkSNzc3oqKirHpK2dnZXLx4kWPHjvHee++1qDaTyURlZSWenp6222EhFJKAUsamg+SLFy+2/Ozv78+aNWuYP38+27ZtAyA+Pp6xY8dSUlKCj48P5eXlHD58mKysLAD279+PyWQiPT3dcuZsRkYGHh4e5OTkEBERAdwLu/T0dJycnFpc28aNG6mqqmLy5MlNtqmrq7N61r3BYGjx+oUQtmfTWM7KyiIsLIw+ffqg1WqZMWMGN2/epKamBoDg4GCGDBlCZmYmALt376Z///6MGzcOgLNnz1JQUIBWq8XNzQ03Nzc8PT2pra3l8uXLlu0EBQUpCqe9e/eyatUqDhw4gJeXV5PtkpOTrZ577+fn15qPQYgmOeDQqt6TA13zUhebBVRhYSHjx49n2LBhvPnmm+Tl5bF161bAeiA7Pj6enTt3Avd6R7GxsZbeUlVVFaNHjyY/P99q+vzzz5k6daplHRqNpsV17du3j/j4eA4cOEB4eHizbRMTE6moqLBMRUVFLd6OEC0hh3jK2OwQLy8vD5PJxKZNmywPBDxw4ECDdtOnTychIYHU1FTOnz/PzJkzLe+NGjWK/fv34+XlhU6na3NNf/zjH5k9ezb79u3jqaeeemB7Z2fndn0IoRByHpQyive6oqKiQQ+nqKiIgIAAjEYjW7Zs4cqVK+zatYu0tLQGy/fs2ZOJEyeybNkyIiIi6Nu3r+W9adOm0atXL6Kjo8nNzeXq1avk5OSwaNEibty4oajOvXv3EhMTw6ZNmwgJCaG0tJTS0lIqKiqU7rIQNiM9KGUU73VOTg4jR460mlatWsXw4cNJSUlh/fr1DB06lD179pCcnNzoOuLi4qivr2f27NlW811dXTlx4gT9+vVj4sSJDBo0iLi4OGpraxX3qH7/+99z584dnn/+eXx8fCzTL3/5S6W7LITNSEAp42Bu6lnH7WjXrl0sWbKE4uJiRYPdajMYDLi7uzNo4yC69ejW0eW0yAj9iI4uQZExvmM6uoQWq62uZXn4cioqKhT/wbz/u/TLQ7/EWaN8GKGuuo7XJ7zeqm13ZqrGck1NDZcvX2bdunXMmzfPrsNJiPagZg9q69at+Pv74+LiQkhICGfOnGmy7c6dO3FwcLCaXFxcrNqYzWZWrFiBj48PPXr0IDw8nEuXLimuSwlVA2rDhg0EBgai1+tJTExUc9NC2AW1Amr//v0sXbqUlStX8re//Y3hw4cTGRlJeXl5k8vodDpKSkos07Vr16ze37BhA6mpqaSlpXH69Gk0Gg2RkZHU1ta26rNoCVUDKikpCaPRSHZ2Nm5ubmpuWgi7oFZApaSkMGfOHGJjYxk8eDBpaWm4urqyY8eOJpdxcHBAr9dbJm9vb8t7ZrOZzZs389JLLxEdHc2wYcN44403KC4u5tChQ639OB6oa468CdFB1Aio+vp68vLyrM77c3R0JDw8nFOnTjW5XFVVFf3798fPz4/o6GjOnTtnee/q1auUlpZardPd3Z2QkJBm19lWElBCdCIGg8Fq+ualWfd99dVX3L1716oHBODt7U1paWmj6x04cCA7duzgf/7nf9i9ezcmk4mxY8daTu+5v5ySddqCBJQQKrr/VBfFl7r839UWfn5+VpdjNXUqj1KhoaHExMQwYsQIfvSjH/HWW2/Ru3dv/vu//9sm628tuaOmECpq65nkRUVFVqcZNHblQ69evejWrRtlZWVW88vKytDr9S3a3kMPPcTIkSMpKCgAsCxXVlaGj4+P1TpHjBihaF+UkB6UECpq6xiUTqezmhoLKCcnJ0aPHk12drZlnslkIjs7m9DQ0BbVeffuXf7+979bwmjAgAHo9XqrdRoMBk6fPt3idbaG9KCEUJFa1+ItXbqUmTNnMmbMGIKDg9m8eTPV1dXExsYCEBMTQ58+fSyHiK+88grf+973CAgI4Pbt27z22mtcu3aN+Ph44N6h6eLFi1mzZg2PPfYYAwYM4OWXX8bX17ddbwMuASWEitQKqGeeeYYvv/ySFStWUFpayogRIzhy5IhlkPv69euWi/oB/vWvfzFnzhxKS0vp2bMno0eP5qOPPmLw4MGWNgkJCVRXVzN37lxu377ND37wA44cOdLghE5b6pBLXToLudSl/XW1S12S3k/CRaP8H3RtdS1JkUld7lIX6UEJoSK1elDfFRJQQqhIAkoZCSghVCQBpYwElBAqkoBSRgKqBQpuFeDg0jluWl97p/2uLG8PnWmQ3BbuPzShNct1RV0zloUQnYL0oIRQkRziKSMBJYSKJKCUkYASQkUSUMpIQAmhIgkoZSSghFCRBJQyXXOvhRCdgvSghFCR9KCUkYASQkUSUMpIQAmhIgkoZSSghFDR/YcmtGa5rkgCSggVSQ9Kma6510KITkF6UEKoSHpQykhACaEiCShlJKCEUJEElDISUEKoSAJKGUV7PWvWrHZ9SJ8tffjhh3z/+9/n4YcfpkePHgQGBvLb3/62o8sSXVxbnyzc1XT6HlR9fT1OTk4N5ms0GhYuXMiwYcPQaDR8+OGHzJs3D41Gw9y5czugUiGEUjaN5ZSUFIKCgtBoNPj5+bFgwQKqqqoAqK6uRqfTcfDgQatlDh06hEajobKyEoCioiImT56Mh4cHnp6eREdHU1hYaGl/vxe3du1afH19GThwYKO1jBw5kmeffZYhQ4bg7+/P9OnTiYyMJDc315a7LIQi0oNSxqZ77ejoSGpqKufOnSMzM5Pjx4+TkJAA3OvRTJkyhYyMDKtlMjIymDRpElqtFqPRSGRkJFqtltzcXE6ePImbmxtRUVHU19dblsnOzubixYscO3aM9957r0W1ffrpp3z00Uf86Ec/st0OC6GQBJQyNj3EW7x4seVnf39/1qxZw/z589m2bRsA8fHxjB07lpKSEnx8fCgvL+fw4cNkZWUBsH//fkwmE+np6ZZT+zMyMvDw8CAnJ4eIiAjgXtilp6c3emj3bX379uXLL7/kzp07JCUlER8f32Tburo66urqLK8NBoPiz0CI5jjSykHyLnpOtU33Oisri7CwMPr06YNWq2XGjBncvHmTmpoaAIKDgxkyZAiZmZkA7N69m/79+zNu3DgAzp49S0FBAVqtFjc3N9zc3PD09KS2tpbLly9bthMUFNSicALIzc3lk08+IS0tjc2bN/PHP/6xybbJycm4u7tbJj8/v9Z+FEI06v61eEqnrnotns0CqrCwkPHjxzNs2DDefPNN8vLy2Lp1K4DV4Vl8fDw7d+4E7vWOYmNjLR9+VVUVo0ePJj8/32r6/PPPmTp1qmUdGo2mxXUNGDCAoKAg5syZw5IlS0hKSmqybWJiIhUVFZapqKhIwScgxIOpeYi3detW/P39cXFxISQkhDNnzjTZ9g9/+AM//OEP6dmzJz179iQ8PLxB+1mzZuHg4GA1RUVFKa5LCZsFVF5eHiaTiU2bNvG9732Pxx9/nOLi4gbtpk+fzrVr10hNTeX8+fPMnDnT8t6oUaO4dOkSXl5eBAQEWE3u7u5trtFkMlkdwn2bs7MzOp3OahKiM9q/fz9Lly5l5cqV/O1vf2P48OFERkZSXl7eaPucnByeffZZ/vKXv3Dq1Cn8/PyIiIjgiy++sGoXFRVFSUmJZWruiMQWFAdURUVFgx5OUVERAQEBGI1GtmzZwpUrV9i1axdpaWkNlu/ZsycTJ05k2bJlRERE0LdvX8t706ZNo1evXkRHR5Obm8vVq1fJyclh0aJF3LhxQ1GdW7du5d133+XSpUtcunSJ7du3s3HjRqZPn650l4WwGbV6UCkpKcyZM4fY2FgGDx5MWloarq6u7Nixo9H2e/bsYcGCBYwYMYLAwEDS09MxmUxkZ2dbtXN2dkav11umnj17tvqzaAnFAZWTk8PIkSOtplWrVjF8+HBSUlJYv349Q4cOZc+ePSQnJze6jri4OOrr65k9e7bVfFdXV06cOEG/fv2YOHEigwYNIi4ujtraWsW9GZPJRGJiIiNGjGDMmDFs3bqV9evX88orryjdZSFspq0BZTAYrKbGjgjq6+vJy8sjPDz839t1dCQ8PJxTp061qM6amhqMRiOenp5W83NycvDy8mLgwIE899xz3Lx5sw2fxoM5mM1mc7tuoRG7du1iyZIlFBcXt3iwuyMYDAbc3d156NcP4eDSOQYp+7n36+gSFFkYvLCjS2ix2upalocvp6KiQvEfzPu/S3/++5/RaFs+hnpfdWU1TwU91WD+ypUrG4yrFhcX06dPHz766CNCQ0Mt8xMSEvjggw84ffr0A7e3YMEC3n//fc6dO4eLiwsA+/btw9XVlQEDBnD58mV+/etf4+bmxqlTp+jWrZvifWoJVc8kr6mpoaSkhHXr1jFv3jy7Dich2kNbr8UrKiqyCkdnZ2eb1XbfunXr2LdvHzk5OZZwApgyZYrl56CgIIYNG8ajjz5KTk4OYWFhNq8DVL5h3YYNGwgMDESv15OYmKjmpoWwC209xPv2lziNBVSvXr3o1q0bZWVlVvPLysrQ6/XN1rdx40bWrVvH0aNHGTZsWLNtH3nkEXr16kVBQYHCT6HlVA2opKQkjEYj2dnZuLm5qblpIboMJycnRo8ebTXAfX/A+5uHfN+2YcMGVq9ezZEjRxgzZswDt3Pjxg1u3ryJj4+PTepuTKe/WFiIzkSt260sXbqUmTNnMmbMGIKDg9m8eTPV1dXExsYCEBMTQ58+fSxfZK1fv54VK1awd+9e/P39KS0tBbCcMF1VVcWqVav4+c9/jl6v5/LlyyQkJBAQEEBkZKTi/WkpCSghVKRWQD3zzDN8+eWXrFixgtLSUkaMGMGRI0fw9vYG4Pr16zg6/nud//Vf/0V9fT2TJk2yWs/9Qfhu3brx2WefkZmZye3bt/H19SUiIoLVq1e3yzjYfRJQQqhIzcdOLVy4kIULG/+WNCcnx+r1N+8Y0pgePXrw/vvvK66hrSSghFCRWj2o7woJKCFUJAGlTNfcayFEpyA9KCFUJD0oZSSghFCRBJQyElBCqEgCShkJKCFUJAGljASUECqSgFKma+61EKJTkB5UCxhNRjB1dBUtc73iekeXIJohT3VRRgJKCBWpeanLd4EElBAqkjEoZSSghFCRBJQyElBCqEgCSpmuuddCiE5BelBCqEh6UMpIQAmhIgkoZSSghFCRBJQyElBCqEgCShkJKCFUJAGlTNfcayFEpyA9KCFUJJe6KCMBJYSK5BBPGQkoIVQkAaWMBJQQKpKAUkYCSggVSUAp0zX3WgjRKSgKqFmzZjFhwoR2KqX9nDx5ku7duzNixIiOLkV0cfd7UK2ZlNq6dSv+/v64uLgQEhLCmTNnmm3/pz/9icDAQFxcXAgKCuLw4cNW75vNZlasWIGPjw89evQgPDycS5cuKa5LiU7fg6qvr2/2/du3bxMTE0NYWJhKFQnRNLUCav/+/SxdupSVK1fyt7/9jeHDhxMZGUl5eXmj7T/66COeffZZ4uLi+PTTT5kwYQITJkzgH//4h6XNhg0bSE1NJS0tjdOnT6PRaIiMjKS2trZNn0lzbBpQKSkpBAUFodFo8PPzY8GCBVRVVQFQXV2NTqfj4MGDVsscOnQIjUZDZWUlAEVFRUyePBkPDw88PT2Jjo6msLDQ0v5+L27t2rX4+voycODAZmuaP38+U6dOJTQ01Ja7KkSrqBVQKSkpzJkzh9jYWAYPHkxaWhqurq7s2LGj0favv/46UVFRLFu2jEGDBrF69WpGjRrF7373O+Be72nz5s289NJLREdHM2zYMN544w2Ki4s5dOhQWz+WJtk0oBwdHUlNTeXcuXNkZmZy/PhxEhISANBoNEyZMoWMjAyrZTIyMpg0aRJarRaj0UhkZCRarZbc3FxOnjyJm5sbUVFRVj2l7OxsLl68yLFjx3jvvfearCcjI4MrV66wcuVKW+6mEK2mRkDV19eTl5dHeHj4v7fr6Eh4eDinTp1qdJlTp05ZtQeIjIy0tL969SqlpaVWbdzd3QkJCWlynbZg02/xFi9ebPnZ39+fNWvWMH/+fLZt2wZAfHw8Y8eOpaSkBB8fH8rLyzl8+DBZWVnAvW6pyWQiPT3dcuZsRkYGHh4e5OTkEBERAdwLu/T0dJycnJqs5dKlSyxfvpzc3Fy6d2/ZbtbV1VFXV2d5bTAYFO2/EO3t27+Tzs7OODs7W8376quvuHv3Lt7e3lbzvb29+ec//9noektLSxttX1paann//rym2rQHm/agsrKyCAsLo0+fPmi1WmbMmMHNmzepqakBIDg4mCFDhpCZmQnA7t276d+/P+PGjQPg7NmzFBQUoNVqcXNzw83NDU9PT2pra7l8+bJlO0FBQc2G0927d5k6dSqrVq3i8ccfb3H9ycnJuLu7WyY/P7/WfAxCNMmhDROAn5+f1e9ocnKyynugLpv1oAoLCxk/fjzPPfcca9euxdPTkw8//JC4uDjq6+txdXUF7vWitm7dyvLly8nIyCA2NtbSW6qqqmL06NHs2bOnwfp79+5t+Vmj0TRbS2VlJZ988gmffvopCxcuBMBkMmE2m+nevTtHjx7lpz/9aYPlEhMTWbp0qeW1wWCQkBK2ZTbdm1qzHPfGaHU6nWX2t3tPAL169aJbt26UlZVZzS8rK0Ov1ze6er1e32z7+/8tKyvDx8fHqk17fjtusx5UXl4eJpOJTZs28b3vfY/HH3+c4uLiBu2mT5/OtWvXSE1N5fz588ycOdPy3qhRo7h06RJeXl4EBARYTe7u7i2uRafT8fe//538/HzLNH/+fAYOHEh+fj4hISGNLufs7IxOp7OahLCp+wHVmgka/H42FlBOTk6MHj2a7OxsyzyTyUR2dnaTXxaFhoZatQc4duyYpf2AAQPQ6/VWbQwGA6dPn27XL6AU96AqKirIz8+3mvfwww8TEBCA0Whky5YtPP3005w8eZK0tLQGy/fs2ZOJEyeybNkyIiIi6Nu3r+W9adOm8dprrxEdHc0rr7xC3759uXbtGm+99RYJCQlWbZvj6OjI0KFDreZ5eXnh4uLSYL4Q6jLRusdUK1tm6dKlzJw5kzFjxhAcHMzmzZuprq4mNjYWgJiYGPr06WM5RPzlL3/Jj370IzZt2sRTTz3Fvn37+OSTT/j9738P3LubwuLFi1mzZg2PPfYYAwYM4OWXX8bX17ddz41UHFA5OTmMHDnSal5cXBzp6emkpKSwfv16EhMTGTduHMnJycTExDRYR1xcHHv37mX27NlW811dXTlx4gS/+tWvmDhxIpWVlfTp04ewsDDpzYjvhjYe4rXUM888w5dffsmKFSsoLS1lxIgRHDlyxDLIff36dRwd/30ANXbsWPbu3ctLL73Er3/9ax577DEOHTpk9Qc9ISGB6upq5s6dy+3bt/nBD37AkSNHcHFxUb4/LeRgNpvN7bb2JuzatYslS5ZQXFzc7GB3RzMYDPcOLZcD7ff/wKacHO3382zMhic2dHQJLVZbXcvy8OVUVFQo/oN5/3ep4lZpq/7YGgwG3D31rdp2Z6bqxcI1NTWUlJSwbt065s2bZ9fhJES7UKkH9V2h6qUuGzZsIDAwEL1eT2JiopqbFsI+tHGQvKtRNaCSkpIwGo1kZ2fj5uam5qaFsBOmNkxdj9wPSgg1ySGeIhJQQqjJbG5lQKn+XZZd6PS3WxFCfHdJD0oIValzouZ3hQSUEGqSMShFJKCEUJMElCISUEKoSQJKEQkoIVQlY1BKyLd4Qgi7JT0oIdQkh3iKSEAJoSYJKEUkoIRQlYxBKSEB9R0zQj+io0sQzZFLXRSRgBJCTXKIp4h8iyeEsFvSgxJCVTIGpYQElBBqkkM8RSSghFCTBJQiElBCqEkCShEJKCFUJWNQSsi3eEIIuyU9KCHUJId4ikhACaGq1j7jTgJKCNHuzLQubORSFyFEe5NDPEVkkFwINdnho89v3brFtGnT0Ol0eHh4EBcXR1VVVbPtX3jhBQYOHEiPHj3o168fixYtoqKiwqqdg4NDg2nfvn2KapMelBBd3LRp0ygpKeHYsWMYjUZiY2OZO3cue/fubbR9cXExxcXFbNy4kcGDB3Pt2jXmz59PcXExBw8etGqbkZFBVFSU5bWHh4ei2iSghFCTnR3iXbhwgSNHjvDxxx8zZswYALZs2cKTTz7Jxo0b8fX1bbDM0KFDefPNNy2vH330UdauXcv06dO5c+cO3bv/O1Y8PDzQ6/Wtrk8O8YRQlakNExgMBquprq6uTdWcOnUKDw8PSzgBhIeH4+joyOnTp1u8noqKCnQ6nVU4ATz//PP06tWL4OBgduzYgVnhfa2kByWEmtrYg/Lz87OavXLlSpKSklpdTmlpKV5eXlbzunfvjqenJ6WlpS1ax1dffcXq1auZO3eu1fxXXnmFn/70p7i6unL06FEWLFhAVVUVixYtanF9igJq1qxZ3L59m0OHDilZrEPk5OTwk5/8pMH8kpKSNnU5hWiTNgZUUVEROp3OMtvZ2bnR5suXL2f9+vXNrvLChQvK6/gWg8HAU089xeDBgxsE5csvv2z5eeTIkVRXV/Paa6+1X0DZo/r6epycnJp8/+LFi1b/Q7/910IIdbXtWjydTmf1+9yUF198kVmzZjXb5pFHHkGv11NeXm41/86dO9y6deuBf8grKyuJiopCq9Xy9ttv89BDDzXbPiQkhNWrV1NXV9dksH6bTcegUlJSCAoKQqPR4OfnZ+nSAVRXV6PT6RqM8h86dAiNRkNlZSVw7y/E5MmT8fDwwNPTk+joaAoLCy3tZ82axYQJE1i7di2+vr4MHDiw2Zq8vLzQ6/WWydFRht3Ed1/v3r0JDAxsdnJyciI0NJTbt2+Tl5dnWfb48eOYTCZCQkKaXL/BYCAiIgInJyfeeecdXFxcHlhTfn4+PXv2bHE4gY0DytHRkdTUVM6dO0dmZibHjx8nISEBAI1Gw5QpU8jIyLBaJiMjg0mTJqHVajEajURGRqLVasnNzeXkyZO4ubkRFRVFfX29ZZns7GwuXrzIsWPHeO+995qtacSIEfj4+PDEE09w8uRJW+6uEMrZ2XlQgwYNIioqijlz5nDmzBlOnjzJwoULmTJliuUbvC+++ILAwEDOnDkD/Ducqqur2b59OwaDgdLSUkpLS7l79y4A7777Lunp6fzjH/+goKCA//qv/+LVV1/lhRdeUFSfTQ/xFi9ebPnZ39+fNWvWMH/+fLZt2wZAfHw8Y8eOpaSkBB8fH8rLyzl8+DBZWVkA7N+/H5PJRHp6Og4ODsC9APPw8CAnJ4eIiAjgXtilp6c3e2jn4+NDWloaY8aMoa6ujvT0dH784x9z+vRpRo0a1egydXV1Vt+KGAyGNn0eQjRgh0912bNnDwsXLiQsLAxHR0d+/vOfk5qaannfaDRy8eJFampqAPjb3/5m+YYvICDAal1Xr17F39+fhx56iK1bt7JkyRLMZjMBAQGkpKQwZ84cRbXZNKCysrJITk7mn//8JwaDgTt37lBbW0tNTQ2urq4EBwczZMgQMjMzWb58Obt376Z///6MGzcOgLNnz1JQUIBWq7Vab21tLZcvX7a8DgoKajacAAYOHGh1+Dd27FguX77Mb3/7W3bt2tXoMsnJyaxataq1uy9EC9jf/aA8PT2bPCkT7nU2vnl6wI9//OMHni4QFRVldYJma9nsEK+wsJDx48czbNgw3nzzTfLy8ti6dSuA1eFZfHw8O3fuBO71jmJjYy29paqqKkaPHk1+fr7V9PnnnzN16lTLOjQaTatqDA4OpqCgoMn3ExMTqaiosExFRUWt2o4QTbKzQzx7Z7MeVF5eHiaTiU2bNlkGog8cONCg3fTp00lISCA1NZXz588zc+ZMy3ujRo1i//79eHl5teibCqXy8/Px8fFp8n1nZ2dFA3hCKGZnZ5LbO8UBVVFRQX5+vtW8hx9+mICAAIxGI1u2bOHpp5/m5MmTpKWlNVi+Z8+eTJw4kWXLlhEREUHfvn0t702bNo3XXnuN6OhoXnnlFfr27cu1a9d46623SEhIsGr7IJs3b2bAgAEMGTKE2tpa0tPTOX78OEePHlW6y0KIDqL4EC8nJ4eRI0daTatWrWL48OGkpKSwfv16hg4dyp49e0hOTm50HXFxcdTX1zN79myr+a6urpw4cYJ+/foxceJEBg0aRFxcHLW1tYp7VPX19bz44osEBQXxox/9iLNnz5KVlUVYWJjSXRbCduQQTxEHs9KLY2xg165dLFmyhOLi4gcOdnckg8GAu7s7LAcefJqHXQj2De7oEhSZGjT1wY3sRG11LcvDl1uuO1Pi/u9Sxbk30GldFW/bUFmD+5CYVm27M1P1TPKamhpKSkpYt24d8+bNs+twEqJdyBiUIqqeVr1hwwYCAwPR6/UkJiaquWkh7IMc4imiakAlJSVhNBrJzs7Gzc1NzU0LYSfadruVrkYuTBNC2K1OfzcDIToVGYNSRAJKCDXZ4bV49kwCSgg1SQ9KEQkoIVRlfxcL2zMJKCHUJD0oReRbPCGE3ZIelBBqkh6UIhJQQqhKxqCUkIASQlWtvWxFAkoI0d7kEE8RCSghVCWHeEpIQH3H/DX+rx1dgiKpp1Mf3Eh0WRJQQqhJLnVRRAJKCDXJGJQiElBCqEkCShEJKCFUJYPkSkhACaEm6UEpItfiCSHslgSUEGqyw4cm3Lp1i2nTpqHT6fDw8CAuLo6qqqpml/nxj3+Mg4OD1TR//nyrNtevX+epp57C1dUVLy8vli1bxp07dxTVJod4QqjK/sagpk2bRklJCceOHcNoNBIbG8vcuXPZu3dvs8vNmTOHV155xfLa1fXfz/u7e/cuTz31FHq9no8++oiSkhJiYmJ46KGHePXVV1tcmwSUEGqyszGoCxcucOTIET7++GPGjBkDwJYtW3jyySfZuHEjvr6+TS7r6uqKXq9v9L2jR49y/vx5srKy8Pb2ZsSIEaxevZpf/epXJCUltfiZmHKIJ4Sa7OwQ79SpU3h4eFjCCSA8PBxHR0dOnz7d7LJ79uyhV69eDB06lMTERGpqaqzWGxQUhLe3t2VeZGQkBoOBc+fOtbg+6UEJ0YkYDAar187Ozjg7O7d6faWlpXh5eVnN6969O56enpSWlja53NSpU+nfvz++vr589tln/OpXv+LixYu89dZblvV+M5wAy+vm1vttElBCqKmNl7r4+flZzV65ciVJSUkNmi9fvpz169c3u8oLFy4or+P/zJ071/JzUFAQPj4+hIWFcfnyZR599NFWr/fbJKCEUFXbBsmLiorQ6XSWuU31nl588UVmzZrV7BofeeQR9Ho95eXlVvPv3LnDrVu3mhxfakxISAgABQUFPProo+j1es6cOWPVpqysDEDReiWghFBTGwfJdTqdVUA1pXfv3vTu3fuB7UJDQ7l9+zZ5eXmMHj0agOPHj2MymSyh0xL5+fkA+Pj4WNa7du1aysvLLYeQx44dQ6fTMXjw4BavVwbJhVCTnQ2SDxo0iKioKObMmcOZM2c4efIkCxcuZMqUKZZv8L744gsCAwMtPaLLly+zevVq8vLyKCws5J133iEmJoZx48YxbNgwACIiIhg8eDAzZszg7NmzvP/++7z00ks8//zzisbMJKCEUJWpDVP72LNnD4GBgYSFhfHkk0/ygx/8gN///veW941GIxcvXrR8S+fk5ERWVhYREREEBgby4osv8vOf/5x3333Xsky3bt1477336NatG6GhoUyfPp2YmBir86ZaQg7xhOjiPD09mz0p09/fH/M37kfl5+fHBx988MD19u/fn8OHD7epNkU9qFmzZjFhwoQ2bVBNdXV1/OY3v6F///44Ozvj7+/Pjh07Oros0ZXZ2SGevev0Paj6+vomz0qdPHkyZWVlbN++nYCAAEpKSjCZuub/aGEn7OxMcntn0zGolJQUgoKC0Gg0+Pn5sWDBAstFh9XV1eh0Og4ePGi1zKFDh9BoNFRWVgL3vkadPHkyHh4eeHp6Eh0dTWFhoaX9/V7c2rVr8fX1ZeDAgY3WcuTIET744AMOHz5MeHg4/v7+hIaG8v3vf9+WuyyEQvY3BmXPbBpQjo6OpKamcu7cOTIzMzl+/DgJCQkAaDQapkyZQkZGhtUyGRkZTJo0Ca1Wi9FoJDIyEq1WS25uLidPnsTNzY2oqCjq6+sty2RnZ3Px4kWOHTvGe++912gt77zzDmPGjGHDhg306dOHxx9/nP/8z//k66+/tuUuC6GMHOIpYtNDvMWLF1t+9vf3Z82aNcyfP59t27YBEB8fz9ixYykpKcHHx4fy8nIOHz5MVlYWAPv378dkMpGeno6DgwNwL8A8PDzIyckhIiICuBd26enpzV5weOXKFT788ENcXFx4++23+eqrr1iwYAE3b95sEJL31dXVUVdXZ3n97csKhGgzeWiCIjbtQWVlZREWFkafPn3QarXMmDGDmzdvWr6eDA4OZsiQIWRmZgKwe/du+vfvz7hx4wA4e/YsBQUFaLVa3NzccHNzw9PTk9raWi5fvmzZTlBQ0AOvhjaZTDg4OLBnzx6Cg4N58sknSUlJITMzs8leVHJyMu7u7pbp25cVCCHUZbOAKiwsZPz48QwbNow333yTvLw8tm7dCmB1eBYfH8/OnTuBe72j2NhYS2+pqqqK0aNHk5+fbzV9/vnnTJ061bIOjUbzwHp8fHzo06cP7u7ulnmDBg3CbDZz48aNRpdJTEykoqLCMhUVFSn+HIRolhziKWKzQ7y8vDxMJhObNm3C0fFe7h04cKBBu+nTp5OQkEBqairnz59n5syZlvdGjRrF/v378fLyatHp/M35/ve/z5/+9Ceqqqpwc3MD4PPPP8fR0ZG+ffs2ukxbrwwX4sHadi1eV6O4B1VRUdGgh1NUVERAQABGo5EtW7Zw5coVdu3aRVpaWoPle/bsycSJE1m2bBkRERFWYTFt2jR69epFdHQ0ubm5XL16lZycHBYtWtRkr6cpU6dO5eGHHyY2Npbz589z4sQJli1bxuzZs+nRo4fS3RbCNqQHpYjigMrJyWHkyJFW06pVqxg+fDgpKSmsX7+eoUOHsmfPHpKTkxtdR1xcHPX19cyePdtqvqurKydOnKBfv35MnDiRQYMGERcXR21treIelZubG8eOHeP27duMGTOGadOm8fTTT5OaKo/aFh2pteHUNQPKwWxW/+uBXbt2sWTJEoqLi1t868+OYDAY7o1hLQdcOrqaljGt6Fy/yKmnO88fjNrqWpaHL6eiokLxH8z7v0sV2dPRaZT/zhuq63EP292qbXdmqp5JXlNTQ0lJCevWrWPevHl2HU5CiI6n6t0MNmzYQGBgIHq9nsTERDU3LYR9kDEoRVQNqKSkJIxGI9nZ2ZZv1oToUiSgFOn0FwsL0anIxcKKSEAJoSozrftGrmte6iIBJYSapAeliNzyVwhht6QHJYSapAeliASUEKqSa/GUkIASQk3Sg1JEAkoINUlAKSIBJYSq5BBPCfkWTwhht6QHJYSa5BBPEQkoIdQkAaWIBJQQapKnuigiASWEqmSQXAkZJBdCTXZ4u5Vbt24xbdo0dDodHh4exMXFWZ4I3pjCwkIcHBwanf70pz9Z2jX2/r59+xTVJj0oIbq4adOmUVJSwrFjxzAajcTGxjJ37lz27t3baHs/Pz9KSkqs5v3+97/ntdde4z/+4z+s5mdkZBAVFWV57eHhoag2CSgh1GRng+QXLlzgyJEjfPzxx4wZMwaALVu28OSTT7Jx40Z8fX0bLNOtWzf0er3VvLfffpvJkyc3uBGlh4dHg7ZKyCGeEKoytWG69/CFb051dXVtqubUqVN4eHhYwgkgPDwcR0dHTp8+3aJ15OXlkZ+fT1xcXIP3nn/+eXr16kVwcDA7duxA6TNapAclhJra2IPy8/Ozmr1y5UqSkpJaXU5paSleXl5W87p3746npyelpaUtWsf27dsZNGgQY8eOtZr/yiuv8NOf/hRXV1eOHj3KggULqKqqYtGiRS2uTwJKCDW1MaCKioqsHjvV1JOwly9fzvr165td5YULF5TX8S1ff/01e/fu5eWXX27w3jfnjRw5kurqal577TUJKCHsVhsDSqfTtei5eC+++CKzZs1qts0jjzyCXq+nvLzcav6dO3e4detWi8aODh48SE1NDTExMQ9sGxISwurVq6mrq2syWL9NAkqI76DevXvTu3fvB7YLDQ3l9u3b5OXlMXr0aACOHz+OyWQiJCTkgctv376dn/3sZy3aVn5+Pj179mxxOIEElBAqs68TNQcNGkRUVBRz5swhLS0No9HIwoULmTJliuUbvC+++IKwsDDeeOMNgoODLcsWFBRw4sQJDh8+3GC97777LmVlZXzve9/DxcWFY8eO8eqrr/Kf//mfiuqTgBJCTXZ4qcuePXtYuHAhYWFhODo68vOf/5zU1H8/kt5oNHLx4kVqamqsltuxYwd9+/YlIiKiwTofeughtm7dypIlSzCbzQQEBJCSksKcOXMU1eZgVvq9XxdiMBhwd3eH5YBLR1fTMqYVneuSiNTTqQ9uZCdqq2tZHr6cioqKFo0DfdP936WKgyPRabop3rah+i7ukz5t1bY7M+lBCaEqE+DQyuW6HgkoIVRlArMEVEvJmeRCCLslPSgh1GRuZQ9KblgnhGh/MgalhKJDvFmzZjFhwoR2KsW2Zs2a1ej9aIYMGdLRpYmuzA7vB2XPOv0YVH19faPzX3/9dUpKSixTUVERnp6e/OIXv1C5QiG+QQJKEZsGVEpKCkFBQWg0Gvz8/CxXLwNUV1ej0+k4ePCg1TKHDh1Co9FQWVkJ3LsYcvLkyXh4eODp6Ul0dDSFhYWW9vd7cWvXrsXX15eBAwc2Wou7uzt6vd4yffLJJ/zrX/8iNjbWlrsshDISUIrYNKAcHR1JTU3l3LlzZGZmcvz4cRISEgDQaDRMmTKFjIwMq2UyMjKYNGkSWq0Wo9FIZGQkWq2W3NxcTp48iZubG1FRUVY9pezsbC5evMixY8d47733WlTb9u3bCQ8Pp3///rbbYSFEu7LpIPnixYstP/v7+7NmzRrmz5/Ptm3bAIiPj2fs2LGUlJTg4+NDeXk5hw8fJisrC4D9+/djMplIT0/HweHeQGJGRgYeHh7k5ORYTqnXaDSkp6fj5OTUorqKi4v53//93yZvYXpfXV2d1Q3ADAZDi/ddiJYx07oB7655wYdNe1BZWVmEhYXRp08ftFotM2bM4ObNm5ZreIKDgxkyZAiZmZkA7N69m/79+zNu3DgAzp49S0FBAVqtFjc3N9zc3PD09KS2tpbLly9bthMUFNTicALIzMzEw8PjgQP8ycnJuLu7W6Zv3xxMiDaTQzxFbBZQhYWFjB8/nmHDhvHmm2+Sl5fH1q1bAeuB7Pj4eHbu3Anc6x3FxsZaektVVVWMHj2a/Px8q+nzzz9n6tSplnVoNJoW12U2m9mxYwczZsx4YKglJiZSUVFhmYqKilq8HSFaRAJKEZsd4uXl5WEymdi0aROOjvdy78CBAw3aTZ8+nYSEBFJTUzl//jwzZ860vDdq1Cj279+Pl5eXzS6I/OCDDygoKGj0fsnf5uzsrOheNUIo19qg6ZoBpbgHVVFR0aCHU1RUREBAAEajkS1btnDlyhV27dpFWlpag+V79uzJxIkTWbZsGREREfTt29fy3rRp0+jVqxfR0dHk5uZy9epVcnJyWLRoETdu3GjVDm7fvp2QkBCGDh3aquWFsCnpQSmiOKBycnIYOXKk1bRq1SqGDx9OSkoK69evZ+jQoezZs4fk5ORG1xEXF0d9fT2zZ8+2mu/q6sqJEyfo168fEydOZNCgQcTFxVFbW9uqHlVFRQVvvvlmi3pPQgj70yH3g9q1axdLliyhuLhY0WC32uR+UO2vy90ParcenavyoV9DjQn36aVyP6j2VFNTQ0lJCevWrWPevHl2HU5CtAuzqXVnDMghXvvbsGEDgYGB6PV6EhMT1dy0EHbC1Iap61E1oJKSkjAajWRnZzd4RLIQXYIMkisit1sRQk12+NAEe9bp72YghPjukh6UEKoy0bob1nXNHpQElBBqavUtfyWghBDtTQJKEQkoIVQlh3hKSEAJoSbpQSki3+IJIeyWBJQQarLDEzXXrl3L2LFjcXV1xcPDo2W7YTazYsUKfHx86NGjB+Hh4Vy6dMmqza1bt5g2bRo6nQ4PDw/i4uIszyhoKQkoIdRkhwFVX1/PL37xC5577rkWL7NhwwZSU1NJS0vj9OnTaDQaIiMjqa2ttbSZNm0a586dszw74MSJE8ydO1dRbTIGJYSq7G+QfNWqVQCWO90+sBKzmc2bN/PSSy8RHR0NwBtvvIG3tzeHDh1iypQpXLhwgSNHjvDxxx8zZswYALZs2cKTTz7Jxo0b8fX1bdG2pAclhJruX+qieLKfQfKrV69SWlpKeHi4ZZ67uzshISGcOnUKgFOnTuHh4WEJJ4Dw8HAcHR05ffp0i7clPahm3L9VVtHzRZ3mHjz3ny/YWcQO7jzPKTQYDCxnOW25hZrh67Yt9+0nDXXEbapLS0sB8Pb2tprv7e1tea+0tBQvLy+r97t3746np6elTUtIQDXj/j92ebqL+KbKysp7NzJUwMnJCb1ej9+ilv/j/DY3N7cGv4srV64kKSmpQdvly5ezfv36Ztd34cIFAgMDW12PGiSgmuHr60tRURFardby5BlbMBgM+Pn5UVTUOXpmUu89ZrOZysrKFo+ffJOLiwtXr161esJRa7b/7d/DpnpPL774IrNmzWp2fY888kir6tDr9QCUlZXh4+NjmV9WVsaIESMsbcrLy62Wu3PnDrdu3bIs3xISUM1wdHS0eqiDrel0uk7xD/4+qRfFPadvcnFxwcVFnXtH9+7dm969e7fLugcMGIBeryc7O9sSSAaDgdOnT1u+CQwNDeX27dvk5eUxevRoAI4fP47JZCIkJKTF25JBciG6uOvXr5Ofn8/169e5e/eu5WlN3zxnKTAwkLfffhsABwcHFi9ezJo1a3jnnXf4+9//TkxMDL6+vpaH4w4aNIioqCjmzJnDmTNnOHnyJAsXLmTKlCnKeqBmobqKigozYK6oqOjoUlpE6v1umzlzppl75zFYTX/5y18sbQBzRkaG5bXJZDK//PLLZm9vb7Ozs7M5LCzMfPHiRav13rx50/zss8+a3dzczDqdzhwbG2uurKxUVFuHPNWlq6urqyM5OZnExMRO8aBQqVd0FAkoIYTdkjEoIYTdkoASQtgtCSghhN2SgBJC2C0JKCGE3ZKAEkLYLQkoIYTdkoASQtgtCSghhN2SgBJC2C0JKCGE3fr/EB7I2ptQEB8AAAAASUVORK5CYII=", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "mats = []\n", + "for i in range(33):\n", + " mat = np.zeros([7, 3])\n", + " for layer in range(7):\n", + " for pos, pref in enumerate([\"a\", \"e1\", \"e2\"]):\n", + " key = \"{}_{}\".format(pref, layer+1)\n", + " val = result_dict[key][i]\n", + " mat[layer, pos] = val\n", + " mats.append(mat)\n", + "mats = np.array(mats)\n", + "\n", + "mat = mats[-1] - mats[10] # delta in causal strength\n", + "\n", + "x_labels = ['Layer {}'.format(i) for i in range(1, 8)]\n", + "y_labels = ['$a$', '$e_1$', '$e_2$']\n", + "\n", + "cmap = mcolors.LinearSegmentedColormap.from_list('orange_green', ['orange', 'white', 'green'], N=256)\n", + "norm = mcolors.TwoSlopeNorm(vmin=-1.0, vmax=1.0, vcenter=0)\n", + "fig, ax = plt.subplots(figsize=(5, 4))\n", + "cax = ax.matshow(mat, cmap=cmap, norm=norm)\n", + "cbar = fig.colorbar(cax, fraction=0.046, pad=0.04)\n", + "cbar.ax.tick_params(labelsize=10)\n", + "plt.yticks(range(mat.shape[0]), x_labels, fontsize=10)\n", + "plt.xticks(range(mat.shape[1]), y_labels, fontsize=13)\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAbwAAAGXCAYAAADI2+UqAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/SrBM8AAAACXBIWXMAAA9hAAAPYQGoP6dpAAB2gklEQVR4nO3deVxU1fsH8M+dGfYdBBEQEXCGXQQEccENM7dc0rJyK00sNVP7lZZfs6w0zBY101zSzLRFNMUll9xyzdw3VJBVRUCWAQZmu78/iAvjzMAM2wDzvF8vX3rOnHvvM0eYZ+5yzmFYlmVBCCGEtHI8QwdACCGENAVKeIQQQowCJTxCCCFGgRIeIYQQo0AJjxBCiFGghEcIIcQoUMIjhBBiFCjhEUIIMQqU8AghhBgFSngNQCQS4eOPP66xzblz5yASiXDgwIEa2yUkJEAkEiEzM7MhQySEEKMnMHQAjSEjIwM//PADTp06hUePHgEA3N3dERUVhRdffBF+fn4GjrDl2rp1KywsLDBq1KgG3/e9e/ewf/9+jBw5Eh4eHg2+f0KIcWt1Ce/o0aOYPXs2+Hw+hg0bBj8/P/B4PKSkpODgwYPYtm0bjhw5And3d0OHqtHw4cMxZMgQmJqaGjoUjbZt2wYHB4dGS3irVq1CZGQkJTxCSINrVQkvPT0dc+bMgZubGzZt2gQXFxeV19955x38/PPP4PFqvpJbWloKS0vLxgxVKz6fDz6fb5BjG0p5eTlMTEwMHQYhpJVrVffw1q9fj9LSUixZskQt2QGAQCDAhAkT0K5dO65u3rx56NKlC9LT0/H666+jS5cueOeddwBUJL6lS5eid+/eCAoKwsCBA7FhwwbossDE6tWr4efnhy1btmhtI5VKERcXh/DwcFy8eBGA5nt4/fr1Q1xcHC5cuIDRo0cjODgY/fv3x65du9T2efv2bYwbNw4hISGIiYnB6tWrsWPHDp3uC+bk5GD+/PmIiYlBUFAQevbsiTfeeIPbrl+/frh79y7Onz8PkUgEkUiE8ePHAwAKCgrw+eefY9iwYejSpQvCwsIwZcoU3L59W+UYlfcy9+7di6+++gq9evVC586d8eOPP2LWrFkAgAkTJnD7P3fuHADg2rVrmDx5MqKiohASEoJ+/fph/vz5tfwvEEJIlVZ1hnf06FF06NABnTt31ms7uVyOyZMnIzw8HO+99x7Mzc3BsizeeOMNnDt3DqNHj4a/vz9OnjyJ+Ph4ZGdn4/3339e6v6+++gpr167Fxx9/jBdeeEFjm7KyMrz55pu4fv06fvjhB4SEhNQYY1paGmbNmoXRo0dj5MiR2LFjB+bNm4fAwEB06tQJAJCdnY2JEycCAKZOnQpLS0v89ttvOl8enTlzJu7du4dx48bB3d0dT548walTp/Dw4UN4eHjg/fffx+LFi2FpaYlp06YBANq0aQOg4r7p4cOH8eyzz8LDwwO5ubn45ZdfMG7cOOzduxdt27ZVOdbq1athYmKCyZMnQyqVomfPnhg/fjy2bNmCadOmwdvbGwDg4+ODvLw8TJ48GQ4ODpg6dSpsbW2RmZmJQ4cO6fS+CCEEAMC2EmKxmBUKheybb76p9lphYSGbl5fH/ZFIJNxr7733HisUCtkvvvhCZZtDhw6xQqGQXb16tUr9zJkzWZFIxKalpXF1QqGQ/eijj1iWZdmlS5eyfn5+bEJCgsp2Z8+eZYVCIbt//362uLiYHTduHBsVFcXevHlTpd2OHTtYoVDIZmRkcHV9+/ZlhUIh+88//3B1eXl5bFBQELt06VKubvHixaxIJFLZZ35+PhsZGam2T019JBQK2fXr12ttw7IsO2TIEHbcuHFq9eXl5axCoVCpy8jIYIOCgthVq1ap9UP//v1V/h9YlmX379/PCoVC9uzZsyr1lf8XV69erTE2QgipSau5pFlcXAwAGu+9jR8/HtHR0dyfrVu3qrV56aWXVMonTpwAn8/nLtlVeu2118CyLE6cOKFSz7IsPv74Y/z4449YtmwZRo4cqTFOsViMyZMnIyUlBVu2bIG/v79O78/X1xcRERFc2dHRER07dkRGRgZXd/LkSYSGhqrs097eHsOGDat1/+bm5jAxMcH58+dRWFioU0zVmZqacvdGFQoF8vPzYWlpiY4dO+LmzZtq7UeMGAFzc3Od9m1jYwMAOHbsGGQymd6xEUII0IouaVpZWQGouO/2tI8//hglJSXIzc3F//3f/6m9LhAI4OrqqlKXlZUFFxcXWFtbq9T7+Phwr1e3a9culJaWYtGiRRg6dKjWOD/77DNIpVLs3LmTuxSpi+r3HSvZ2dmpJKesrCyEhoaqtfP09Kx1/6ampnjnnXfw+eefo0ePHujcuTP69OmDESNGwNnZudbtlUolfvzxR/z888/IzMyEQqHgXrO3t1drr89TmJGRkRg4cCBWrVqFTZs2ITIyErGxsRg2bFizfZqVENL8tJozPBsbGzg7O+Pu3btqr3Xu3Bndu3dHWFiYxm2rn53UVVhYGNq0aYOtW7eioKBAa7v+/fuDZVl8//33UCqVOu+/KZ7cnDRpEv7880/MmTMHZmZm+OabbzB48GCNZ2hPW7NmDZYsWYKIiAgsW7YMGzZswA8//IBOnTppfMhH17M7AGAYBitWrODuCVbeQx01ahRKSkr0eo+EEOPVahIeAPTp0wdpaWm4evVqvffl7u6Ox48fc5dKK6WkpHCvV9ehQwds2LABjx8/xpQpU9S2qxQbG4vPPvsMiYmJ+Oijj+od59Mxp6WlqdWnp6frvA9PT0+89tpr2LhxIxITEyGTybBx40budYZhNG73559/IioqCp999hmGDBmCnj17onv37igqKtL52Nr2XSk0NBSzZ89GQkICvvjiC9y9exf79u3Tef+EEOPWqhLelClTYGFhgffffx+5ublqr2s609AmJiYGCoVC7X7fpk2bwDAMYmJi1Lbx8/PD999/j+TkZLzxxhsoKyvTuO8RI0ZgwYIF2L59O5YtW6ZzTLXp2bMnLl++jFu3bnF1BQUF2LNnT63bSiQSlJeXq9R5enrCysoKUqmUq7OwsNCYxPh8vlr/7t+/H9nZ2TrHb2FhAaDiPmd1hYWFavuuvE9ZPTZCCKlJq7mHBwBeXl744osvMHfuXDz77LPcTCssyyIzMxOJiYng8Xhq9+s06devH6KiovDVV18hKysLIpEIp06dwpEjRzBx4kSt98VCQ0OxevVqTJ06FW+99Ra+/fZbjYOqx40bh+LiYnz11VewsbHhHvOvjylTpmD37t149dVXMW7cOG5YQrt27VBQUFDjGVRqaiomTZqEZ599Fr6+vuDz+Th8+DByc3MxZMgQrl1gYCC2bduG1atXo0OHDnB0dER0dDT69OmDb7/9FvPnz0eXLl1w584d7NmzB+3bt9c5fn9/f/D5fKxbtw5isRimpqbo1q0b9uzZg23btiE2Nhaenp4oKSnBr7/+Cmtra41fPAghRJNWlfCAikuGe/bswcaNG3Hq1Cns2LEDDMPAzc0NvXv3xksvvaTTXJo8Hg/fffcdVqxYgX379iEhIQHu7u5499138dprr9W4bXR0NL7++mu89dZbePfdd7F8+XKN7aZNmwaxWMwlvVdeeaVO77lSu3bt8OOPP+KTTz7B2rVr4ejoiFdeeQUWFhb45JNPYGZmpnVbV1dXDBkyBGfOnMHu3bvB5/Ph7e2Nr7/+GgMHDuTaTZ8+HQ8ePMD69etRUlKCyMhIREdHY9q0aZBIJNizZw/27duHgIAArF27Vut718TZ2RkfffQR1q5diw8++AAKhQI//vgjIiMjce3aNezbtw+5ubmwsbFBSEgIvvjiC70SKiHEuDGsPtf5SIv06aef4pdffsGlS5eMbtoyQgip1Kru4RGo3TfMz8/H7t27ER4eTsmOEGLUWt0lTWP34osvIjIyEj4+PsjNzcWOHTtQXFyMN99809ChEUKIQdElzVbmyy+/xJ9//olHjx6BYRgEBARgxowZ6N69u6FDI4QQg6KERwghxCjQPTxCCCFGgRIeIYQQo0AJjxBCiFGghEcIIcQoUMIjhBBiFCjhEUIIMQqU8AghhBiFFpvwkpKSkJSUZOgwCCGEtBAtNuFJpdJ6r4VWXl6Of//9V20dOGNH/aId9Y121DfaUd9o1tT90mITXkNQKBQqf5MK1C/aUd9oR32jHfWNZk3dL0ad8AghhBgPSniEEEKMAiU8QgghRoESHiGEEKNACY8QQohRoIRHCCHEKFDCI4QQYhT0TnhpaWlYuHAhhg8fjoCAAAwdOlSn7ViWxffff48+ffogJCQEL774Ii5fvqzv4QkhhJA60Tvh3b17F8ePH0eHDh3g4+Oj83br1q3DihUrMGnSJKxduxbOzs547bXXkJGRoW8IhBBCiN70Tnj9+vXD8ePHsWLFCgQGBuq0TXl5OdauXYvXXnsNkyZNQnR0NL788kvY29tjw4YNegdNCCGE6Eug7wY8nv63/S5evIji4mIMGjSIqzM1NcWAAQNw6NAhvfdHCCE1Ud5Lh/J+FgDW0KFUkMrQJicHeFQMualJrc1ZlgULJVhWASUrBwsFWFZZ7d8KKNmKv1k8/W85WFZZ7d//tf9vu4p2zaNfFAoleFJA6mIHS0vfRj+e3gmvLlJSUgAA3t7eKvU+Pj7YvHkzysrKYG5urvd+WZZFaWlpneOSSCQqf5MK1C/aUd9o11z6RnnrHjL/jIfYPA9gDBoKhwULllHiYUHF3yyjhJJRcvVcmVGCZSrqjEnZ7gvo/GpCvfZhaWlZa5smSXhFRUUwNTWFmZmZSr2trS1YlkVhYWGdEp5MJsOtW7fqHV9qamq999EaUb9oR32jnUH7hmUh+Psb5DjV/3OBNB0J70m9P8vDw8NrbdMkCa+xmJiYwNe37qfBEokEqamp8PLygoWFRQNG1rJRv2hHfaNdc+ibvH8SkGRx0yDHblHYZnLqC0CgNIW7y3Nw9/dv/GM1+hFQcSYnlUpRXl6ucpZXVFQEhmFgZ2dXp/0yDKPTaWxtLCwsGmQ/rQ31i3bUN9oZqm8kRVm4d3t1VQULOLQNA6PDPbPGplAoUVIqga2NPQSm5uDxBGB4AvB4JmB4AjB8E/U6ngA8vmod77+23L95JlV/8zVsX/3v/7ZjGD4YpnkkvNLSUty6dQvu/v5N8jPTJAmv8t7d/fv34efnx9WnpKTAzc2tTpczCSGkklIhw7UD70KBqoVE2wt6QjTyGwNGVaXyg92viT7YiWZNMtNKWFgYrK2tsX//fq5OJpPh4MGDiImJaYoQCCGt2L3zq1CUf5sr25a2gU+/dwwYEWmO9D7Dk0gkOH78OAAgKysLxcXFOHDgAAAgMjISjo6OmDhxIh48eMANOTAzM0NcXBxWrlwJR0dHCIVCbNu2DQUFBZg8eXIDvh1CiLHJSTuB9Ks/cWWBwhR+/JEQeLc3YFSkOdI74eXl5WHWrFkqdZXlH3/8EVFRUVAqlWpLtr/++utgWRYbN27EkydP4O/vjw0bNqB9e/qhJITUTVnxI9w8ukilrtPDSFiN6WeYgEizpnfC8/DwQFJSUo1ttmzZolbHMAzi4uIQFxen7yEJIUSNUinHtSPvQ1ZeyNW5PRGijXkgeEGNP4iZtDy0WgIhpEVKubAWhY+ucGVriSO8ckLAj4kAU4cZoUjrRz8VhJAWJy/jDFIv/cCV+QoT+D2MBs/CCvzIIANGRpozSniEkBalvCQHN44uRPV5Mjs96gpzmTX43UPBmJkaLjjSrFHCI4S0GKxSget/LYBU8oSra5fvizbF7QE+D4KeXQwYHWnuKOERQlqM+5c2IP/BBa5sVWaPjjmhAABeWAAYOxsDRUZaAkp4hJAW4cmDC0j5dx1X5sMUfg+6g8fyAQCC3hGGCo20EJTwCCHNnlSSj+tHPgDYqmVzfB+Gw0JWcUbHE3qB5+ZiqPBIC0EJjxDSrLGsEjeOLoS0NJerc7WMgnORJ1fm09kd0QElPEJIs5Z2ZQvyMk5zZSt7b3RM8uHKjGsb8Pw6GiI00sJQwiOENFsFj64g+fy3XJknMEOA0wTwS6umLuT3jmg2y92Q5o0SHiGkWZKVFeLakflg2arkJur+LszPPaxqZGMFfniAAaIjLRElPEJIs8OyLG4c+wjlxdlcnWunwWhb7gc2r4CrE/TsAkbQJMt6klaAEh4hpNnJuL4NuWnHubKlXQf49ZoPxYmqMXgwEYDfnQaaE91RwiOENCtFOTdx92zVSuU8vimCBywFLysfbOoDrp7fNQiMlYUhQiQtFCU8QkizIS8X49rheWCVcq5O2H0ubJyEkB/7p6ohQ0MRiP4o4RFCmgWWZXHzxGJIirK4OhfvWLj7Pw9lXgGU1+5y9bxAX/CcHQ0RJmnBKOERQpqFrFs78DjlCFe2sHVHQMwCMAwDxfELAFu1OoKgT1dDhEhaOEp4hBCDE+fdwZ3Ty7kywxMgOHYpBGY2YEvLoDh/req19q5gOnoYIkzSwlHCI4QYlFxWimuH5kGpkHJ1nbrNgq1zxfg6xZnLgFTGvSbo05UGmpM6oYRHCDEYlmVx++QSlBamcXVtOvRG+6CXKl6XKyA/ebFqAwdb8EJETR0maSUo4RFCDOZh0h48uruPK5tZt0Vgnw+5MzjlpVtAUTH3uiAmHAyfPrZI3dBPDiHEIIrzU3D71FKuzDB8BPdfAhNzOwAVZ38qQxHMTcGPCmnqMEkrQgmPENLkFDJJxX07eTlX5xP5JuxdO3Nl5d00sA9zuDK/W2cw5mZNGidpXSjhEUKaXNLpL1CSn8yVndp3R4fOE1TaKKqf3fEYCHqFN1V4pJWihEcIaVKP7u7Hg9u7uLKZpTMC+34Mhqn6OFI+yoXy9n2uzOvsB8bBtinDJK0QJTxCSJMpLUzHrZOfVVUwPAT1/xSmFg4q7VTO7kADzUnDoIRHCGkSCnk5rh6aB4WslKvzDn8dDm6qlyrZomIo/r3JlRmf9uC1d22yOEnrRQmPENIk7p79GsV5SVzZwa0rOnaZrNZOfuoSoKha9JXO7khDoYRHCGl02SlHkHnjV65sauGIoH6LwfD4Ku1YqQyK05e5MuPiCJ6/T1OFSVo5SniEkEYlKcrCreMfV6thENhvMcysnNXaKi5cB0okXJkfEwGGR9OIkYZBCY8Q0miUChmuHZkPubRqthSvLq/CyaObWltWyVasilDJygL8iMCmCJMYCUp4hJBGc+/8ShQ9vsGV7Vw7wzsiTmNb5c17YHPyuTK/RxcwpiaNHiMxHpTwCCGNIif1BNKvbuXKJmZ2CO7/GXg8gcb2KtOICfgQ9OjS2CESI0MJjxDS4MqKH+HmsUUqdQF9F8HcWvPwAmXGQ7ApmVyZHx4IxsaqMUMkRogSHiGkQbFKOa4deR+y8kKuzjNkHJw7xGjdRv7UQHM+DUUgjYASHiGkQaVf2YjCR1e4sq1LIHwjZ2htz+YXQXmlanwez98bvLZOjRojMU6aL6YTQkgdyApvIOvuT1xZYGqN4P5LwONrf/hEfuICoGS5Mp3dkcZCZ3iEkAYhLc1Fyf2NAKqSl3/vhbCwdde6DSsph+LsVa7MuLuA5+vZmGESI0YJjxBSb6xSgTt/LwYrF3N1HoEvoK13/xq3U5y7ApRLubKgd1dutXNCGholPEJIvaVe3oSi7Itc2aaNCJ26vV3jNqxCAfmJf6sq7KzBC/VrpAgJoYRHCKmn8tJc3L+0gSvzBBYIjl0KvqDm1cmVV5KAgqozQkHPcDACfg1bEFI/lPAIIfWSeukHKOXlXNk78m1Y2tV8H45lWdWhCKYm4Ed3bqwQCQFACY8QUg9lxY+QeXMHV+ZbuMPZ+9lat2OTM8BmZldtFxUCxtK8UWIkpBIlPEJInd2/uAGsUsaVzd2Gg2Fq/1iRH692dscw4MeEa29MSAOhhEcIqZPSwgw8SPqDK1s5+cHEvvbLksrHeVDeSObKvBAheE72jREiISoo4RFC6iTl33VglVUrk3uGTtFpSIGi+pOZqBiKQEhT0DvhJScn49VXX0VoaCh69OiB+Ph4SKXSWrfLz8/HwoUL0adPH4SGhmLo0KHYtm1bnYImhBhWcX4KHt3dx5XtXUNh3y6y1u3Y4lIozl/nyoyXO3hebo0SIyFP02tqscLCQkycOBFeXl5YuXIlsrOzsXTpUpSVlWHhwoU1bjtr1iykpKRgzpw5aNeuHU6cOIFFixaBz+fjhRdeqNebIIQ0rZQLa1F9RhWfrtN1O7s7fRmQy7mygKYRI01Ir4S3fft2lJSUYNWqVbC3twcAKBQKfPTRR4iLi0Pbtm01bpeTk4Nz585hyZIlGDVqFAAgOjoa165dw969eynhEdKCiHOT8DjlMFd29IiCg1sYSktLa9yOlckh/7tqcDrjZA9ekG+jxUnI0/S6pHnixAlER0dzyQ4ABg0aBKVSiVOnTmndTv7fNzobGxuVemtra7Asq2kTQkgzlfzPdypln4g3dNpO8e9NoLgqKfJjIsDw6DEC0nT0OsNLSUnB888/r1Jna2sLZ2dnpKSkaN2uXbt26NmzJ9asWYOOHTvC1dUVJ06cwKlTp/DFF1/ULXJUDF6t7VtlTSQSicrfpAL1i3bG3jfinBvITT/JlR08esDExgelpaU19w3Lgjl2HpUXPVkLM0iDfSCtx+9vS2LsPzfaNGS/WFpa1tpGr4RXVFQEW1tbtXo7OzsUFhZq2KLKypUrMXv2bAwZMgQAwOfzsWDBAgwcOFCfEFTIZDLcunWrzttXSk1Nrfc+WiPqF+2MtW/ESd+olOW2/dR+BzX1jXVWLjo8fsKVc71d8Tj5XqPE2JwZ689NbRqiX8LDax/L2STr4bEsi/nz5yM1NRXLly+Hs7MzTp8+jc8++wx2dnZcEtSXiYkJfH3rfg9AIpEgNTUVXl5esLCwqPN+WhvqF+2MuW8KH13CDXFVcnPq0A+i8Ge4ck19w5zZxf2b5fPgNKQvnGytGz3m5sKYf25q0tT9olfCs7W1hVgsVqsvLCyEnZ2d1u2OHTuGAwcOYPfu3RCJRACAqKgo5OXlYenSpXVOeAzD6HQaWxsLC4sG2U9rQ/2inbH1DcuyuHGtaoJoMDwIo97U2AdP940yKxvSlEyuzA8LgKmrS6PG21wZ28+NrpqqX/S6Y+zt7a12r04sFiMnJwfe3t5at7t37x74fD6EQqFKvb+/Px4/fkzXtQlp5vIyzqDw0RWu3K7TIFg5dNRpW/nxCyplQe+IBo2NEF3plfBiYmJw+vRpFBUVcXUHDhwAj8dDjx49tG7n7u4OhUKBpKQklfobN27AycmJTvEJacZYlkXyP6u5MsPjo2P4VN22LRBDebHqMihP6AWem3Ge3RHD0yvhjR07FlZWVpg+fTr+/vtv7NixA/Hx8Rg7dqzKGLyJEydiwIABXDkmJgZubm5466238Mcff+DMmTNYtmwZdu7ciXHjxjXcuyGENLic1GMQ51YlLTfRCFjaeui0rfzvi4BSyZX5dHZHDEive3h2dnbYvHkzFi9ejOnTp8PKygqjR4/G7NmzVdoplUooFFVz7FlbW2PTpk346quv8MUXX0AsFsPDwwPz5s2jhEdIM8aySiRfqBp3x+ObomPYZN22LZdCceYyV2Zc24Dnp9tlUEIag95Pafr4+GDTpk01ttmyZYtaXYcOHfD111/rezhCiAFlJx9EyZOqlQ3c/Z+HubXmGZWepjh3DZBULQzL7x2h0/RjhDQWmuaAEKKRUin/b87MCjyBOby6TNJpW1aphOJEtYdVbKzADw9o4AgJ0Q8lPEKIRo/u7ENpYTpXbh/0Isws2+i0rfLaXbBPqiajEPTsAkbQJMN+CdGKEh4hRI1SIUPKv99zZb6pFbw6T9R5e/mxaiuamwjA796lIcMjpE4o4RFC1GTd3omy4odcuUPwOJiYa59cQkX6Q7BpD7giv2sQGCsaekQMjxIeIUSFQl6G+xerZlUxMbODZ/BLOm/PnLpcrUBDEUjzQQmPEKIi8+bvkJbmcuUOoRMgMLOpYYsqJmIJcLNqNiZeoC94zo4NHiMhdUEJjxDCkctKkXrpB65sauGE9oEv6ry9U1I6mGprXNKK5qQ5oYRHCOFkXNsGWVkBV/bq8ir4Jjref5OUwT656r4f094VTEfdZmQhpClQwiOEAABk5UVIu/IjVzazagt3/1G67+D8DfDlVTMsCfp0pYHmpFmhhEcIAQCkX/0JcmkxV+4YNgV8gZlO27JyBZizV6sqHGzBCxE1dIiE1AslPEIIpJJ8pF/bxpUtbN3hJhqm8/bKS7fAiEu4siAmHAyfPl5I80I/kYQQpF3eDIWslCt7h8eBxzfRaVtlXgFkice5MmtmCn5USIPHSEh9UcIjxMiVl+Qg48avXNnS3guuvs/qtC1bKIbsu1+Aamd36BoIxly3S6GENCVKeIQYufuXNkKpqFrVwCdiGhgev9bt2BIJpGt/U5kzU+JoA7YvDUUgzRMlPEKMmET8EFm3EriytZMQLt79a92OLZdCun4H2EdVA9TZNvZI6xsKmJk2RqiE1BslPEKM2P2L68Aq5VzZp+sbYJiaPxZYuRyyH3apzJcJexuwk4ZDYU7JjjRflPAIMVKlhel4mJTIlW1dgtDGs1eN27BKJWRb90J5J7Wq0toSptNeAOx1m36MEEOhhEeIkUq5sBYsWzVQ3KfrmzUOFGdZFvLfD0J5Jamq0swUplNHg+fi1JihEtIgKOERYoSKn9zDo3t/cmX7duFwdI+scRv53hNQVB9cLhDAdPIo8DxcGytMQhoUJTxCjFDyhbUAqiZ59u36Ro1nd/K/zkHx17mqCh4Dk4nPgefr2YhREtKwKOERYmSKcm4h5/5fXNmpfXfYt9O+Irn8zBXIqw0sBwCTlwaDH+jbaDES0hgo4RFiZJL/+U6l7NP1Da1tFZdvQ/77nyp1gpH9wQ8PbJTYCGlMlPAIMSIFjy4jL+MUV3b26gNb5wCNbRVJ9yHbmlj9yicEA3tA0Cu8scMkpFFQwiPEiKie3THwiZimsZ0yNQuyH3YBCiVXx+8VDv4z3Rs3QEIaESU8QozEk6zzyH9wgSu39X0G1k6d1NopH+RAum4HIJVxdbyIQAiG96P17UiLRgmPECPAsiySz6+uqmB48A6PU2unzCuAdO2vgKSMq+MF+sLkxWfB8CjZkZaNEh4hRiAv/W8UPr7GldsJh8LKvoNKG7aoGLI1v6qsfMD4tIfJhOfA8GufTJqQ5o4SHiGtHMsqkXyh6t4dwxPAO/x11TYlEkjX/Ao2r6CqnUdbmE4eBcZE0FShEtKoKOER0so9vn8U4tyq6cDc/UbAwsaNK7PlUkg3qK58wLg4wnTqGFrXjrQqlPAIacVYpQIp1Z7M5PHN0DFsStXrcjlkm3aBTVVd+cA07gUw1pZNGSohjY4SHiGt2KN7f6Kk4D5X9ggcDTMrZwDVVj5ISq3awMoCptNeAONg28SREtL4KOER0kopFTKk/LuWK/MFFvAKnQSghpUP4sbQygek1aKER0gr9fBOIiRFmVy5ffBLMLVwBEArHxDjRAmPkFZIqZAi5eI6riwwtUaHzuMB0MoHxHhRwiOkFcq8lYDy4myu7Nl5PEzMbCE/q2Hlg7G08gExDpTwCGllFDIJUi9u5Mom5nbwDHoJiitJkP92UKWtYGR/8CNo5QNiHCjhEdLKZNz4DVJJHlf2Cp0E5n4OZD/tAdiqpQ9o5QNibCjhEdKKyKXFSLuyiSubWjrBzbonZD/spJUPiNGjhEdIK5J+7WfIygq5spfPi1BsTFRd+SA8gFY+IEaJEh4hrYSsrBBpV3/iymaWLmhzsOSplQ98YDJ2EK18QIwSJTxCWom0K1ugkFatdOCZ7Q9eUVWyY7w9YDKeVj4gxosSHiGtgFTyBOnXt3Flc4UdnB+4cOWKlQ+eB2NqYojwCGkWKOER0grcv/QDlPKqsznPbH/w/vv15lY+sKCVD4hxo4RHSAtXVpyNrJu/c2XLcls4i9tXFGjlA0I4lPAIaeHuX9oApULKlT1zg8GAV7HyQRytfEBIJUp4hLRgkqIsPLi1iytbldnDqdi9YuWDqWPAa0srHxBSSe+El5ycjFdffRWhoaHo0aMH4uPjIZVKa98QQHZ2Nt577z1069YNISEhGDRoEHbv3q130ISQCin/rgPLKrhyh9xgMJUrH7SnlQ8IqU6gT+PCwkJMnDgRXl5eWLlyJbKzs7F06VKUlZVh4cKFNW77+PFjvPjii+jYsSMWL14Ma2tr3L17V+dkSQhRVZJ/Hw/vJHJlG4kTHCRuMJlEKx8QooleCW/79u0oKSnBqlWrYG9vDwBQKBT46KOPEBcXh7Zt22rddtmyZXB1dcX69evB/28cUHR0dN0jJ8TI3TsYD6BqbswOOcEwHTsE/KBOhguKkGZMr0uaJ06cQHR0NJfsAGDQoEFQKpU4deqU1u2Ki4uxf/9+vPzyy1yyI4TUXc7x35BTcJ4r25W4oM3Al2nlA0JqoFfCS0lJgbe3t0qdra0tnJ2dkZKSonW7GzduQCaTQSAQYNy4cQgMDESPHj2wbNkyyGQyrdsRQtSVXL2AGze+Uqnr6P0yBDG08gEhNdHrkmZRURFsbdUfcbazs0NhYaGGLSrk5uYCABYsWIAXXngBM2bMwNWrV7FixQrweDzMnTtXz7ArsCyL0tLSOm0LABKJROVvUoH6RTtD940yLQM3jn4AuXk5V+dqFgXLAaPq9bvQEAzdN80Z9Y1mDdkvlpa1jzXVK+HVlVJZsSxJ9+7dMW/ePABAt27dUFJSgo0bN2L69OkwNzfXe78ymQy3bt2qd3ypqan13kdrRP2inSH6xqygGPh3LcR2uVydhbItygLG49bt200ejzb0c6Md9Y1mDdEv4eG1X+HQK+HZ2tpCLBar1RcWFsLOzq7G7YCKJFdddHQ01qxZg7S0NIhEIn1CAQCYmJjA19dX7+0qSSQSpKamwsvLCxYWFnXeT2tD/aKdwfrmSRHyDi5DkmMSVyWAOfxHfgNzW/emi6MG9HOjHfWNZk3dL3olPG9vb7V7dWKxGDk5OWr39qqrLSmVl5fX+Lo2DMPodBpbGwsLiwbZT2tD/aJdU/YNW1SMgp8245793yr1gQM+g6Nr83sik35utKO+0ayp+kWvh1ZiYmJw+vRpFBUVcXUHDhwAj8dDjx49tG7n7u4OoVCI06dPq9SfPn0a5ubm9TpLI6Q1YyVlkKz9GbcsD0DBk3P1XsGT4Ozd24CREdLy6JXwxo4dCysrK0yfPh1///03duzYgfj4eIwdO1ZlDN7EiRMxYMAAlW1nz56Nv/76C59++ilOnTqFNWvWYOPGjZg0aRJ94yFEA7ZcivJ1v+MuewClZlVfMh3ahsOn25sGjIyQlkmvS5p2dnbYvHkzFi9ejOnTp8PKygqjR4/G7NmzVdoplUooFAqVun79+uHLL7/E6tWrsW3bNri4uGDmzJmYOnVq/d8FIa0MK1dAtvkPPMw/gRzXNK7ezKINggcuBcOj8ayE6EvvpzR9fHywadOmGtts2bJFY/3gwYMxePBgfQ9JiFFhlUrIft6Lovv/IsXzElfPMHwEP/M5TC0cDRgdIS0XrZZASDPCsizkCYdRfvUKbrmdBstTcq/5dpsFe9dQwwVHSAtHCY+QZkS+/yTkpy/hTrvzKDct4epdOvaHZ/DLBoyMkJaPEh4hzYT82HkoDp9FpuMt5Fs/4Oot7TwR0GchGIYxYHSEtHyU8AhpBuTnr0G++xgKLLKR1uY6V88TmCF4QDwEptYGjI6Q1oESHiEGprh6B/JfDqCcL0GS2xmAqVryx6/nfNg4Nb/B5YS0RJTwCDEgxZ00yLbsgZJVIMntNGSCqlmH3PxGwE00zIDREdK6UMIjxECUaQ8h25gAKBRIc76KIsuqSaFt2ogg6vGuAaMjpPWhhEeIASgf5UK67jdAKkOudSayqk8KbWqN4AHx4AvMDBghIa0PJTxCmpjySSGka34FSssgMRHjrut5ldcD+34MS1sPA0VHSOtFCY+QJsSKSyBb8wtQVAwFI8dtt9NQ8GXc6x06T4SzF00KTUhjoIRHSBNhJWWQrv0NbG4BACDF5SJKzAu41+3bhcEnkiaFJqSxUMIjpAmwUhmk6xPAPngMAMi2TUG2/X3udVMLJwT3/ww8nt7T2xJCdEQJj5BGxsoVkG36A+z9TABAsVk+kl0vVjVgeAiOXQIzK2cDRUiIcaCER0gjYpUsZNv2QXk7BQAg50lx2/0MlEzV8lm+kdPh4BZuqBAJMRqU8AhpJCzLQr7zMJSXblWUweKu2wWUmYi5Nm069EaHzhMMFSIhRoUSHiGNRH7gbyhOVa1nl+V0F3lWGVzZwsYdgX0XgWHo15CQpkC/aYQ0Avnxf6A4dIYrF1rkIq3NFa7M45sieMDnMDGzNUR4hBglSniENDDFP9ch/+MoV5byy5Dk/S9YVC3mKurxf7B19jdEeIQYLUp4hDQgxbW7kP2ynyuzUOJOyG1I5QVcXTvhELj5jTRAdIQYN0p4hDQQxd00yH7cDSirlvfJiChAQWnVPJnWjr7w6zmfFnMlxAAo4RHSAJTpVSsfVCqIMEe6+BBX5ptYVUwKbWJhiBAJMXqU8AipJ2V2HqTrfgfKq+bElHZ2xW3pTpV2AX0Wwsq+Q1OHRwj5DyU8QuqBfVII6ZpfgBJJVaXIE7esD0JeXsRVtQ9+GW29Yw0QISGkEiU8QuqIFZdAuvZXoLCYq2M6uuO+XzLEube4Oru2ndEp6i1DhEgIqYYSHiF1UVYO6fe/gc3J56oYNxc86WeNrNsJXJ2JuT2CY5eAxzcxRJSEkGpoanZC9MTIFWC27AWb9biqro09pC9G4NbBuOotEdT/M5hbt236IAkhaijhEaIPhQLtT14D8yCvqs7WGszkYbh2bDqU8jKu2jsiDk4eUQYIkhCiCV3SJERHbLkUzI4jsKme7CzNYRI3BklXv0FpQRpX7dS+OzqGTTZAlIQQbegMj5BaKLMeQ3HmMhT/3gRTLq16wdQEpq+PQWbeEWSnVI23M7Nui8B+i2lSaEKaGUp4hGjASmVQXL4NxZkrYNMeqL/O58H0tZEQm+fi7sGvuHqGJ0DIgHiYmts3YbSEEF1QwiOkGuWjXCjOXIHiwnVAUq6xjdzMBLwXBkLR3g5XE94Eq5Rzrwmj58LOJaipwiWE6IESHjF6rEwO5dUkyM9cAZuSqbUd4+0BRbg/7vBlEHVqj+t/zUN5cTb3elufgfAIHNMUIRNC6oASHjFaypwnFWdz/1xXnSmlOgsz8COCwI/uDJ5rG5SWloK9dQuZ137Ek8yzXDMr+47w772AJoUmpBmjhEeMCitXQHn9LhRnrkB5N01rO6aDGwTdQ8HrLAJjqjpoXFZ4Axl3f+DKfIEFgp+Jh8DEstHiJoTUHyU8YhSUeQVQnL0KxflrgLhEcyMzU/DDA8CPDgXP3UVjk/KSbJTcXw+gagkg/5gPYO3g3QhRE0IaEiU80mqxCiWUN5OhOHMZyqT71XOUCsajLfjRoeCH+YMxM9W6P6VChqQTH4KVVyVMj4AxcO00qKFDJ4Q0Akp4pNVh84sgP3cVinNXVSZ2VmFqAn4Xf/C7dwavfbva96lU4MbRD1Gce4Ors3UOhLD7nIYKmxDSyCjhkVaBVSqhvH2/4t7czWSA1Xw6x7RzBr97KPhhAWAszHTctwI3jn2E7OQ/uTqBqS2CB3wOHl/7GSEhpHmhhEdaNLaoGIpz1yA/ewXIL9LcSCAAr4sfBNGdwXRw0+tJSpZV4tbJT/Ho7t6qSkYAUczHsLCp/cyQENJ8UMIjLQ6rZKG8m1Zxb+76PUCp1NiOcXGsOJsLDwRjZaH/cVgWSX9/jge3/6jaJ88EVj7TYNcuvM7xE0IMgxIeaTHY4lIozl+rmO4rr0BzIz4fvBAhBN1DwXh71HlcHMuyuHN6OTJv/s7VMTw+RDEfI7vYqU77JIQYFiU80qyxLAs2OQPyM1egvHoHUCg0tmPa2IPfrTP4kcFgrOs3Ho5lWdw7+w0yrm+r2j/DR1D/JbBxjUb2rVs1bE0Iaa4o4ZFmiWVZKG+lQP7nKbAZjzQ34vHAC+5UMQuKbwcwvIaZ5ST5n++QdnVLVQXDQ2C/j9HWuz9KS0sb5BiEkKZHCY80KyzLQnn7fkWiS3+ouZGDLQTR/53N2Vo36PFT/l2H1EsbqtUwCOjzIVx9n23Q4xBCmh4lPNIs1JroGAa8QJ+KWVBEXmB4Db/WXOqlH5ByYY1KnX/vBXATDm3wYxFCmh4lPGJQtSY6Pg/8qBAI+kWBcbRrtDjSrv6Ee+dXqdT59ZwHd78RjXZMQkjT0vtrcnJyMl599VWEhoaiR48eiI+Ph1QqrX3DajZt2gSRSIS4uDh9D09aCZZlobh9H9IVWyFb97t6suPzwI/uDLP5r8Nk9DONmuwyrv+Cu2e+UqkTdp9LS/0Q0srodYZXWFiIiRMnwsvLCytXrkR2djaWLl2KsrIyLFy4UKd95OTk4Ntvv4WTEz3abYxYloUyKbXijE7DSuLg88CPDIagf7dGTXKVMm8mIOlUvEqdb9QseAa/3OjHJoQ0Lb0S3vbt21FSUoJVq1bB3t4eAKBQKPDRRx8hLi4Obdu2rXUfy5YtQ79+/fDggYYPO9JqsSwL5Z3/El2qhv973n+JLrZpEh0APLi9G7dPfqpS59P1TXiFTmiS4xNCmpZelzRPnDiB6OhoLtkBwKBBg6BUKnHq1Klat79w4QIOHz6MuXPn6h0oaZlYloUiKRXSlT9DtvY39WTH44HfLQSm778OkxcGNlmye3h3H24e/1ilrmPY6+gYNrlJjk8IaXp6neGlpKTg+eefV6mztbWFs7MzUlJSatxWoVBg8eLFmDZtGlxcNK81RlqPijO6tP/O6LLUG/B44EcGgR8bDV4TJblK2cmHcOPoh6i+XlCH0InwjqB7yoS0ZnolvKKiItja2qrV29nZobCwsMZtf/75Z0gkEkyaNEmvAGvCsmy9BgJLJBKVv0mFevULywLJmWD+Og9Gw1OXLI8HdPED2zsCSkdbyACgCQdz56WfQNKJhQBbNf9mO/8X4BY0Waf3Sz8z2lHfaEd9o1lD9oulZe0zLDXJsIS8vDysWLECn3/+OUxNG245FZlMhlsNMM1Tampq/YNphfTqF5aFVXY+nK+mwCpH/csPyzAo8G6HnEAvyGwsgOysij9NSFpwFSXJ3wFs1fRkZs59ILHsj9u3b+u1L/qZ0Y76RjvqG80aol/Cw2uf0F2vhGdrawuxWKxWX1hYCDs77ZelvvnmG4hEIkRERKCoqGIJF7lcDrlcjqKiIlhaWkIg0D/3mpiYwNfXV+/tKkkkEqSmpsLLywsWFvrPpt9a6dUvLAuk/HdGl6bpjI4BQv3A9omAnaMdmvbiZZX8B+dw++JalWTX1ncYvLu9A4bR/VY2/cxoR32jHfWNZk3dL3plGW9vb7V7dWKxGDk5OfD29ta63f379/HPP/+ga9euaq917doV69atQ0xMjD6hAAAYhtHpNLY2FhYWDbKf1qamfmFZFsp76RX36FIy1RvwGPAjgsAfEA2ek33jBlqLJ1nnkXTsA7BKGVfXTjgMAX0W6pXsqqOfGe2ob7SjvtGsqfpFr4QXExODNWvWqNzLO3DgAHg8Hnr06KF1u/fff587s6v02WefwdzcHHPmzIFIJKpD6MQQdE50sd3Aa+PQ9AE+Jf/hJVw+MBtKRTlX5+r7LAJ6/6/OyY4Q0jLplfDGjh2LLVu2YPr06YiLi0N2djbi4+MxduxYlTF4EydOxIMHD3Do0CEAgL+/v9q+bG1tYWlpiaioqHq+BdJUFHfTak504YEVZ3TNINEBQMGjq7i8/y0o5WVcnYt3LAL6fgSGxzdgZIQQQ9Ar4dnZ2WHz5s1YvHgxpk+fDisrK4wePRqzZ89WaadUKqHQsm4ZaXkUlWd0yRnqL1Ymutho8JybR6IDgMLHN3Bp/wwoZFVPgDp79UZQv0/A49EUsoQYI71/8318fLBp06Ya22zZsqXG13VtQwzsfhbKj13QnOgYBryIQAiaWaIDgKLc27i0dzoU0hKuro1nTwTHLgWPb2LAyAghhkRfdYkKVskCd9Phdfhf8LILqg3N/g/DgBceAMGAaPCcHQ0RYo2K8+7i0t43IZdWPU3s6NENwQPiweM33JAYQkjLQwmPAACUeQVQ/HMdin+ug5dfBKunGzTzRAcAxfkp+DfxDcjKqsYBOrhFoPMzX4AvMDNgZISQ5oASnhFjpTIor92B4vw1KO+ma25Umehio8FzaZ6JDgBKCtJwMXEaZGX5XJ29axeEPvs1+CY07okQQgnP6LAsCzb9ERTnr0Jx6TZQVq65HcMAIUKYDerVrBMdAJQWZuBi4jRIS/O4OjuXYIQO+oaSHSGEQwnPSLDiEij+vQnF+WtgH+Vqbce0dYKiix/uWDIQhoWC18wHyUrED3ExcRrKSx5zdbbOAQgdvBICU7ULs4QQI0YJrxVjFUoob6dUXLK8kQwolZobmpmC38Uf/KhgMJ7tIJFIoGiAOUobW1lxNi7uiUNZ8SOuztpJhC6DV8HEzMaAkRFCmiNKeK2QMjsPivPXoLhwAxCXaG3H8/UEPzIYvBAhGNOW9bh+eUkOLiZOg0RcNQG1laMPwoZ8CxNzQ83YSQhpzijhtRJsWTkUl29Dcf665vXnKtnbgN81qCLRGXiOy7oqL83Dv4nTUFpY9aCNpb0XwoZ8B1OL5jUmkBDSfFDCa8FYlgWbkgn5+WtQXkkCpDLNDfl88II7gR8VDF6nDmB4LXcOSakkHxf3voHSglSuztLOE+FD18DM0slwgRFCmj1KeC0QWyCG4sL1igdQcgu0tmM82oIfGQx+F38wVi3/aUVZWSEu7p2OkifJXJ2FjTvChq6BmZWzASMjhLQElPBaCFYuh/L6vYoHUJJSK9ah08TSvGJuy8gg8Nzbam7TAsnLxbi0bwaK85K4OnNrV4QNWwNz69bzPgkhjYcSXjOnzMqG4vx1KP69AZSWaW7EMOCJOlZcsgz0AVOHxXSbM7m0BJf2zURRzk2uzszKBWFD18DCxs2AkRFCWpLW9cnYSrAlEigu3oLi/FWwWY+1tmOc7MGPCgY/IgiMfet8DF8hk+Dy/lkofHyNqzO1dELY0DWwtGtvwMgIIS0NJbxmglUqobybBsW5a1BeuwtoW17J1AS8ziIIIoPBeHuAYZimDbSJyMqLkHnzd2Rc/wXS0qqB8ibmDggbugZW9h0MGB0hpCWihNcMKLPzINuYADYnX2sbxsu94gGUUBEY89Y7EXJpUSYyrv2MB7d3QyGXqLxmYm6H8KHfwdrB20DREUJaMkp4BsbKFZBt2qU52dlYgR8RWDFmrm3rfuS+MPsa0q5uweP7RwFWfUYYU0snhA5aAWunTgaIjhDSGlDCMzDFsX/AZldNegweD7wAn4oHUPw6guHzDRdcI2OVCuSkHkfa1Z9QmH1FYxtz63ZoH/wS3P2GQ2Bq3cQREkJaE0p4BqTMK4D80OmqCisLmM2d1GofQKmkkEnwIGk30q/9DElRpsY2ts6B8AwZBxfvfuDx6MeUEFJ/9EliICzLQr7zCCCTc3WCYX1adbIrL8lBxo1fkXnzd8jLizS0YNCmQww6hIyDfbsurfaBHEKIYVDCawLKlEwoLt0CL1gIvrDi6ULl9XtQ3qyaMYTp6AF+RJChQmxUxU/uIe3qVjy6ux+sUn36Mx7fDO1EQ+EZ/Ao9fUkIaTSU8BoZWyKBdN3vQLkUivPXwJs3BbA0h2zn4apGPAYmoweA4bWeMxqWZfEk6xzSr/yEvMwzGtuYWjjCI/AFeASMpkmfCSGNjhJeI1PeSQXKpRUFmRzyvy9W/LtAzLXhx0SA1651zAWpVMjwKPlPpF/5CcVP7mpsY2XfEZ4hr8C102DwBa13iAUhpHmhhNfI2BLVsWTKq3fA5le7f2VvA8HAHk0cVcOTlRch6+YOZFz/BeWlORrbOLhFoEPIODh59gDDtNwVGwghLRMlvEbGPilULecVqJRNRvQHY2bahBE1LElRFtKv/YwHt/9QGygOAAyPj7bez8Az5BXYOvsbIEJCCKlACa+ByP88BcXVO+BHd4agZxhX/3TCq44X4A1ecMscSF3bQHG+qRU8/EahffBYmFu7GiBCQghRRQmvASgzHkH+5ykAgHznYfCEHcBzqZgZRWvCMxFAMDK2RT16zyoVyEk7jrQrNQ0Ud0X74JdpoDghpNmhhFdHLMtCefEmFNfvQZmaVe0FQLp0A3iijmDatQGbma1xe8GAaPCc7Jsm2HqqGCi+B+nXttYwUDzgv4Hi/WmgOCGkWaJPpjpg5XLINiRULMSqhTLpPpB0X+NrjIsj+H0iGym6hiOV5OHB9U3Iuvk7ZOWaz1TbdOhNA8WrkcvlkEqlhg7DICQSicrfpAr1jWa19YuJiQkEAkGDfbZQwqsDxZFzNSa7GtnbwGTcMDCC5jtHpqQwHSX3N+Hfi/9oHyguHArPkJdhZe/V9AE2QyzLIj09Hbm5ubU3buVSU1MNHUKzRX2jWU39IhAI4O7uDicnp3onPkp4emJZtmL18TownT0BvPbN9wEOlmWRefM33Dn9pcZEZ2LugPZBL8AjYAwNFH9KZbJzd3eHtbU1eDwadkFIfbAsC5lMhvz8fKSlpaGkpAQdOtRvJiZKeHpiM7PB5hbUaVumjX2DxtKQ5NIS3DrxCbKTD6q9ZmnvhQ7cQHFzA0TXvMnlci7Zubo23y80hLRE9vb2MDc3x4MHD2BiYgI3N7c674u+hupJcelW7Y14DEwmjVCrZiyaZ7IQ593F+YTxasnO1qUzOj/7FaJf+A3u/qMo2WlRec/O2pqeSiWkMdja2gIADh06hMxMzQ/O6YLO8PSkvKZ5uqxKglGx4Ik6gufsAGXPMCj+m0qMJ+rYFOHphWVZPEjajaS/P4dSUc7VMzwBzN2fR2Dv6bCysjJghC0LXcYkpHFU3rsrKirClStX4OHhUaf9UMLTA1suVZkphd8rHIqT/6q04YcHgrGomB9SMCQGkMrAlkogGNK7KUOtlUImwe2/l+LhnUSVenNrV3TquQiZuTx66pIQ0qxYW1sjPT0dMpkMJiYmem9PCU8PT9+743l7qCW8ymQHAIyZKUzGDmqK0PRSkn8fVw+9h5L8ZJX6Np69ENj3I8iUJkCuDpduCSGkCfH5fCiVSigUCkp4jY3NzVcpM84O4IWKoLycBADg+TW/y5ZPe3h3H26f+Exl3kuG4cMncjo6dB4PhuFBVlpqwAgJIaRxUMLTA5vzVMJr4wDBsz0hy8kH5AoIBvUyUGS1U8jLcef0F8i6laBSb2bpjODYJbBv18VAkRFCSNOgu+x6UDnDs7MGY2oCnosTzOZOgum7rzXbMXalhRn4Z9erasnO0SMKUaN/pmRHWqx169bh2WefhVKpPoF5fWzbtg19+vRpMbPmzJs3DyKRCCKRCEOHDjV0OLXatGkTF69IJMKTJ0+a5LiU8PSgrHaGx7RRHXjdXB/wyE45jHM7XkFxXlK1WgbeEdPQZdBKmFo4Giw20jIkJCRwH0wXLlxQe51lWfTu3RsikQhxcXEatxOJRAgICECvXr0wb948ZGerzjGrT9tKxcXFWL9+PV5//fUGf0J21KhRkMlk2L59e4Pu9+LFi1i5ciWKiopqb1zN7du3MXfuXPTq1QtBQUHo0aMHXnrpJaxatYpr4+DggPj4eMydO1dl23Pnzqn0bfU/ly9fboi3pbdevXohPj4eAwYMaNLj0iVNPVQ/w+O1ad4zjSgVMtw9+zUyrqv+wppaOCKo36dw9Gj+c3mS5sXMzAyJiYmIiIhQqT9//jwePXoEU1PN6zq+9dZb8PDwgFQqxeXLl7Fz5078+++/SExMhJmZWZ3b/v7775DL5Y1yRmNmZoYRI0Zg06ZNGD9+fIN9ob106RJWrVqFkSNHcmPLanPw4EHMmTMHbm5uePHFF9G2bVs8ePAAZ86cwe7duzFjxgwAgKWlJYYPH651P+PHj0dwcLBKnaenZ93fTD34+PjAx8cH6enpOHToUJMdlxKejtiyckBcwpUZ5+ab8CTiB7h2eB6KHqtOgWbfLhzB/T+FmZWzgSIjLVnv3r1x4MABLFiwAAJB1UdHYmIiAgMDUVBQoHG7mJgY7oN2zJgxcHBwwLp163DkyBEMHjy4zm0TEhLQr18/tUTYUAYNGoT169fj7NmziI6ObpRj1KawsBDvv/8+goODsXnzZpUvFbNmzdJ69qtJREQEnn322cYIs8WgS5q1UFy4Ael3v0C26Q+V+qcvaTYXOakncG7HK2rJzqvLawgbupqSHamzIUOGoKCgAKdOneLqpFIp/vzzTwwbNkzn/VSeIWZkZNS5bUZGBpKSktC9e3eV+ldffVXrZbJRo0ZhzJgxOscZFBQEe3t7HDlypNa2WVlZWLRoEQYOHIiQkBBERUXhrbfeUpkVZOXKlYiPjwcA9O/fn7usWNPMIadPn4ZYLMbo0aM1nkG3bdtW5/cDVFwGlsvlem2jyblz5/D6668jIiICkZGRiIuLQ3p6er3329joDK8GypRMyH7eq/G15pbwlAoZkv9ZjbQrP6rUm5jZIbDfYrTx7GGgyEhr4e7ujtDQUOzduxe9e1dMpHDixAmIxWIMHjwYW7Zs0Wk/WVkV60fqcklPW9tLly4BAAICAlTqfX19ce7cOUilUpUEcfjwYdy4cQMbN27UKcZKAQEBuHjxYq3trl27hkuXLmHIkCFwdXVFVlYWtm3bhgkTJmDv3r2wsLDAgAEDkJqaisTERMyfPx8ODhWfIY6O2u+jVy6bk5SUpLWNrubPn4/S0lLw+XyEh4fj3XffVbvEqYuEhAR88MEH6N69O95++21IJBL89NNPmDRpEvbt2wdz8+Y7BSElPC1YhQKy39UnUgYA2FqBadt8HvYoK87GtSPzUfhIdRVyu7YhCI5dAnPr5vn0aGvHKpVgHzwGpPX/Rl1vpgIwbi5g6vlwx7Bhw7B8+XKUlZXB3Nwce/bsQdeuXWs80yguLsaTJ08glUpx5coVrFq1Cqampujbt2+d26akpACA2hRTnTp1gkKhQGpqKoRCIYCKh2pWrFiByMhI9Oih3xe/9u3b65Tw+vTpo3a5sG/fvnjxxRfx559/YsSIEfDz80NAQAASExMRGxur0/RYUVFRsLCwwObNm3H8+HHExsaiV69e6Nq1K/h83ZYYMzExwcCBAxETEwMHBwckJydjw4YNeOWVV7B9+3a1Lw01uXPnDhYuXIiZM2fizTff5Op79eqF4cOH48SJE3jmmWd03l9To4SnheL8NbCP1Nc2Y5zsYfLqSDA6/rA1tryMM7j+1wLIygpU6j1DxsE3cgZ4fP1nIyD1x8oVkK76GWz6Q0OHwmE828F0xsv1Wotx0KBB+Oyzz3D06FH06tULx44dw4IFC2rcZtKkSSpld3d3LFu2TOPKErq2LSgogEAgUJvr1dfXF0BFQqxMePv370dSUhK2bt2qy1tUYWtri7KyMkgkElhYWGhtV/2sRiaTobi4GJ6enrC1tcXNmzcxYsQIvY8NVLz/7du3Y82aNTh+/DjWr1+P9evXw83NDZ9++qnaJV1NwsLCEBYWxpX79++PgQMH4rnnnsPy5cuxYcMGneP59ttv4ebmhrFjx6oMJXBxcYGJiYlOl6kNiRKeFsp7qtej+T3DwNhag98jtFmsesAqFUj593vcv7gBAMvVC0ytEdBnEVw6qn97Jk2HfVLQrJIdALDpD8E+KQDj4lTnfTg6OiI6OhqJiYkoKyuDQqHAwIEDa9xm4cKF6NixI8RiMXbs2IF//vlH6xOd+rTVpFOnTgCqzgCVSiVWrVqFnj17qjxd+vPPP+O3337DnTt3MG3aNMycOVPj/li24nertqc0y8rKsHbtWiQkJCA7O5vbDgDEYrHO8Wvi5+eHr7/+GlKpFJcuXcKuXbuwc+dOzJ49G8eOHasxEWvToUMH9O/fHwcPHoRCodDpbFEqleL48eOQSCRaH+Kp/AKia/82NUp4WrD5VT+kPGEHmIyKNWA0qspLc3H9yAfIf6A6JsqmjT+CByyFpW3dZhInDYdxtAfj2a5ZJT3Gsx0YR/t672fo0KH43//+h9zcXMTExNR6Ly4kJIS7VxQbG4uXX34Zc+fOxYEDB9TO0HRta29vD7lcjuLiYpVlmWxsbODi4sIlvD179iA5ORmff/65ynFcXFwwY8YMJCaqTp7+tKKiIlhYWNR6X2rx4sVISEjAxIkTERoaChsbGzAMg9mzZ6skv/owNTVFVFQUoqKikJ+fj6NHj+L+/ft6XZKsztXVFTKZDBKJRKelrTIyMiCRSDBr1iyEhoZqbOPn5wdA9/5tanonvOTkZHzyySe4dOkSrKysMHz4cLz99ts1fgt7/PgxNm3ahFOnTiE9PR02Njbo2rUr5syZA3d393q9gcbCFlQNDGXsdRsv0xSeZP2D60c+gFSSp1LvEfgChNGzwePr/m2YNB5GwIfpW6+0unt4ADBgwAB8+OGHuHz5Mr766iu9tuXz+ZgzZw4mTJiArVu3YurUqXVq6+3tDQDIzMzkPmQrderUCSkpKVAoFFi9ejViY2PVHs6Ija34Anv8+PEa483MzOSOVZPK+3Tz5s3j6srLy9XO7hpqPF/l562NjU2d95GZmQkzMzNYWlrq1L6kpGJYlo+PT62XUnXt36amV8IrLCzExIkT4eXlhZUrVyI7OxtLly5FWVkZFi5cqHW7Gzdu4NChQ3j++efRuXNn5Ofn47vvvsOYMWOQmJhY41NKhsAqlEBhcVWFfd1/qBoKyyqReukHJF9YA7BV0yjxTSzhH/M/uPo23xvFxorh8cB4tL4HhqysrLBo0SJkZWWhX79+em8fFRWFkJAQbN68GRMnTqxxHJ22tl26VEyHd/36dbWE5+vri99++w07d+5Eeno6Vq5cqXeMlW7evKnTkAtNlwS3bNkChUKhUld5+VGXy5wXLlxAUFCQ2tnl7du3cfLkSQQEBKB9+/a17ufJkydqn7G3b9/GX3/9hV69euk8S427uzsYhsHBgwfVLmPL5XKUlJTAzs5Op30Zil4Jb/v27SgpKcGqVatgb28PAFAoFPjoo48QFxen9Umt8PBw7N+/X2WwalhYGPr06YNdu3bhtddeq/s7aAxFxUC1yxCMg2HP8KSSfNz463/IyzyjUm/t6IvgAfGwsu9goMiIsRo5cmS9tp88eTJmzZqFhIQEvPTSS3q3bd++PYRCIc6cOYPRo0ertO/UqRNKS0uxfPlyDB48mHt4RV/Xr19HQUEB+vfvX2vbPn364I8//oC1tTV8fX1x+fJlnD59mvucrBQYGAgA+OqrrzB48GCYmJigb9++Gs+yli9fjtTUVDz77LPw8/ODXC7H7du38ccff8DGxoYb01ebt99+G+bm5ujSpQucnJxw7949/PrrrzA3N8c777yj1l4kEiEyMlJtmImTkxOGDBmCxMREFBcXIyYmBgqFAunp6Th48CC+/PJLtVl4mhu9Et6JEycQHR2t8p84aNAgfPjhhzh16hRGjRqlcTtN1/hdXV3h6OiIx48f6xdxE6h+ORMwbMIreHQZ1w7PR3mJaj+5+Q2HqMe74AsM/wANIfp65pln4OnpiY0bN+KFF17Qq23l2dTzzz+Pb775hhsiUanySc3CwsJ6PSxx4MABuLm5oVu3brW2/eCDD8Dj8bBnzx6Ul5cjLCwMP/zwA6ZMmaLSLiQkBLNmzcL27dtx8uRJKJVKHDlyRGPCe+2113DgwAGcOnUKu3btgkKhgIeHB8aNG4cpU6bofGUsNjYWe/bswaZNm1BcXAwHBwcMGDAAM2bMQIcOql+WKy9bOjtrnqBiyZIlEAqF2L17N+Lj42Fubo727dtjzJgxXDJvzvRKeCkpKXj++edV6mxtbeHs7MzdJNbV/fv3kZeXBx8fH722q45lWZTWY+22ykGdlX9zHuWqTEFTbm4CNPEacSzL4sHN7Ui7tBZgqy6L8Pjm8I6aCxefZ1EuVQLSho9La78QjX3T2vtp1KhRWr/MVvfXX3/pvB2Px1OZQ1GftpWef/55fPfdd9izZ4/KDCpdunSp90BtqVSKXbt24fXXX9fpvputrS2WLFmiVv90nwDAm2++qTKGTZsBAwboNbmyUqnEkydPIBAIVE4yJkyYgAkTJui0jwsXLoBhGJVJwKszNTVFXFyc1td1VV5ejpKSEr1/dxQKBeRyOUpLS9VWyNDlXqReCa+oqEjj2ZqdnR0KCwt13g/Lsvjkk0/g4uKCIUOG6BOCCplMhlu36r8yd2pqqkq5zd1UVL84e/thFticR/U+jq6U8hKUpm6CrEB1IDnPvB2sfeKQJ3VDXgO879o83S+kCvWN4dnY2GDy5MnYsGEDnn/+eb1WTJDL5VAoFFAqlZDL5SgvL4dAIODOHnfs2AGBQFDr5dbm5OHDh4iOjkanTp3q/HTk2bNnMWTIEIhEonrFUlv/btu2TeMXhNoUFRUhPz8fSUlJag9KhoeH17q9QYYlrFy5EmfPnsX69et1fkJIExMTE+7yRV1IJBKkpqbCy8tLZSwLc6/q8iFraQ6/4KA6HwMA8tJPIOf+QbTx7IM2HWse3iDOvYU7J+IhK1F9nN254zPwjpoLvknd+0tX2vqFaO6byjrS9KZOnVrjk57afPfddypL66xZswZLlizhzjJfeumlFpXspkyZgueeew6Abmc62rz33nsNEk9t/Ttw4ECVe6u6Pm1aecIlEonqNIWZXgnP1tZW49NFhYWFOj+d8+uvv+Lbb7/Fp59+Wu8ZyBmGqdd/biULCwuV/UiLS1F5ssxztINZPY5RVpyNu39/BKVCivzMv9HGowss7dSfrGJZFpk3fsWdM1+CVVY9xs7jm0LU4124+Y1o8jX3nu4XUoX6pmWbOXNmsxkM3RB8fX3r9eW/odXWv+3atUO7du303i+fz4dAIIClpWXjJzxvb2+1e3VisRg5OTk6jVU5dOgQFi1ahLfeekvtyarmpPqg86fH4EnED5FxfTss7TzBE5gh/erPcPKIgm/UWxoTUnbKISgVFasms0oFHt7dB58I1evf8nIxbp74BI9TDqvUW9i2R8iAz2HTpn6XFwghhOiZ8GJiYrBmzRqVe3kHDhwAj8erdVLWc+fOYc6cORgzZgymT59e94gbGcuyYPOrDzpXPdW+8df/UPDokkpdcV4S7F1D4ezVW21/kkLVueXKi1XXr8p/cBE3jv4PZcWq9whdvGMR0Pt/EJjWPgMCIYSQ2umV8MaOHYstW7Zg+vTpiIuLQ3Z2NuLj4zF27FiVMXgTJ07EgwcPuCerkpOTMX36dHh5eWH48OEqy8o7OjoabNVdTZRJqYCkjCszTlWXauWyUrVkVynrVoJKwit4dBWplzchN011pgFx3p2K4yikSP5nzX/L+VQb88cTQBg9Bx6BLzT5JUxCCGnN9Ep4dnZ22Lx5MxYvXozp06fDysoKo0ePxuzZs1XaKZVKlRkGrly5ArFYDLFYrHYjeOTIkVi6dGk93kLDYVkW8gN/V1XweOAFdeKKpQVpWrctyrkFllWCYXiQSvJxad8MKGQlau2Kn9xDUe5t3Dz2EYr/S36VLGzdEdT/M9i51O8hGUIIIer0fkrTx8cHmzZtqrHN0yP0dR3HY2jKe+kqk/3yuwaC52TPlUvy72vdVirJgzg3CbbO/ki/ulVjsgMAVinD+YTxKtODAYCb3wgIu8+FoAmewiSEEGNEqyVUw6ZkVhUYoCzSDalnV6AkPxnOXr0hEdc88/3N4x8jdOCXyLjxSy0Hqkp2Jub28I9ZQMv5EEJII6OEV40yp2pBw8K2Jbh+eCo3RCA3/W9tm3GK8+7g75+H6nw8J88eCOi9EGaWbfQPlhBCiF4o4VXDPq5KeI/t0lTGwz3NzMoFnbq9jZL85P8WYdUdT2AGYfQcuPs/Tw+mEEJIE6GE9x+WZcHm5HPlMpMSQKa9fTvhULj6DgTLKmFm5YI7Z76EUl6u0iao/6ewsu8IWXkRzK1dce/8SvAF5vDq8hqs7L0a6Z0QQgjRhBJeJXEJUC7limWoeW5QK/uOAACG4cEjYDSs7Dvi3z1xqBxiYO0kRFufZ8AwVfP7hQzQbTkPQgghDa/+yx+3EtXP7lgoIZVVlV07DVZrb+XQUaXs4BYO36i3ADAQmFrDv9f7KsmOEEKIYdEZ3n+qP7BSLpCARdWTlI7uXdHGsyeuH3kfAGBq6QRrR/VljbxCJ6Bdp0HgC8whMDP8KumEEEKq0CnIf6o/sFJuXqbymrl1O7j6DkTIwOVoH/wyugz+Fjy+6dO7AACYWTlTsiOkiaxbtw7PPvus2tpo9bVt2zb06dMHUqm09sbNwLx58yASiSASiTB0qO5PihvKpk2buHhFIhGePHlS+0YNgBLef6pf0ix3ZFVes7BxAwC4ePWBqPtc2Dh1AiHGIiEhgftgunDhgtrrLMuid+/eEIlEKguDVt9OJBIhICAAvXr1wrx585CdrTqnrD5tKxUXF2P9+vV4/fXX9VoLTxejRo2CTCbD9u3bG3S/Fy9exMqVK1FUVFR742pu376NuXPnolevXggKCkKPHj3w0ksvqSzB4+DggPj4eMydO1dl23Pnzqn0bfU/1ad5bEq9evVCfHy8XgvcNgS6pPkf9lEuAOCJ1QPcsag25o7hwczKxUBREdJ8mJmZITExERERESr158+fx6NHj9QW5Kz01ltvwcPDA1KpFJcvX8bOnTvx77//IjExEWZmZnVu+/vvv0MulzfKGY2ZmRlGjBiBTZs2Yfz48Q02fOjSpUtYtWoVRo4cqXExbU0OHjyIOXPmwM3NDS+++CLatm2LBw8e4MyZM9i9ezdmzJgBoGIdvOHDh2vdz/jx4xEcHKxSZ6h5jH18fODj44P09HSNq9k3Fkp4AFAgBptXgCLzXNz0OKnykrmVC3h8EwMFRkjz0bt3bxw4cAALFiyAQFD10ZGYmIjAwEAUFBRo3C4mJob7oB0zZgwcHBywbt06HDlyBIMHD65z24SEBPTr108tETaUQYMGYf369Th79my91+6sq8LCQrz//vsIDg7G5s2bVb5UzJo1S+vZryYRERF49tlnGyPMFoMuaQJAcsUSPnk2mWovmVvrv0ghIa3RkCFDUFBQgFOnTnF1UqkUf/75J4YNG6bzfirPEDMyMmppqb1tRkYGkpKS0L17d5X6V199VetlslGjRmHMmDE6xxkUFAR7e3scOXKk1rZZWVlYtGgRBg4ciJCQEERFReGtt95CZmbVZ8rKlSsRH18xNKl///7cZcXqbZ52+vRpiMVijB49WuMZdPVVanRRXFwMuVz7hBq6OnfuHF5//XVEREQgMjIScXFxSE9Pr/d+Gxud4QFgUrIAAGJz9RunJua6XXYg5GmsUgFx3h0o5WW1N25kPIE5bJyEYHj8Ou/D3d0doaGh2Lt3L3r3rlgK68SJExCLxRg8eLDapPHaZGVV/L7pcklPW9tLlyqW6QoICFCp9/X1xblz5yCVSlUSxOHDh3Hjxg1s3LhRpxgrBQQE4OLFi7W2u3btGi5duoQhQ4bA1dUVWVlZ2LZtGyZMmIC9e/fCwsICAwYMQGpqKhITEzF//nw4ODgAqFgiTRuJRAIASEpK0ituTebPn4/S0lLw+XyEh4fj3XffVbvEqYuEhAR88MEH6N69O95++21IJBL89NNPmDRpEvbt21enlcibCiU8lgVSKr49lpkUq71sZV/7Su6EPE2pkOHC7skoenzD0KFwbF0CEfHchnpdoh82bBiWL1+OsrIymJubY8+ePejatWuNZxrFxcV48uQJpFIprly5glWrVsHU1BR9+6pPmK5r25SUFACAh4eHSn2nTp2gUCiQmpoKoVAIoOKhmhUrViAyMrLWhaqf1r59e50SXp8+fdQuF/bt2xcvvvgi/vzzT4wYMQJ+fn4ICAhAYmIiYmNj1WLXJCoqChYWFti8eTOOHz+O2NhY9OrVC127dgWfr9uXFxMTEwwcOBAxMTFwcHBAcnIyNmzYgFdeeQXbt29X+9JQkzt37mDhwoWYOXMm3nzzTa6+V69eGD58OE6cOIFnnnlG5/01NaNPeKbiUjDiUsh45ZCaSNReb+Op3y8IIQAgEWc1q2QHAEWPb0AizqrXtHaDBg3CZ599hqNHj6JXr144duwYFixYUOM2kyZNUim7u7tj2bJlcHV1rXPbgoICCAQCWFlZqdT7+voCqEiIlQlv//79SEpKwtatW3V5iypsbW1RVlYGiUQCCwsLre2qn9XIZDIUFxfD09MTtra2uHnzJkaMGKH3sYGK9799+3asWbMGx48fx/r167F+/Xq4ubnh008/Vbukq0lYWBjCwsK4cv/+/TFw4EA899xzWL58OTZs0H0u4G+//RZubm4YO3asylACFxcXmJiY6HSZ2pAo4YkrklyJmepUYvauXdAhdALs23UxRFikhbOwcYetS2CzSnq2LoGwsHGv1z4cHR0RHR2NxMRElJWVQaFQYODAgTVus3DhQnTs2BFisRg7duzAP//8o/WJTn3aatKpU8WQocozQKVSiVWrVqFnz57c/UCpVIoPP/wQZ86cQVFREXx9fTF//nx06aL+u86yFUOUantKs6ysDGvXrkVCQgKys7O57QBALBbrHL8mfn5++PrrryGVSnHp0iXs2rULO3fuxOzZs3Hs2LEaE7E2HTp0QP/+/XHw4EEoFAqdzhalUimOHz8OiUSi9SEeKysrvfq3qRl9wuOXV8wQXWJWoFIfHLsEZlbOBoiItAY8vgm6Dv+hVd3DqzR06FD873//Q25uLmJiYmq9FxcSEsLdK4qNjcXLL7+MuXPn4sCBA2pnaLq2tbe3h1wuR3FxMaytrbl6GxsbuLi4cAlvz549SE5Oxueff861kcvlcHd3x88//wxXV1fs378f06ZNw19//aUWT1FRESwsLGq9L7V48WIkJCRg4sSJCA0NhY2NDRiGwezZs1WSX32YmpoiKioKUVFRyM/Px9GjR3H//n29LklW5+rqCplMBolEotKH2mRkZEAikWDWrFkIDQ3V2MbPz0+v/m1qlPCkFQmvtFrCMzG3hymtUUfqieHxYevsb+gwGtyAAQPw4Ycf4vLly/jqq6/02pbP52POnDmYMGECtm7diqlTp9aprbd3xb31zMxM+Pn5qWzXqVMnpKSkQKFQYPXq1YiNjVV5OMPS0pIbuwZUPH26ZMkS3L9/H0FBQSr7yszM5I5Vk8r7dPPmzePqysvL1c7uGmo8X+VZr41N3Wd1yszMhJmZGSwtLXVqX1JSAqBiDF1tl1J17d+mZvTDEvhSOcr5EjyxrlrN3NqxE61TR4gWVlZWWLRoEWbOnIl+/frpvX1UVBRCQkKwefNmlJeX16lt5eWx69evq23j6+uL+/fvY+fOnUhPT8esWbNqPEZqaioKCwvRoUMHtddu3rypcv9LG02XBLds2QKFQqFSV3n5UZfLnBcuXEBZmfrVgdu3b+PkyZMICAhA+/bta92Ppmm7bt++jb/++gs9evTQeZYad3d3MAyDgwcPqr0ml8tRWKh5hZma+repGf0ZHq9cilvuf0MmqPrBcnTvasCICGn+Ro4cWa/tJ0+ejFmzZiEhIQEvvfSS3m3bt28PoVCIM2fOYPTo0SrtO3XqhNLSUixfvhyDBw/mHl7RpKysDP/3f/+HuLg4tbOl69evo6CgAP3796/1/fTp0wd//PEHrK2t4evri8uXL+P06dOwt7dXaRcYGAgA+OqrrzB48GCYmJigb9++Gs+yli9fjtTUVDz77LPcpcLbt2/jjz/+gI2NDTemrzZvv/02zM3N0aVLFzg5OeHevXv49ddfYW5ujnfeeUetvUgkQmRkpNowEycnJwwZMgSJiYkoLi5GTEwMFAoF0tPTcfDgQXz55Zdqs/DU1L+GYPQJTyrLQLFF1Tcga8dOaB9c8y8gIaR+nnnmGXh6emLjxo144YUX9GpbeTb1/PPP45tvvuGGSFSqfFKzsLAQM2fO1LpfmUyGWbNmwdPTE9OnT1d7/cCBA3Bzc0O3bt1qfT8ffPABeDwe9uzZg/LycoSFheGHH37AlClTVNqFhIRg1qxZ2L59O06ePAmlUokjR45oTHivvfYaDhw4gFOnTmHXrl1QKBTw8PDAuHHjMGXKlBrH71UXGxuLPXv2YNOmTSguLoaDgwMGDBiAGTNmqJ11VV62dHbW/PzCkiVLIBQKsXv3bsTHx8Pc3Bzt27fHmDFjuGReqbb+NQSGbag7qk3s2rVrAFCngZOVSktLkfn9IqRbVM2kEDV6u9FPDl1aWopbt27B399f5+v7xkJT31B/GYZYLEZsbCzeeecdvWZQASqe3pw7dy4kEglWrVqlMlUaUPFEYr9+/fD6669j4sSJDRl2o5g3bx7Onj2LhIQECAQCnefpfNrx48cRFxeHP/74AyKRqM7x1Na/5eXlKCkpwfr167FhwwacOXOmxgRe+Tt248YNiMViTJ48uU4D3I3+Hp5cqXot3dKu9mvihBDDs7GxweTJk7Fhwwa9lwdauHAhcnJy8M0336h9GAPAjh07IBAIar3c2pw8fPgQ0dHRePnll+u8j7Nnz2LIkCH1SnZA7f27bds2REdH6zUGsCEY/SVNBVs1u4oA5uALmu+0OIQQVVOnTq3xSU9NsrKy8Ntvv8HMzEzlcuW6deu4e1AvvfRSi0p2U6ZMwXPPPQcA9brK8N5779U7Fl36d+DAgSr3Vpvq/p7RJzwZqhKeqcDOgJEQQpqCu7t7g8xN2Zz4+vpy9y4NTZf+bdeuHdq1a/qJ+Y37kqaShZxXNZ2YmYm94WIhhBDSqIw74ZWXQyqoSnimZro99UQIIaTlMeqEx5aUqSQ8MwsnA0ZDCCGkMRl1wlMUP4GSVzUTAs2dSeqjhY7wIaTZq/zdqu/vmFEnPGnRI5WymY1+qwcTAlSsNwZUDLQlhDQ8qVQKAPVerd2oE55MnKNSNrVr+qeGSMsnEAggEAg0zllICKkflmWRm5sLqVRa7y+VRj0sQVqimvDMHdwMFAlpyRiGgbu7O9LS0vDw4UPY2trS5OOE1BPLspBKpcjNzUVhYSFyc3OhVCrBMIzOE14/zbgTXlmeStnUgc7wSN04OTmhuLgYWVlZePDggaHDIaTVqEx6YrEYxcXF6NixI3cbQV/GnfDK87l/C5SmEJjov3IwIUDFWZ6XlxeKi4vx999/A6hYRseYzvTkcjnEYjFsbGw0TidlzKhvNKutX+RyOWQyGZRKJcRiMfh8PgIDA+v8e2XUPS+XFXH/NlUadiVe0jpUzhh/5coVPHnyxKie3JTL5SgoKIBMJqMP9adQ32ima78wDIN27dqhc+fO8Pev+6LKRt3z1qbtkSOpWHXBQdA8puUhLRvDMAgKCkJAQABKS0v1ntS4JZNIJLhz5w6EQiG30CmpQH2jma79wuPxYGlpWed7d5WMOuG59o4DfpGAz1fCY1TNqyITog8ejwdra2tDh9GkBAIBLC0tYWNjQ8skPYX6RrOm7hejTniMsyMK+r8Ef39/COiHkBBCWjWjHodHCCHEeFDCI4QQYhQo4RFCCDEKlPAIIYQYBUp4hBBCjAIlPEIIIUaBEh4hhBCjQAmPEEKIUaCERwghxChQwiOEEGIUGLaFTud+8eJFsCwLU1PTOu+DZVnIZDKYmJgY1TIutaF+0Y76RjvqG+2obzRryH4xNTWFSCSqsU2LnUuzIX5oGIapV8JsrahftKO+0Y76RjvqG82aul9a7BkeIYQQog+6h0cIIcQoUMIjhBBiFCjhEUIIMQqU8AghhBgFSniEEEKMAiU8QgghRoESHiGEEKNACY8QQohRoIRHCCHEKFDCI4QQYhQo4RFCCDEKlPAIIYQYBaNMeMnJyXj11VcRGhqKHj16ID4+HlKp1NBhGVxaWhoWLlyI4cOHIyAgAEOHDjV0SM3C/v378cYbbyAmJgahoaEYPnw4fv/9d9C868Dx48cxbtw4dOvWDUFBQejfvz+WLFkCsVhs6NCanZKSEsTExEAkEuHatWuGDsegEhISIBKJ1P588cUXjXrcFrs8UF0VFhZi4sSJ8PLywsqVK5GdnY2lS5eirKwMCxcuNHR4BnX37l0cP34cnTt3hlKppA/0/2zatAnu7u6YN28eHBwccPr0afzvf//Do0ePMGPGDEOHZ1AFBQUICQnB+PHjYW9vj7t372LlypW4e/cuNm7caOjwmpXVq1dDoVAYOoxmZf369bCxseHKbdu2bdwDskZmzZo1bGhoKJufn8/Vbd++nfX392cfPXpkuMCaAYVCwf37vffeY4cMGWLAaJqPvLw8tboFCxawYWFhKn1GKvzyyy+sUCg0+t+n6u7du8eGhoay27ZtY4VCIXv16lVDh2RQO3bsYIVCocbfrcZkdJc0T5w4gejoaNjb23N1gwYNglKpxKlTpwwXWDPA4xndj4NOHB0d1er8/f1RXFyM0tJSA0TUvFX+bslkMsMG0ox88sknGDt2LDp27GjoUIya0X3CpaSkwNvbW6XO1tYWzs7OSElJMVBUpKX5999/0bZtW1hbWxs6lGZBoVCgvLwcN27cwLfffot+/frBw8PD0GE1CwcOHMCdO3cwffp0Q4fS7AwdOhT+/v7o378/1q5d2+iXfI3uHl5RURFsbW3V6u3s7FBYWGiAiEhLc+HCBezbtw/vvfeeoUNpNvr27Yvs7GwAQK9evbB8+XIDR9Q8SCQSLF26FLNnz6YvR9U4Oztj5syZ6Ny5MxiGwV9//YWvv/4a2dnZjfoshdElPELq49GjR5g9ezaioqIwYcIEQ4fTbHz//feQSCS4d+8evvvuO0ybNg0//PAD+Hy+oUMzqO+++w5OTk54/vnnDR1Ks9KrVy/06tWLK/fs2RNmZmbYvHkzpk2bBhcXl0Y5rtFd0rS1tdX4yHRhYSHs7OwMEBFpKYqKivD666/D3t4eK1eupHue1fj5+aFLly4YM2YMVq9ejXPnzuHQoUOGDsugsrKysHHjRrz11lsQi8UoKiri7vmWlpaipKTEwBE2L4MGDYJCocCtW7ca7RhGd4bn7e2tdq9OLBYjJydH7d4eIZXKysoQFxcHsViMX375ReVRaqJKJBLBxMQE6enphg7FoDIzMyGTyTB16lS11yZMmIDOnTvj119/NUBkxsvoEl5MTAzWrFmjci/vwIED4PF46NGjh4GjI82RXC7H22+/jZSUFGzdurXxxwq1cFeuXIFMJjP6h1b8/f3x448/qtTdunULS5YswUcffYTg4GADRdY87du3D3w+HwEBAY12DKNLeGPHjsWWLVswffp0xMXFITs7G/Hx8Rg7dqzRf5BJJBIcP34cQMXlmOLiYhw4cAAAEBkZqfHxfGPw0Ucf4ejRo5g3bx6Ki4tx+fJl7rWAgACYmpoaLjgDmzFjBoKCgiASiWBubo7bt29jw4YNEIlEiI2NNXR4BmVra4uoqCiNrwUGBiIwMLCJI2o+Jk+ejKioKIhEIgDAkSNH8Ouvv2LChAlwdnZutOMyLGt802kkJydj8eLFuHTpEqysrDB8+HDMnj3bqD+4gIpLMP3799f42o8//qj1l7e169evH7KysjS+duTIEaM+k/n++++xb98+pKeng2VZuLu7Y8CAAZg8eTI9lajBuXPnMGHCBPz+++9GfYb3ySef4OTJk3j06BGUSiW8vLwwZswYjB8/HgzDNNpxjTLhEUIIMT70mBkhhBCjQAmPEEKIUaCERwghxChQwiOEEGIUKOERQggxCpTwCCGEGAVKeIQQQowCJTxCCCFGgRIeaZESEhIgEomQmZnZYPtcuXIlN9VRUzLUcVsSpVKJoUOH4rvvvjN0KACA/Px8hIaGclPxkZaBEh5pEHfv3sU777yDXr16ISgoCD179sTcuXNx9+7deu13zZo1OHz4cANFaTgSiQQrV67EuXPnDB2KXu7du4eVK1c26BeLukhMTMTDhw8xbtw4rq6kpAQrVqzA5MmTERkZCZFIhISEhHodp/KLlKY/OTk5XDsHBweMHj0a33zzTb2OR5oWJTxSbwcPHsTIkSNx9uxZjBo1Ch9++CFGjx6Nc+fOYeTIkfVaF23t2rUaE97w4cNx9epVuLu71yd0FW+88QauXr3aYPurTiKRYNWqVTh//nyTHre+7t27h1WrVmmdS7SpbNiwAUOGDFFZlik/Px/ffvstUlJSGvwM+a233kJ8fLzKn8rVVSq99NJLuHHjBs6cOdOgxyaNx+hWSyANKz09He+++y7at2+PrVu3qqyoMGHCBLzyyit49913sXv3brRv377Bjsvn8xt8NW2BQACBoOl/JQx13Jbi5s2buH37NubNm6dS7+Ligr///hvOzs64du0aRo8e3WDHjImJqXVyZx8fHwiFQuzcuRPR0dENdmzSeOgMj9TL+vXrIZFIsHjxYrXlgxwdHfHxxx+jtLQU69at4+or71klJydj1qxZCAsLQ1RUFD755BOUl5dz7UQiEUpLS7Fz507uslLlh56me3j9+vVDXFwczp07h1GjRiEkJATDhg3jLiMePHgQw4YNQ3BwMEaNGoWbN2+qxPv0vbR58+Zpvby1cuVKAIBUKsU333yDUaNGITw8HKGhoXj55Zdx9uxZbj+ZmZncB+KqVavU9qHpHp5cLse3336L2NhYBAUFoV+/fvjyyy8hlUpV2lW+5wsXLmD06NEIDg5G//79sWvXLh3+94C9e/di1KhR6NKlC8LCwjBs2DBs3ryZ6+NZs2YBqPjyUhl39cuyx48fx8svv4zQ0FB06dIFU6dOVbuMPW/ePHTp0gUZGRmYPHkyQkND0bNnT6xatQq6zF1/+PBhmJiYICIiQqXe1NRUr6VkdIm1uuLiYigUihr32b17dxw9elSn90EMjxIeqZejR4/C3d1d7cOoUteuXeHu7q7x5v7bb7+N8vJyzJ07FzExMdiyZQv+97//ca/Hx8fD1NQUERER3GWlF198scZ40tLSMHfuXPTr1w9z5sxBYWEhpk2bht27d2PJkiUYNmwYZs6cifT0dLz99ttQKpVa9/Xiiy+qXdYaNmwYAHDJvbi4GL/99hsiIyPxzjvvYMaMGXjy5AmmTJmCW7ducW0XLVoEABgwYAC3rwEDBmg99oIFC7BixQoEBARg/vz56Nq1K9auXYvZs2drfM+zZs1Cjx49MG/ePNjZ2WHevHm13j89deoU5syZA1tbW7zzzjuYO3cuIiMjcfHiRQAV/3fjx48HAEybNo2L28fHBwCwa9cuxMXFwdLSEu+88w7efPNN3Lt3Dy+//LLaPT+FQoEpU6bAyckJ//d//4egoCCsXLkSK1asqDFGALh06RKEQiFMTExqbauNPrECFQk+PDwcnTt3xrRp05Camqpxv4GBgSgqKqr3vWrSRFhC6qioqIgVCoXsG2+8UWO7adOmsUKhkBWLxSzLsuyKFStYoVDITps2TaXdokWLWKFQyN66dYurCw0NZd977z21fe7YsYMVCoVsRkYGV9e3b19WKBSyFy9e5OpOnjzJCoVCNiQkhM3KyuLqt2/fzgqFQvbs2bNcXWVc2qSmprLh4eHsq6++ysrlcpZlWVYul7Pl5eUq7QoLC9nu3buz8+fP5+ry8vJYoVDIrlixQm2/Tx/31q1brFAoZD/44AOVdkuXLmWFQiF75swZtff8zz//qBwrKCiIXbp0qdb3wrIs+8knn7BhYWHce9Fk//79av3EsixbXFzMRkREsAsWLFCpz8nJYcPDw1Xq33vvPVYoFLKLFy/m6pRKJTt16lQ2MDCQzcvLqzHOmJgYdubMmTW2uXr1KisUCtkdO3aovaZPrHv37mXnzZvH7ty5kz106BD71VdfsZ07d2ajoqLYBw8eqO374sWLrFAoZPfu3VtjfKR5oDM8UmclJSUAACsrqxrbVb5e2b7SK6+8olKufALvxIkTdY7J19cXXbp04cqdO3cGAHTr1g1ubm5q9RkZGTrtt7S0FDNmzICtrS2WL1/O3T/k8/ncwsFKpRIFBQWQy+UICgpSu2Sqq8qz4VdffVWl/rXXXlN5vZKvr6/KGbajoyM6duxY63uztbWFRCLBqVOn9I7x9OnTKCoqwpAhQ/DkyRPuD4/HQ+fOnTU+jVr9/5thGLzyyiuQyWS1PvRRUFCg9sBIY8U6ePBgLFmyBCNGjEBsbCzefvttrF+/HgUFBRqHRFTGlZ+fX+f4SNOhO+WkzrQlsqdpS4wdOnRQKXt6eoLH49XrEfh27dqplCuf6nN1dVWpr1yNu6ioSKf9/u9//0N6ejq2b98OBwcHldd27tyJjRs34v79+5DJZFx9XVdCz8rKAo/Hg6enp0q9s7MzbG1t1Z6YfPo9A4CdnR0KCwtrPM7LL7+M/fv34/XXX0fbtm3Ro0cPDBo0CDExMbXGWHmJb+LEiRpff3q1cx6Pp/bQUseOHQFApydA2XrcI9M31qdFRESgc+fONSbmxlylmzQcSnikzmxsbODs7IykpKQa2yUlJaFt27a1frA0xIeGtic3tdXr8kG6efNmJCYmYtmyZfD391d57Y8//sC8efMQGxuLyZMnw8nJCXw+H2vXrtX57FEbXfujrk+rOjk5YdeuXfj7779x4sQJnDhxAgkJCRgxYgQ+//zzGret7Lf4+HiND4405BO09vb2On8x0aQhYnV1dcX9+/fV6iu/VDz9JYg0T5TwSL307dsXv/76Ky5cuKDxwZULFy4gKytL48MmaWlpKt/609LSoFQq63xm1BguXLiA+Ph4TJw4Ec8995za63/++Sfat2+PVatWqSSopx/G0CeZu7u7Q6lUIi0tjXtABAByc3NRVFTUoGMPTU1N0a9fP/Tr1w9KpRKLFi3CL7/8gjfffBMdOnTQGnfl/5uTkxO6d+9e63GUSiUyMjK4szoAXAKp7f14e3vX66xf31g1ycjI0JjUKuOq/v9Emi+6h0fqZfLkyTA3N8eHH36odh+joKAAH374ISwsLDBlyhS1bbdu3apS/umnnwBA5ZKapaVlvb7d18fjx4/x9ttvIywsDO+++67GNpVnB9XPFK9cuYLLly+rtLOwsACg2yXU3r17AwA3PKDSDz/8oPJ6fT39/8Xj8bjhEZXDHyrjFovFKm179eoFa2trrF27VuUybqUnT56o1VX//2ZZFlu3boWJiUmtY9hCQ0Nx9+5dtSEZutInVk1xHz9+HDdu3ECvXr3UXrtx4wZsbGzQqVOnOsVGmhad4ZF68fLywtKlS/F///d/GDZsGEaPHg0PDw9kZWXh999/R35+Pr788ku1+1FAxbfjadOmoVevXrh8+TJ2796NoUOHws/Pj2sTGBiIM2fO4IcffoCLiws8PDy4B04a2yeffMINMdi7d6/KayKRCH5+fujTpw8OHjyI6dOno0+fPsjMzMT27dvh6+uL0tJSrr25uTl8fX2xf/9+eHl5wd7eHp06dYJQKFQ7rp+fH0aOHIlffvkFRUVF6Nq1K65du4adO3ciNjYW3bp1a5D3t2DBAhQWFqJbt25o27YtHjx4gJ9++gn+/v7cGYu/vz/4fD7WrVsHsVgMU1NTdOvWDU5OTli0aBHeffddjBo1CoMHD4ajoyMePHiA48ePIywsDAsXLuSOZWZmhpMnT+K9995DSEgITp48iWPHjmHatGlq4zef1r9/f6xevRrnz59Hz549VV776aefUFRUhMePHwOoGCbz6NEjAMD48eNhY2MDa2trnWMdO3Ys/P39ERQUBBsbG9y8eRM7duxAu3btMG3aNLXYTp8+jb59+9I9vBaCEh6pt0GDBsHb2xvff/89fv/9dxQUFMDe3h5RUVGIi4vT+KEOAF9//TW++eYbLF++HAKBAOPGjVM7k5o3bx4WLlyIr7/+GmVlZRg5cmSTJbz8/HwoFAosWbJE7bUZM2bAz88Po0aNQm5uLn755Rf8/fff8PX1xbJly3DgwAG1acQ++eQTLF68GEuWLIFMJsOMGTO09s0nn3wCDw8P7Ny5E4cPH0abNm0QFxeHGTNmNNj7e+655/Drr7/i559/RlFREZydnTFo0CDMnDkTPF7FxR9nZ2d89NFHWLt2LT744AMoFAr8+OOPcHJywrBhw+Di4oLvv/8eGzZsgFQqRdu2bREREYFRo0apHIvP52P9+vVYtGgRli1bBisrK8yYMQPTp0+vNc6goCCIRCLs379fLeFt3LhR5aGXgwcP4uDBg9z7q3xoSddYBw0ahOPHj+PUqVMoKyuDs7MzxowZgxkzZqBNmzYqx05OTsadO3fw/vvv69HrxJAYtj6PPxFSBytXrsSqVatw5syZWr/dk5Zv3rx5+PPPP3Hp0qU672PXrl34+OOPcezYsXoNUWhIn376KS5cuICEhAQ6w2sh6B4eIaTZe+655+Dm5qZ239dQ8vPz8fvvv+Ptt9+mZNeC0CVNQkizx+PxkJiYaOgwOA4ODvU6YyWGQWd4hBBCjALdwyOEEGIU6AyPEEKIUaCERwghxChQwiOEEGIUKOERQggxCpTwCCGEGAVKeIQQQowCJTxCCCFGgRIeIYQQo/D/Yp8U5LIytzkAAAAASUVORK5CYII=", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "sns.set(style=\"whitegrid\")\n", + "\n", + "plt.figure(figsize=(5,4))\n", + "ax = plt.subplot(111)\n", + "ax.spines[['right', 'top']].set_visible(False)\n", + "\n", + "layer = 5\n", + "\n", + "palette = sns.color_palette(\"husl\", 6)\n", + "\n", + "plt.plot(x[:-3], result_dict['val1_rank_pos2'+\"_\"+str(layer)][:-3], label='MRR($v_1$) at $S[5,e_1]$', color=palette[0], linewidth=2.5, zorder=2)\n", + "plt.plot(x[:-3], result_dict['val2_rank_pos4'+\"_\"+str(layer)][:-3], label='MRR($v_2$) at $S[5,e_2]$', color=palette[1], linewidth=2.5, zorder=2)\n", + "\n", + "plt.annotate('Grokking starts', xy=(0, 1), xytext=(-10, 20),\n", + " textcoords='offset points',\n", + " fontsize=12)\n", + "\n", + "plt.legend(loc='lower right', bbox_to_anchor=(1.0,0.03), fancybox=True, shadow=True, ncol=1, fontsize=12)\n", + "plt.xlabel(\"Optimization step (1e5)\")\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "CLM", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.13" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/README.md b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6409ddf166c238985e254a7caccbb0f0d6ecb852 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/README.md @@ -0,0 +1,77 @@ +# Multi-Hop Implicit Reasoning in Transformers + +## Overview + +This repository contains the code for reproducing the experiments in our paper **"How Does Transformer Learn Implicit Reasoning?"** . In this work, we explore how implicit multi-hop reasoning emerges during training in transformers. We also propose several novel techniques, such as *cross-query semantic patching* and a *cosine-based representational lens*, to analyze the behavior and internal representations of transformers during multi-hop reasoning. + +## Structure of the Repository + +- **notebooks/**: This folder contains all the Jupyter notebooks that are essential for replicating and understanding our experiments. The notebooks include the data preparation, new methods, and analysis steps. + - **cosine_metrics.ipynb**: Computes the cosine-based representational lens to analyze model behavior. + - **data_preparation.ipynb**: Code for constructing the datasets and preparing the data for training. + - **training_dynamics.ipynb**: Drawing the model's learning dynamics during training. + - **cross_query_semantic_patching.ipynb**: Implements the cross-query semantic patching technique to locate postion that encode Immediate entities. + - **logit_lens.ipynb**: Code for probing the intermediate states using the logit lens. + +- **README.md**: This file, which explains how to replicate the experiments and the structure of the repository. + +## Setup Instructions + +To replicate the experiments, follow these steps: + +### 1. Clone the previous work's repository + +Our work builds upon [GrokkedTransformer](https://github.com/OSU-NLP-Group/GrokkedTransformer). Please clone their repository and follow their instructions for setting up the environment and training the model. + +```bash +git clone https://github.com/OSU-NLP-Group/GrokkedTransformer.git +cd GrokkedTransformer +# Follow the setup instructions in their README +``` + +### 2. Data Preparation + +In the `notebooks/data_preparation.ipynb`, you will find the code to prepare the dataset used in our experiments. Run this notebook to generate the data necessary for the training process. + +### 3. Training and Experiment Reproduction + +After setting up the environment and preparing the data, use the training code provided by the previous work (GrokkedTransformer). The training code will be similar to what is explained in their README. + +> ⚠️ **Important Note on Data Path** +> The original GrokkedTransformer training scripts expect the dataset to be located in a `data/` folder relative to their repository root, i.e., `data//`. +> +> However, our `data_preparation.ipynb` script generates data in a `data/` folder located at the root of our project (at the same level as the `notebooks/` directory). +> +> **To avoid errors when training, you have two options:** +> +> 1. **Modify the training script:** +> In the GrokkedTransformer training script (e.g., `train.sh`), update the following line: +> +> ```bash +> DATASET=data/$1/ +> ``` +> to: +> ```bash +> DATASET=../data/$1/ # or the actual relative path to your generated data +> ``` +> +> 2. **Copy the generated data:** +> Alternatively, you can copy the generated data into their expected directory: +> +> ```bash +> cp -r data/ /data/ +> ``` + +Once the model is trained, you can use our methods in the `notebooks/` folder to analyze the trained model and replicate the results of our experiments. + +### 4. Experiment Analysis + +To analyze the results, use the following notebooks: +- **training_dynamics.ipynb**: This notebook draws the model's learning dynamics during training. +- **logit_lens.ipynb**: This notebook tries to understand the learning dynamics using a popular tool calls logit lens. +- **cosine_metrics.ipynb**: This notebook computes the cosine metrics for understanding the representational space of the model. +- **cross_query_semantic_patching.ipynb**: This notebook helps you locate the postion that encode Immediate entities using our cross-query semantic patching technique. + +## Contact Information + +For any questions or issues, please feel free to contact the authors. diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/cosine_metrics.ipynb b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/cosine_metrics.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..66b6e67224464433d2fbb06072e4d7ed94d643e4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/cosine_metrics.ipynb @@ -0,0 +1,198 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "8adc6d63", + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "id_e2_to_queries = {} # {\"\": [\"\", \"\", ...],...}\n", + "ood_e2_to_queries = {} # {\"\": [\"\", ...], ...}\n", + "\n", + "with open('../data/base_configuration.2000.200.7.2/train.json', 'r') as f:\n", + " data = json.load(f)\n", + "\n", + "# Split the atomic triples into ID and OOD by ID/OOD ratio\n", + "id_data = data[:38000] # 2000 * 20 * 0.95\n", + "ood_data = data[38000:40000] # 2000 * 20 * 0.05\n", + "\n", + "for data in id_data:\n", + " e1, r, e2 = data[\"target_text\"].strip('<>').split('><')[:-1]\n", + " if f\"<{e2}>\" not in id_e2_to_queries:\n", + " id_e2_to_queries[f\"<{e2}>\"] = []\n", + " id_e2_to_queries[f\"<{e2}>\"].append(f\"<{e1}><{r}>\")\n", + "\n", + "for data in ood_data:\n", + " e1, r, e2 = data[\"target_text\"].strip('<>').split('><')[:-1]\n", + " if f\"<{e2}>\" not in ood_e2_to_queries:\n", + " ood_e2_to_queries[f\"<{e2}>\"] = []\n", + " ood_e2_to_queries[f\"<{e2}>\"].append(f\"<{e1}><{r}>\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "22dec9fb", + "metadata": {}, + "outputs": [], + "source": [ + "from transformers import GPT2LMHeadModel\n", + "import torch\n", + "import torch.nn.functional as F\n", + "\n", + "def compute_similarity_metrics(model, tokenizer, target_layer, id_e2_to_queries, ood_e2_to_queries, device):\n", + " id_similarities = [] # ID Cohesion\n", + " ood_similarities = [] # OOD Alignment\n", + "\n", + " target_index = 1 # r1 position\n", + "\n", + " model.to(device)\n", + " model.eval()\n", + "\n", + " # ID-derived e2 in id_e2_to_queries.keys() probably not in ood_e2_to_queries.keys()\n", + " for e2 in ood_e2_to_queries.keys():\n", + "\n", + " id_queries = id_e2_to_queries.get(e2, [])\n", + " ood_queries = ood_e2_to_queries.get(e2, [])\n", + "\n", + " if len(id_queries) == 0 or len(ood_queries) == 0:\n", + " continue\n", + "\n", + " id_hiddens = []\n", + " for query in id_queries:\n", + " inputs = tokenizer([query], return_tensors=\"pt\", padding=True).to(device)\n", + " \n", + " with torch.no_grad():\n", + " outputs = model(**inputs, output_hidden_states=True)\n", + " hidden = outputs.hidden_states[target_layer][0, target_index, :]\n", + "\n", + " id_hiddens.append(hidden)\n", + "\n", + " id_hiddens = torch.stack(id_hiddens)\n", + " id_centroid = id_hiddens.mean(dim=0)\n", + "\n", + " id_cos_sims = F.cosine_similarity(id_hiddens, id_centroid.unsqueeze(0), dim=1)\n", + " id_avg_sim = id_cos_sims.mean().item()\n", + " id_similarities.append(id_avg_sim)\n", + "\n", + " ood_hiddens = []\n", + " for query in ood_queries:\n", + " inputs = tokenizer([query], return_tensors=\"pt\", padding=True).to(device)\n", + " with torch.no_grad():\n", + " outputs = model(**inputs, output_hidden_states=True)\n", + " hidden = outputs.hidden_states[target_layer][0, target_index, :]\n", + " ood_hiddens.append(hidden)\n", + "\n", + " ood_hiddens = torch.stack(ood_hiddens)\n", + " ood_cos_sims = F.cosine_similarity(ood_hiddens, id_centroid.unsqueeze(0), dim=1)\n", + " ood_avg_sim = ood_cos_sims.mean().item()\n", + " ood_similarities.append(ood_avg_sim)\n", + "\n", + " mean_id = sum(id_similarities) / len(id_similarities)\n", + " mean_ood = sum(ood_similarities) / len(ood_similarities)\n", + " return mean_id, mean_ood\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5b5b03e3", + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import re\n", + "\n", + "base_dir = \"/your/checkpoints/directory\" # replace with your directory\n", + "checkpoint_prefix = \"checkpoint-\"\n", + "\n", + "all_ckpts = [\n", + " os.path.join(base_dir, d) for d in os.listdir(base_dir)\n", + " if d.startswith(checkpoint_prefix) and os.path.isdir(os.path.join(base_dir, d))\n", + "]\n", + "\n", + "min_step_interval = 2000\n", + "start_step = 0 \n", + "\n", + "# extract step numbers from checkpoint paths\n", + "ckpt_tuples = []\n", + "for path in all_ckpts:\n", + " match = re.search(r\"checkpoint-(\\d+)\", path)\n", + " if match:\n", + " step = int(match.group(1))\n", + " if step >= start_step:\n", + " ckpt_tuples.append((step, path))\n", + "\n", + "ckpt_tuples.sort()\n", + "\n", + "# sample checkpoints based on the minimum step interval\n", + "selected_ckpts = []\n", + "last_step = -min_step_interval\n", + "for step, path in ckpt_tuples:\n", + " if step - last_step >= min_step_interval:\n", + " selected_ckpts.append((step, path))\n", + " last_step = step\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "44bc43e8", + "metadata": {}, + "outputs": [], + "source": [ + "from transformers import GPT2Tokenizer\n", + "from tqdm import tqdm\n", + "\n", + "device = \"cuda:0\"\n", + "\n", + "target_layer = 5 # determined by cross-query semantic patching\n", + "\n", + "# Load the tokenizer\n", + "tokenizer = GPT2Tokenizer.from_pretrained(selected_ckpts[0][1])\n", + "tokenizer.padding_side = \"left\"\n", + "tokenizer.pad_token = tokenizer.eos_token\n", + "tokenizer.pad_token_id = tokenizer.eos_token_id\n", + "\n", + "results = []\n", + "\n", + "for label, path in tqdm(selected_ckpts):\n", + " print(f\"Processing {label}...\")\n", + " model = GPT2LMHeadModel.from_pretrained(path).to(device)\n", + " id_sim, ood_sim = compute_similarity_metrics(\n", + " model, tokenizer, target_layer,\n", + " id_e2_to_queries, ood_e2_to_queries, device\n", + " )\n", + " results.append((label, (id_sim, ood_sim)))\n", + " del model\n", + " torch.cuda.empty_cache()\n", + "\n", + "print(results)\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "latent", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.19" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/cross_query_semantic_patching.ipynb b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/cross_query_semantic_patching.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5e2507dd20acd850ee124a6016a5d021b1c18e30 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/cross_query_semantic_patching.ipynb @@ -0,0 +1,214 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "bb0b801e", + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "import random\n", + "\n", + "queries = [] # [(source query, target query, expected_patching_result), ...]\n", + "\n", + "with open('../data/base_configuration.2000.200.7.2/train.json', 'r') as f:\n", + " data = json.load(f)\n", + "\n", + "# Split the atomic triples into ID and OOD by ID/OOD ratio\n", + "ID_triples = data[:38000] # 2000 * 20 * 0.95\n", + "\n", + "triple_dict = {}\n", + "legal_head = {} # {\"\": [\"\", \"\", ...], ...}\n", + "id_e2_dict = {} # {\"\": [\"\", \"\", ...], ...}\n", + "\n", + "for triple in ID_triples:\n", + " e1, r, e2 = triple[\"target_text\"].strip('<>').split('><')[:-1]\n", + "\n", + " triple_dict[f\"<{e1}><{r}>\"] = f\"<{e2}>\"\n", + " if f\"<{r}>\" not in legal_head:\n", + " legal_head[f\"<{r}>\"] = []\n", + " legal_head[f\"<{r}>\"].append(f\"<{e1}>\")\n", + " id_e2_dict[f\"<{e2}>\"] = triple[\"input_text\"] # cover\n", + "\n", + "with open('../data/base_configuration.2000.200.7.2/test.json', 'r') as f:\n", + " datas = json.load(f)\n", + " \n", + "for data in datas:\n", + " if data[\"type\"] == \"Train-II\" or data[\"type\"] == \"Test-II\":\n", + " e1, r1, r2 = data[\"target_text\"].strip('<>').split('><')[:3]\n", + " r2 = f\"<{r2}>\"\n", + " for e2 in legal_head[r2]:\n", + " if e2 in id_e2_dict:\n", + " expected_e3 = triple_dict[e2 + r2]\n", + " queries.append((id_e2_dict[e2], data[\"input_text\"], expected_e3))\n", + "\n", + "random.shuffle(queries)\n", + "queries = queries[:2000] \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9fcc60df", + "metadata": {}, + "outputs": [], + "source": [ + "from transformers import GPT2Config, GPT2LMHeadModel, GPT2Tokenizer\n", + "import torch\n", + "\n", + "model_path = \"your_model_path\" # Better to use a Phase II or Phase III checkpoint\n", + "\n", + "device = \"cuda:0\"\n", + "\n", + "tokenizer = GPT2Tokenizer.from_pretrained(model_path)\n", + "tokenizer.padding_side = \"left\"\n", + "tokenizer.pad_token = tokenizer.eos_token\n", + "tokenizer.pad_token_id = tokenizer.eos_token_id\n", + "\n", + "model = GPT2LMHeadModel.from_pretrained(model_path).to(device)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1ab5c3ff", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "from tqdm import tqdm\n", + "\n", + "success_counts = np.zeros((8, 3))\n", + "total_counts = np.zeros((8, 3))\n", + "\n", + "for position in tqdm(range(3)): # 0:e1, 1:r1, 2:r2\n", + " for layer in tqdm(range(1, 9)): # 0:embedding, 1-8:layer1-8\n", + "\n", + " for source_prompt, target_prompt, expected_e3 in tqdm(queries):\n", + "\n", + " # get the source hidden states\n", + " decoder_temp = tokenizer([source_prompt], return_tensors=\"pt\", padding=True)\n", + " decoder_input_ids, decoder_attention_mask = decoder_temp[\"input_ids\"], decoder_temp[\"attention_mask\"]\n", + " decoder_input_ids, decoder_attention_mask = decoder_input_ids.to(device), decoder_attention_mask.to(device)\n", + "\n", + " with torch.no_grad():\n", + " outputs1 = model(\n", + " input_ids=decoder_input_ids,\n", + " attention_mask=decoder_attention_mask,\n", + " output_hidden_states=True\n", + " )\n", + "\n", + " hidden_states_batch = outputs1.hidden_states # [1+num_layers, batch_size, seq_len, hidden_size]\n", + "\n", + " # replace the hidden states of the target position with the source hidden states\n", + " def hook_fn(module, input, output):\n", + " main_output = output[0].clone()\n", + " main_output[0, position, :] = hidden_states_batch[layer][0, position, :]\n", + " return (main_output,) + output[1:]\n", + "\n", + " handle = model.transformer.h[layer - 1].register_forward_hook(hook_fn)\n", + "\n", + " # target prompt\n", + " decoder_temp = tokenizer([target_prompt], return_tensors=\"pt\", padding=True)\n", + " decoder_input_ids, decoder_attention_mask = decoder_temp[\"input_ids\"], decoder_temp[\"attention_mask\"]\n", + " target_decoder_input_ids, target_decoder_attention_mask = decoder_input_ids.to(device), decoder_attention_mask.to(device)\n", + "\n", + " with torch.no_grad():\n", + " outputs2 = model(\n", + " input_ids=target_decoder_input_ids,\n", + " attention_mask=target_decoder_attention_mask,\n", + " # output_hidden_states=True\n", + " )\n", + "\n", + " handle.remove()\n", + "\n", + " # decode the predicted token\n", + " logits = outputs2.logits # [batch_size, seq_len, vocab_size]\n", + " predicted_token_ids = torch.argmax(logits, dim=-1) # [batch_size, seq_len]\n", + " decoded_text = tokenizer.batch_decode(predicted_token_ids, skip_special_tokens=True)\n", + " decoded_token = decoded_text[0].split()[-1] \n", + "\n", + " # check if the decoded token is the expected token\n", + " total_counts[layer-1, position] += 1\n", + " if decoded_token == expected_e3:\n", + " success_counts[layer-1, position] += 1\n", + "\n", + "success_rate = success_counts / total_counts" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "535031cb", + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZUAAAJOCAYAAAB/SppKAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuNSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/xnp5ZAAAACXBIWXMAAA9hAAAPYQGoP6dpAABggUlEQVR4nO3de1xUZf4H8M8wygAqoygYFIrIIqAZJYn365YZ5l3BuEi1XmoplhIKS7FNozTFtJ9piooObgGhrXlhJdHNS7iuZraIugZqKhGgjBcYLjO/P1hOjTOoMGfmwPB5+zqv32+e85x5npkWvnzPczkynU6nAxERkQhspO4AERFZDwYVIiISDYMKERGJhkGFiIhEw6BCRESiYVAhIiLRMKgQEZFoGFSIiEg0DCpERCQaBhUiIhINgwoREYmGQYWsUmVlpdRdaBb4PZClMai0UAcOHMCzzz6Ljh07wsnJCePGjcOFCxek7pYknnrqKQwaNAjffvsthg8fDnt7e0RHR0vdLYvj90DNgYy7FLc8mzdvxksvvYSnnnoK48aNw507d7B69Wq0adMGeXl5sLe3l7qLFtW1a1d07NgRJSUlmDVrFnr06AEvLy+MHj1a6q5ZFL8Hag4YVFqYH3/8Ef369cOCBQvwzjvvCOU//PADHnvsMXz55ZeYPHmyhD20rOLiYnTt2hXt27fHv/71L/j4+EjdJUnwe6Dmoo3UHaDG+etf/4pu3bphzpw5KCkpEcrd3NzQtm1b/PTTTxL2zvJ++OEHAMD8+fNb9S9Sfg/UXHBMpQXRaDTYtWsX/vvf/8LFxQXOzs56R3V1NTp06AAA+PTTT/HEE0+gbdu2WLRokbQdN6PTp08DAIKDg/XKW8vnr2fse9BoNHjxxRfRrVs3ODo6YsCAATh69KhUXaRWgplKC/LTTz/hzp07eO+99zBgwACjdR577DEAgKurKxYtWoRt27ZZsosW98MPP8DV1RWenp565a3l89cz9j3U1NTAw8MDhw4dwiOPPIK0tDQ899xzKCwsRPv27SXsLVkzBpUW5ObNmwAAX19f/PGPf7xn3YkTJwIAdu/ebe5uSap+LOlureXz1zP2PbRr1w4LFy4UXoeEhOD111/H2bNn0a9fP0t3kVoJ3v5qQTw8PCCTyfDll18anKupqcH169cl6JV0amtrkZeXZzSotCYP+j2cP38eZWVl8PLyslDPqDViptKCuLi4YMaMGdi2bRvUajXGjh2L2tpa/Pe//0VmZiY+//xzDBkyROpuWsz58+dRWVnZ6oPKg3wPFRUVCAsLQ3x8PJRKpQV7R60Ng0oLs3HjRvTp0wcqlQqxsbFwcHCAp6cn/vSnP+GJJ56QunsWVT843bdvX4l7Iq37fQ/V1dWYNm0avLy89G6HEZkDg0oLo1AoEB8fj/j4eKm7Irlp06aBy6zu/T1otVqEh4dDJpMhJSUFMpnMwr2j1oZBxUrV1NSgpqYGtbW1qKmpQWVlJdq2bQu5XC511yyitX/+enPmzMG1a9eQlZWFNm34404WoCOrlJCQoAOgd2zatEnqbllMa//8Op1OV1hYqAOgs7Oz07Vr1044/vnPf0rdNbJi3KaFiIhEwynFREQkGgYVIiISDYMKERGJhkGFiIhEw6BCRESiYVAhIrKAW7duISEhAc888wycnJwgk8mwefPmB77+xo0bmD17NpydndGuXTuMHDkSJ06cMF+Hm4hBxUpoNBosWrQIGo1G6q5Ijt9FHX4PzUtJSQn++te/4syZM43er06r1SIoKAjbtm1DVFQUli5diuLiYowYMQLnz583U4+bhutUrIRarYZSqUR5eTkcHR2l7o6k+F3U4ffQvGg0Gly/fh0PPfQQjh8/jieffBKbNm1CZGTkfa9NS0tDcHAw0tPTMXXqVADAr7/+Cm9vb4wdO7ZZPTeImQoRkQUoFAo89NBDTbo2IyMDXbt2xeTJk4UyZ2dnTJ8+HV999VWzykYZVIiImrmTJ0/iiSeegI2N/q/s/v37486dOzh37pxEPTPEHeZEoNVqcfXqVXTo0EGyXWDVarXe/23N+F3UaQ7fg06nw82bN+Hm5mbwC9FcKisrUVVVZZG2dDqdwc+8QqGAQqEQtZ1r165h2LBhBuWurq4AgKtXr+LRRx8Vtc2mYlARwdWrV+Hu7i51NwCg2fSjOeB3Uac5fA+XL1/GI488YvZ2KisrYa9sB1Rpzd4WALRv3x63bt3SK0tISMCiRYtEbaeiosJooLKzsxPONxcMKiLo0KEDAOBswRl0cOwgcW+ktffSLqm70GwEdR8vdRckd1N9E14e3sLPiLlVVVXVBZQhDwFtzHzXoEaHW4eKcPnyZb2JEGJnKQBgb29vdNyksrJSON9cMKiIoD797eDYodXPsnHo0Hz+xy211v6/hd+z+G3htjZAGzPfbpPVZUOOjo5m/2/t6uqKa9euGZTXl7m5uZm1/cbgQD0RUTPn7++PEydOQKvVv62Xm5sLBwcHeHt7S9QzQwwqRGR9bCx0mMG1a9eQn5+P6upqoWzq1Kn45ZdfkJmZKZSVlJQgPT0dzz33nFluuTUVb38REVnIJ598ghs3buDq1asAgJ07d+Lnn38GALz66qtQKpWIj49HSkoKCgoK4OHhAaAuqAwYMAAvvPAC8vLy0KVLF6xZswa1tbV49913pfo4RjGoEJH1kcnqDnO30UgfffQRLl68KLzOzMwUso+wsDAolUqj18nlcuzevRuxsbFYtWoVKioq8OSTT2Lz5s3o1atX0/pvJtymRQT122FcLf251Q/Ofn1xh9RdaDYmeEyRuguSU6vV6OrkarGtYup/FvHHh80/UF+jBbKvcBucuzBTISLrJM065FaPA/VERCQaZipEZH2a6ZhKa8BMhYiIRMNMhYisjxnXkei1QQb4tRARkWiYqRCR9eGYimSYqRARkWiYqRCR9ZHB/OtUmKgYxUyFiIhEw0yFiKyPjazuMHcbZICZChERiYaZChFZH46pSIaZChERiYZBhYiIRMPbX0Rkfbj4UTLMVIiISDTMVIjI+nCgXjLMVIiISDSNCiqbN2+GTCbD8ePHzdUfizp27BheeeUV9OvXD23btoWM90iJrEP94kdzH2SgVWcqu3fvxoYNGyCTyeDp6Sl1d4iIWjyrDiparRaVlZUNnn/55ZdRXl6O48eP46mnnrJgz4jIrGQWOsiA6EGlqqoKCxcuRL9+/aBUKtGuXTsMHToUOTk5Qh2dTgcPDw9MmDDB4PrKykoolUrMmTNHKNNoNEhISICXlxcUCgXc3d0RFxcHjUajd61MJkNUVBRSU1PRu3dvKBQK7N27t8G+du3aFfb29iJ8aiIiAsww+0utVmPDhg2YMWMGZs2ahZs3byI5ORljxozBsWPH4O/vD5lMhrCwMCxduhRlZWVwcnISrt+5cyfUajXCwsIA1GUb48ePx6FDhzB79mz4+vri9OnTSEpKwrlz57Bjxw699vfv34+0tDRERUWhS5cu8PDwEPsjElFzx3UqkhE9qHTq1AmFhYWwtbUVymbNmgUfHx+sXr0aycnJAICIiAgsWbIEaWlpmDt3rlBXpVLBw8MDQ4YMAQBs27YN2dnZOHjwoFAGAH369MHcuXNx5MgRDBo0SCg/e/YsTp8+DT8/P7E/mkCj0ehlSWq12mxtERG1JKLf/pLL5UJA0Wq1KCsrQ01NDQICAnDixAmhnre3NwIDA5GamiqUlZWVYc+ePQgNDRVmYqWnp8PX1xc+Pj4oKSkRjlGjRgGA3m01ABg+fLhZAwoAJCYmQqlUCoe7u7tZ2yOiRuLsL8mYZaA+JSUFffv2hZ2dHTp37gxnZ2fs2rUL5eXlevUiIiJw+PBhXLx4EUBdAKmurkZ4eLhQ5/z58/jPf/4DZ2dnvcPb2xsAUFxcrPeePXr0MMdH0hMfH4/y8nLhuHz5stnbJCJqCUS//aVSqRAZGYmJEyciNjYWLi4ukMvlSExMxIULF/TqhoSEICYmBqmpqZg/fz5UKhUCAgLQq1cvoY5Wq8Wjjz6KFStWGG3v7izBEgPvCoUCCoXC7O0QURNxRb1kRA8qGRkZ8PT0RGZmpt5iwoSEBIO6Tk5OCAoKQmpqKkJDQ3H48GGsXLlSr07Pnj1x6tQpjB49mosTiYiaObOMqQB104br5ebm4ujRo0brh4eHIy8vD7GxsZDL5QgJCdE7P336dFy5cgXr1683uLaiogK3b98WsfdEZBVk+G0GmNkOqT9k89SkTGXjxo1G139ER0dj3LhxyMzMxKRJkxAUFISCggKsXbsWfn5+uHXrlsE1QUFB6Ny5M9LT0zF27Fi4uLjonQ8PDxdmiOXk5GDw4MGora1Ffn4+0tLSkJWVhYCAgKZ8DFy8eBFbt24FAGHrmcWLFwMAunfvrje2Q0RE99ekoPLpp58aLY+MjERkZCSKioqwbt06ZGVlwc/PDyqVCunp6Thw4IDBNba2tggODsaaNWuM/hK3sbHBjh07kJSUhC1btmD79u1wcHCAp6cnoqOjhQH7pigoKMCCBQv0yupfDx8+nEGFqCVjJiEJme7396kkEhMTg+TkZBQVFcHBwUHq7jSaWq2GUqnE1dKf4ejoKHV3JPX1xR1Sd6HZmOAxReouSE6tVqOrkyvKy8st8rNR/7OI6Z6Ardy8jVXVAmk/WeyztRSSP0+lsrISKpUKU6ZMaZEBhYiaIUusI+E6FaMkCyrFxcXIzs5GRkYGSktLER0dLVVXiIhIJJIFlby8PISGhsLFxQWrVq2Cv7+/VF0hImvDdSqSkSyojBgxAs1gOIeIiEQk+ZgKEZHouEuxZKz6IV1ERGRZzFSIyPrYwPx/MvNPcqP4tRARkWgYVIiISDS8/UVE1ocD9ZJhpkJERKJhpkJE1oeLHyXDTIWIiETDTIWIrA/HVCTDTIWIiETDTIWIrA8XP0qGXwsREYmGmQoRWR+OqUiGmQoREYmGmQoRWR+uU5EMMxUiIhINMxUisj42srrD3G2QAWYqREQkGmYqRGR9OPtLMgwqIrL537/WLOSV+VJ3odmo2D1F6i4QWRyDChFZH87+kkzr/rOaiIhExUyFiKyQDDIzj3nomKoYxUyFiIhEw0yFiKyOTGb+TAUyGXTmbaFFYqZCRESiYaZCRFbHEstUIAMzFSOYqRARkWiYqRCR1bGxwJiKTiaD1qwttEzMVIiISDQMKkREJBre/iIiq2OpKcVkiJkKERGJhpkKEVkdZirSYaZCRESiYaZCRFaHmYp0mKkQEZFomKkQkdWx1DYtZIiZChERiYaZChFZHY6pSIeZChERiYaZChFZHWYq0mGmQkREomGmQkRWR/a/f+ZuhQwxUyEiItEwUyEiq8MxFekwUyEiItE0Kqhs3rwZMpkMx48fN1d/LEar1WLz5s0YP3483N3d0a5dO/Tp0weLFy9GZWWl1N0jIhPUr6g390GGWm2mcufOHbzwwgv49ddfMXfuXKxcuRL9+/dHQkICxo4dC51OJ3UXiYhaHKseU9FqtaiqqoKdnZ3BOVtbWxw+fBiDBg0SymbNmgUPDw8kJCTgm2++wR//+EdLdpeIRGIjg9nHVHTMVIwSPVOpqqrCwoUL0a9fPyiVSrRr1w5Dhw5FTk6OUEen08HDwwMTJkwwuL6yshJKpRJz5swRyjQaDRISEuDl5QWFQgF3d3fExcVBo9HoXSuTyRAVFYXU1FT07t0bCoUCe/fuNdpPW1tbvYBSb9KkSQCAM2fONOnzExG1ZqJnKmq1Ghs2bMCMGTMwa9Ys3Lx5E8nJyRgzZgyOHTsGf39/yGQyhIWFYenSpSgrK4OTk5Nw/c6dO6FWqxEWFgagLtsYP348Dh06hNmzZ8PX1xenT59GUlISzp07hx07dui1v3//fqSlpSEqKgpdunSBh4dHo/pfVFQEAOjSpYtJ3wMRSYezv6QjelDp1KkTCgsLYWtrK5TNmjULPj4+WL16NZKTkwEAERERWLJkCdLS0jB37lyhrkqlgoeHB4YMGQIA2LZtG7Kzs3Hw4EGhDAD69OmDuXPn4siRI3oZx9mzZ3H69Gn4+fk1qf9Lly6Fo6Mjxo4d22AdjUajlyWp1eomtUVEZG1Ev/0ll8uFgKLValFWVoaamhoEBATgxIkTQj1vb28EBgYiNTVVKCsrK8OePXsQGhoq/JWRnp4OX19f+Pj4oKSkRDhGjRoFAHq31QBg+PDhTQ4o77//PrKzs/HBBx+gY8eODdZLTEyEUqkUDnd39ya1R0TmUZ+pmPsgQ2aZ/ZWSkoK+ffvCzs4OnTt3hrOzM3bt2oXy8nK9ehERETh8+DAuXrwIoC6AVFdXIzw8XKhz/vx5/Oc//4Gzs7Pe4e3tDQAoLi7We88ePXo0qc9ffPEF3nnnHbz00kt4+eWX71k3Pj4e5eXlwnH58uUmtUlErYdGo8Gbb74JNzc32NvbIzAwEPv27Xuga7OzszFy5Eh06dIFHTt2RP/+/bF161Yz97hpRL/9pVKpEBkZiYkTJyI2NhYuLi6Qy+VITEzEhQsX9OqGhIQgJiYGqampmD9/PlQqFQICAtCrVy+hjlarxaOPPooVK1YYbe/uLMHe3r7Rfd63bx8iIiIQFBSEtWvX3re+QqGAQqFodDtEZCEWWEfS2NlfkZGRyMjIwF/+8hf84Q9/wObNm/Hss88iJydH79b+3f7+979j4sSJGDhwIBYtWgSZTIa0tDRERESgpKQEMTExJn4ScYkeVDIyMuDp6YnMzEy99DAhIcGgrpOTE4KCgpCamorQ0FAcPnwYK1eu1KvTs2dPnDp1CqNHjzZLupmbm4tJkyYhICAAaWlpaNPGqmdZE5EEjh07hs8//xzLli3DvHnzANTdqenTpw/i4uJw5MiRBq/95JNP4Orqiv379wt/zM6ZMwc+Pj7YvHlzswsqZhlTAaC3eDA3NxdHjx41Wj88PBx5eXmIjY2FXC5HSEiI3vnp06fjypUrWL9+vcG1FRUVuH37dpP7eubMGQQFBcHDwwNff/11k7IcImp+mtuYSkZGBuRyOWbPni2U2dnZ4aWXXsLRo0fveQtdrVajU6dOendH2rRpgy5dujTL31lN+rN848aNRtd/REdHY9y4ccjMzMSkSZMQFBSEgoICrF27Fn5+frh165bBNUFBQejcuTPS09MxduxYuLi46J0PDw8XZojl5ORg8ODBqK2tRX5+PtLS0pCVlYWAgIBGf4abN29izJgxuH79OmJjY7Fr1y698z179sTAgQMb/b5ERHc7efIkvL294ejoqFfev39/AMD333/f4ISfESNG4MMPP8SCBQswc+ZMyGQybNu2DcePH0daWprZ+95YTQoqn376qdHyyMhIREZGoqioCOvWrUNWVhb8/PygUqmQnp6OAwcOGFxja2uL4OBgrFmzRm+Avp6NjQ127NiBpKQkbNmyBdu3b4eDgwM8PT0RHR0tDNg3VmlpqfDXwVtvvWVwfubMmQwqRHRfdy8pMDbmeu3aNbi6uhpcW1929erVBt9/wYIFKCgowJIlS7B48WIAgIODA7788kujC8il1qigUh807ic+Ph7x8fF6ZUFBQQ3Wt7W1RYcOHRr8gtq2bYu4uDjExcXds93G7Nfl4eHB/b2IrJQlpvzWv//dGUZCQgIWLVqkV1ZRUWF0ck/9FlIVFRUNtqNQKODt7Y2pU6di8uTJqK2txWeffYawsDDs27cPAwYMMPGTiEvyUenKykqoVCpMmTIFDg4OUneHiKhRLl++rHdby1jwsLe3N9hWCoCwI/q9xkaioqLw3Xff4cSJE7CxqRsGnz59Onr37o3o6Gjk5uaa+hFEJdkuxcXFxdi2bRuef/55lJaWIjo6WqquEJGVkcECA/X/e5ywo6Oj3mEsqLi6uuLatWsG5fVlbm5uRj9HVVUVkpOTERQUJAQUoO7uzdixY3H8+HFUVVWJ8ZWJRrKgkpeXJ0wjXrVqFfz9/aXqChGRWfn7++PcuXMG4y/1WUZDv/9KS0tRU1OD2tpag3PV1dXQarVGz0lJsqAyYsQI6HQ6/PLLL4iKipKqG0RkhZrblOKpU6cKYyH1NBoNNm3ahMDAQGFc5tKlS8jPzxfquLi4oGPHjti+fbteRnLr1i3s3LkTPj4+zW5aseRjKkRE1i4wMBDTpk1DfHw8iouL4eXlhZSUFBQWFgqb7AJ1CyIPHjwoTCKSy+WYN28e3nnnHQwYMAARERGora1FcnIyfv75Z6hUKqk+UoMYVIjI6ljicb+Nff8tW7ZgwYIF2Lp1K65fv46+ffvi66+/xrBhw+553dtvv40ePXrg448/xrvvvguNRoO+ffsiIyMDU6ZMMeETmIdMx3m1JlOr1VAqlSgqvWqwuKm1cQjykboLzUbF7rNSd0FyarUaXZ1cUV5ebpGfjfqfRZf5A2FjZ96/mbWVNSh+/6jFPltLwUyFiKyOJdepkD7JBuqJiMj6MFMhIqvDTEU6zFSIiEg0zFSIyOrYyGSwaW7Tv1oJZipERCQaZipEZHWa4zqV1oKZChERiYaZChFZHc7+kg4zFSIiEg0zFSKyOjL89rwTc7ZBhpipEBGRaJipEJHV4ZiKdJipEBGRaJipEJHVYaYiHWYqREQkGmYqRGR1uKJeOsxUiIhINMxUSFx8OjVRq8agQkRWhwP10uHtLyIiEg0zFSKyOsxUpMNMhYiIRMNMhYisjwUyFc4pNo6ZChERiYaZChFZHS5+lA4zFSIiEg0zFSKyOpz9JR1mKkREJBpmKkRkderGVMydqZj17VssZipERCQaZipEZHU4piIdZipERCQaZipEZHVksMA6FfO+fYvFTIWIiETDTIWIrA7HVKTDTIWIiETDTIWIrA4zFekwUyEiItEwUyEiq8NMRTrMVIiISDTMVIjI6vB5KtJhpkJERKJhpkJEVodjKtJhpkJERKJhUCEiItE0Kqhs3rwZMpkMx48fN1d/LGr9+vUYPnw4unbtCoVCgR49euCFF15AYWGh1F0jIlPUj9Sb+yADrXpM5eTJk+jRowfGjx+PTp06oaCgAOvXr8fXX3+NU6dOwc3NTeouEhG1KFYdVLRaLaqqqmBnZ2f0/Jo1awzKJk6ciICAAGzZsgVvvfWWubtIRGbAgXrpiD6mUlVVhYULF6Jfv35QKpVo164dhg4dipycHKGOTqeDh4cHJkyYYHB9ZWUllEol5syZI5RpNBokJCTAy8sLCoUC7u7uiIuLg0aj0btWJpMhKioKqamp6N27NxQKBfbu3duo/nt4eAAAbty40ajriIjIDJmKWq3Ghg0bMGPGDMyaNQs3b95EcnIyxowZg2PHjsHf3x8ymQxhYWFYunQpysrK4OTkJFy/c+dOqNVqhIWFAajLNsaPH49Dhw5h9uzZ8PX1xenTp5GUlIRz585hx44deu3v378faWlpiIqKQpcuXYQgcS+lpaWora3FpUuX8Ne//hUAMHr0aNG+EyKyLC5+lI7oQaVTp04oLCyEra2tUDZr1iz4+Phg9erVSE5OBgBERERgyZIlSEtLw9y5c4W6KpUKHh4eGDJkCABg27ZtyM7OxsGDB4UyAOjTpw/mzp2LI0eOYNCgQUL52bNncfr0afj5+T1wnx9++GEh6+ncuTNWrVqFp556qsH6Go1GL0tSq9UP3BYRkTUT/faXXC4XAopWq0VZWRlqamoQEBCAEydOCPW8vb0RGBiI1NRUoaysrAx79uxBaGiocL8yPT0dvr6+8PHxQUlJiXCMGjUKAPRuqwHA8OHDGxVQAGDPnj3YvXs3li9fjm7duuH27dv3rJ+YmAilUikc7u7ujWqPiMyrfkzF3AcZMstAfUpKCpYvX478/HxUV1cL5T169NCrFxERgaioKFy8eBHdu3dHeno6qqurER4eLtQ5f/48zpw5A2dnZ6NtFRcX672+u40HMXLkSADA2LFjMWHCBPTp0wft27dHVFSU0frx8fF4/fXXhddqtZqBhYgIZggqKpUKkZGRmDhxImJjY+Hi4gK5XI7ExERcuHBBr25ISAhiYmKQmpqK+fPnQ6VSISAgAL169RLqaLVaPProo1ixYoXR9u7+ZW5vb29S/3v27InHH38cqampDQYVhUIBhUJhUjtEZD6c/SUd0YNKRkYGPD09kZmZqfelJyQkGNR1cnJCUFAQUlNTERoaisOHD2PlypV6dXr27IlTp05h9OjRFvuPWFFRYTCzjIiI7s8sYypA3bTherm5uTh69KjR+uHh4cjLy0NsbCzkcjlCQkL0zk+fPh1XrlzB+vXrDa6tqKi47/hHQ2pqanD9+nWD8mPHjuH06dMICAho0vsSkfQ4piKdJmUqGzduNLr+Izo6GuPGjUNmZiYmTZqEoKAgFBQUYO3atfDz88OtW7cMrgkKCkLnzp2Rnp6OsWPHwsXFRe98eHi4MEMsJycHgwcPRm1tLfLz85GWloasrKwmBYBbt27B3d0dwcHB6N27N9q1a4fTp09j06ZNUCqVWLBgQaPfk4iotWtSUPn000+NlkdGRiIyMhJFRUVYt24dsrKy4OfnB5VKhfT0dBw4cMDgGltbWwQHB2PNmjV6A/T1bGxssGPHDiQlJWHLli3Yvn07HBwc4OnpiejoaHh7ezflI8DBwQF/+tOfkJOTg4yMDFRUVMDNzQ0zZszAO++880DrW4ioeeI6FenIdL+/TyWRmJgYJCcno6ioCA4ODlJ3p9HUajWUSiWKSq/C0dFR6u5IyuHZXvev1EpU7DkndRckp1ar0dXJFeXl5Rb52aj/WXzi/8ZDbt/WrG3VVlTjxJ//brHP1lJIvvV9ZWUlVCoVpkyZ0iIDChE1PxxTadilS5cwd+5c9OrVC05OTvjnP/8JACgpKcFrr72GkydPmvT+km0oWVxcjOzsbGRkZKC0tBTR0dFSdYWIqFXIy8vD0KFDodVqERgYiP/+97+oqakBAHTp0gWHDh3C7du3hZ1PmkKyoJKXl4fQ0FC4uLhg1apV8Pf3l6orRGRtLJFJtMBMJS4uDh07dsR3330HmUxmMDEqKCgIX3zxhUltSBZURowYgWYwnENE1Gr885//xMKFC+Hs7IzS0lKD8926dcOVK1dMasOqn6dCRK0TV9Qbp9Vq7zl2/euvv5q8W4jkA/VERGQZTzzxBHbt2mX0XE1NDT7//HMMGDDApDYYVIjI6nD2l3Hx8fHYu3cvXn75Zfz4448AgF9++QXZ2dl4+umncebMGZOfeMvbX0RErcTYsWOxefNmREdH47PPPgMAhIWFQafTwdHREVu2bMGwYcNMaoNBhYisDlfUNyw8PByTJ0/Gvn37cP78eWi1WvTs2RNjxoxBhw4dTH5/BhUiolbin//8J3x9feHs7IyJEycanC8pKUFeXp5J2QrHVIjI6shggTEVtLxUZeTIkdi3b1+D57/55hvhoYVNxaBCRNRK3G9toEajER5f0lS8/UVEVofrVH5z6dIlFBYWCq/z8/OF/b5+78aNG1i3bh26d+9uUnsMKkREVmzTpk149913hUC7ZMkSLFmyxKCeTqeDXC7HunXrTGqPQYWIyIpNnz4dffr0gU6nw/Tp0/Haa69h6NChenVkMhnatWsHf39/dO3a1aT2GFSIyOrw9tdvfH194evrC6Auaxk+fLhZH0LIoEJE1ErMnDnT7G0wqBCR1eHix4ZVVlbiyy+/xIkTJ1BeXg6tVqt3XiaTtcznqRARkWVdvHgRI0eORGFhITp27Ijy8nI4OTnhxo0bqK2tRZcuXdC+fXuT2uA6FSKyOtxQ0rjY2FiUl5fju+++w7lz56DT6fDFF1/g1q1b+PDDD2Fvb4+srCyT2mBQISJqJfbv349XXnkF/fv3h41N3a9/nU4HhUKB2NhYjB49Gn/5y19MaoNBhYisjwy/DayY7ZD6QzbenTt3hJlfjo6OkMlkKC8vF84PHDgQhw4dMqkNBhUiolaiW7du+PnnnwEAbdq0wcMPP4zvvvtOOJ+Xlwc7OzuT2uBAPRFZHa5TMW7UqFH46quvkJCQAACIjIxEYmIirl+/Dq1Wi61btyIiIsKkNhhUiIhaibfeegv/+te/oNFooFAoMH/+fFy9ehUZGRmQy+V4/vnnsXz5cpPaYFAhIqtjI6s7zN1GS9OtWzd069ZNeG1nZ4cNGzZgw4YNorXBMRUiIgIAnD17Fi+++KJJ78GgQkRWh+tUDP3666/Izc3FuXPnDM4dO3YMkydPRu/evaFSqUxqh0GFiMiKaTQahIeHw9XVFYMGDYKvry/8/f1RWFiIX375BRMnTsTAgQPxj3/8Ay+//DLOnj1rUnscUyEiq2Mjk8HGzJmEud9fLO+//z5SU1MxYMAADBkyBAUFBcjMzMTMmTNRXFyMa9euYeHChXj11Vfh5ORkcnsMKkREVuzzzz/H008/jb179wply5cvR2xsLPz8/JCfn4+HHnpItPZ4+4uIrA7HVH5z8eJFTJgwQa9s0qRJAIC4uDhRAwrAoEJEZBEajQZvvvkm3NzcYG9vj8DAQOzbt++Br//iiy8wcOBAtGvXDh07dsSgQYOwf//++15XVVUFpVKpV1b/+pFHHmnch3gADCpEZHVsLHQ0RmRkJFasWIHQ0FB8/PHHkMvlePbZZx9or61FixZhxowZcHd3x4oVK7B48WL07dsXV65ceaC2G8qqzJFtyXQ6nU70d21l1Go1lEolikqvwtHRUeruSMrh2V5Sd6HZqNhjOHWztVGr1ejq5Iry8nKL/GzU/yz+UfU82jjYmrWtmjtVyA7b9kCf7dixYwgMDMSyZcswb948AHUPy+rTpw9cXFxw5MiRBq/97rvvMGjQICxfvhwxMTGN7qeNjQ3s7OzQpo3+EPqtW7dgb28PuVyuV373JpONxYF6IrI6MgvM/mrMX/n126DMnj1bKLOzs8NLL72E+fPn4/Lly3B3dzd67cqVK/HQQw8hOjoaOp0Ot2/fbtSDtCzxCOHfY1AhIjKzkydPwtvb2yCj6d+/PwDg+++/bzCofPPNNxg0aBBWrVqFxYsXo7S0FA899BDefvttREVF3bftTZs2mf4BGoFBhYisjiV3KVar1XrlCoUCCoVCr+zatWtwdXU1eI/6sqtXrxpt4/r16ygpKcHhw4exf/9+JCQkoFu3bti0aRNeffVVtG3bFnPmzBHj44iGA/VERCZwd3eHUqkUjsTERIM6FRUVBoEGgPDskoqKCqPvfevWLQBAaWkpNmzYgHnz5mH69OnYtWsX/Pz8sHjxYhE/iTiYqRCR1bHkivrLly/r3dYyFjzs7e2h0WgMyisrK4XzxtSXt23bFlOnTv2tbRsbBAcHIyEhAZcuXdLbeVhqDCpERCZwdHS87+wvV1dXo9N/r127BgBwc3Mzep2TkxPs7OzQsWNHg1laLi4uAOpukTWnoMLbX0REZubv749z584ZjL/k5uYK542xsbGBv78/fv31V1RVVemdqx+HcXZ2Fr/DJmBQISKr09y2aZk6dSpqa2vx2WefCWUajQabNm1CYGCgMPPr0qVLyM/P17s2ODgYtbW1SElJEcoqKyuRmpoKPz+/BrMcqfD2FxGRmQUGBmLatGmIj49HcXExvLy8kJKSgsLCQiQnJwv1IiIicPDgQfx+TfqcOXOwYcMG/PnPf8a5c+fQrVs3bN26FRcvXsTOnTsb1Y+bN2/ixo0betOXr169irVr10Kj0WDKlCnCNOemYlAhIqvTlG1UmtJGY2zZsgULFizA1q1bcf36dfTt2xdff/01hg0bds/r7O3tsX//fsTFxWHjxo24ffs2/P39sWvXLowZM6ZRfZg9ezYKCgrw3XffAaibDj1gwAD8/PPPsLGxwccff4y9e/dixIgRjfx0v2FQISKyADs7OyxbtgzLli1rsM6BAweMlru4uGDz5s0m9+HQoUN661pUKhWuXr2KI0eOoHfv3hg9ejQWL15sUlDhmAoRWZ36KcXmPlqakpISPPzww8Lrv//97xgyZAgGDBiADh06ICIiAqdOnTKpDQYVIqJWomPHjigqKgJQt+Dy22+/xdNPPy2cb9OmDe7cuWNSG7z9RURWx5LbtLQkgwYNwpo1a+Dj44O9e/eisrJS7wFe586d08tkmoJBhYiolfjwww/x9NNPY8qUKQCAN954A7179wYA1NbWIj09Hc8884xJbTCoEJHVseQ2LS2Jl5cXzp49i7y8PCiVSnh4eAjn7ty5g08++QSPPfaYSW0wqBARtSJt27Y1Gjg6dOhg8Cz7pmjUQP3mzZshk8lw/Phxkxtubqqrq+Hn5weZTIaPPvpI6u4QkQlkFjpamu+//x5/+9vf9MqysrIwbNgwBAYG4uOPPza5Dc7++p/Vq1fj0qVLUneDiMhs4uLi8MUXXwivCwoKMGnSJBQUFAAAXn/9db2tZJrCqoOKVqsVtpa+l+LiYvz1r3/Fm2++aYFeEZG5cZ2KcadOncKQIUOE11u2bIFcLsfJkyeRm5uLqVOnYu3atSa1IXpQqaqqwsKFC9GvXz8olUq0a9cOQ4cORU5OjlBHp9PBw8PD6P27yspKKJVKvVWfGo0GCQkJ8PLygkKhgLu7O+Li4gyeTyCTyRAVFYXU1FT07t0bCoUCe/fuvW+f33rrLfTq1QthYWEmfHIiouatvLwcnTt3Fl7v3r0bTz31FLp06QIAeOqpp/Df//7XpDZEH6hXq9XYsGEDZsyYgVmzZuHmzZtITk7GmDFjcOzYMfj7+0MmkyEsLAxLly5FWVkZnJychOt37twJtVot/ILXarUYP348Dh06hNmzZ8PX1xenT59GUlISzp07hx07dui1v3//fqSlpSEqKgpdunTRm91gzLFjx5CSkoJDhw61yHnnRGTIBhaY/dUCR1VcXV1x5swZAHXPcvn3v/+NF154QTh/69Yt2NiYlmuIHlQ6deqEwsJC2NraCmWzZs2Cj48PVq9eLezIGRERgSVLliAtLQ1z584V6qpUKnh4eAgp2rZt25CdnY2DBw/qpW19+vTB3LlzceTIEQwaNEgoP3v2LE6fPg0/P7/79lWn0+HVV19FcHAwBg4ciMLCwgf6jBqNRi9LuvsZCUREzdGECROwevVqVFZWIjc3FwqFApMmTRLOnzp1Cp6enia1IfrtL7lcLgQUrVaLsrIy1NTUICAgACdOnBDqeXt7IzAwEKmpqUJZWVkZ9uzZg9DQUCFrSE9Ph6+vL3x8fFBSUiIco0aNAgC922oAMHz48AcKKEDdbLbTp0/jww8/bNRnTExM1Hsm9e+3kSYi6TW356k0F4sXL8bkyZOxdetWFBcXY/PmzejatSuAuj+OMzIy9LZtaQqzrFNJSUnB8uXLkZ+fj+rqaqG8R48eevUiIiIQFRWFixcvonv37khPT0d1dTXCw8OFOufPn8eZM2cafLpZcXGx3uu722iIWq1GfHw8YmNjGx0U4uPj8frrr+u9FwMLETV37du31/tD/u5zP//8MxwcHExqQ/SgolKpEBkZiYkTJyI2NhYuLi6Qy+VITEzEhQsX9OqGhIQgJiYGqampmD9/PlQqFQICAtCrVy+hjlarxaOPPooVK1YYbe/uX+b29vYP1M+PPvoIVVVVCA4OFm57/fzzzwDqnvlcWFgINzc3vdt49RQKBRQKxQO1Q0SWJ7PA7KyWmKncrby8HO3bt4dcLoeNjQ2USqXJ7yl6UMnIyICnpycyMzP1vvSEhASDuk5OTggKCkJqaipCQ0Nx+PBhrFy5Uq9Oz549cerUKYwePVrU/4iXLl3C9evXhX1vfu/999/H+++/j5MnTzb47Ggiopbo+PHjeOedd/DPf/4TVVVV+Mc//oFRo0ahpKQEL730EmJiYprX81TkcjkA6D0OMzc3F0ePHjVaPzw8HHl5eYiNjYVcLkdISIje+enTp+PKlStYv369wbUVFRW4fft2k/r52muvYfv27XrHunXrAACRkZHYvn37A99KI6LmhSvqjTty5AiGDBmC8+fPIywsDFqtVjjXpUsXlJeXC78Hm6pJmcrGjRuNrv+Ijo7GuHHjkJmZiUmTJiEoKAgFBQVYu3Yt/Pz8cOvWLYNrgoKC0LlzZ6Snp2Ps2LFwcXHROx8eHi7MEMvJycHgwYNRW1uL/Px8pKWlISsrCwEBAY3+DE888QSeeOIJvbL622C9e/fGxIkTG/2eRETN2fz58+Hr64vvvvsON2/exIYNG/TOjxw5EikpKSa10aSg8umnnxotj4yMRGRkJIqKirBu3TpkZWXBz88PKpUK6enpRh+VaWtri+DgYKxZs0ZvgL6ejY0NduzYgaSkJGzZsgXbt2+Hg4MDPD09ER0dDW9v76Z8BCKyYtyl2Lh//etfSExMhEKhMPpH/sMPPyw8xKupGhVU6oPG/cTHxyM+Pl6vLCgoqMH6tra299whs23btoiLi0NcXNw92/39Lbem8PDwMPk9iIiaq7Zt2+rd8rrblStX0L59e5PakHzvr8rKSqhUKkyZMsXkqWxERAD3/mrIgAEDkJGRYfTc7du3sWnTJgwfPtykNiR7nkpxcTGys7ORkZGB0tJSREdHS9UVIqJW4d1338Xw4cMRFBSEGTNmAKhbRf/TTz/ho48+wq+//ooFCxaY1IZkQSUvLw+hoaFwcXHBqlWrOHWXiMjMAgMDsXv3brz88suIiIgAUPdIYaBu+cbu3bvRt29fk9qQLKiMGDGC4xdEZBYymfkXJ7bAu18AgFGjRuHs2bP4/vvvcf78eWi1WvTs2RP9+vUT5Tvj44SJiFohf39/s9whknygnohIbByoN+5vf/vbPWfwvvDCC0hLSzOpDQYVIqJWIikp6Z77Ftrb2yMpKcmkNhhUiMjqcJsW486ePYvHH3+8wfOPPfYY8vPzTWqDQYWIqJXQ6XS4ceNGg+evX7+u97iSpmBQISKrwzEV4x5//HH87W9/Q1VVlcE5jUaDbdu23TOTeRAMKkRErcRbb72FH3/8ESNHjsTOnTvx008/4aeffsLf//53jBgxAv/5z3/w1ltvmdQGpxQTkdXhhpLGjR07FsnJyYiOjtbbiV2n06FDhw5Yv379PfdpfBAMKkRErUhkZCQmT56Mffv2CU/j7dmzJ55++ml06NDB5PdnUCEiqyOTySywor7lZSr1HB0dMWXKFLO8N8dUiIhaiezsbMyfP7/B82+//Tb2799vUhsMKkRkdWwsdLQ07733Hi5fvtzg+StXrmDx4sUmtdESvxciImqC06dPIzAwsMHzTz75JH744QeT2uCYChFZHwuMqbTEbYo1Go3RNSq/P3/nzh2T2mCmQkTUSvTp0wfbt283ek6n0yEzMxN+fn4mtcGgQkRWhyvqjXv11Vdx+PBhTJs2DadPn0ZNTQ1qamrwww8/YNq0aTh69CheffVVk9rg7S8iolYiLCwMFy5cwHvvvYfMzEzY2NTlFVqtFjKZDO+88w5mzpxpUhsMKkRkdbiivmEJCQkICwvD9u3b8dNPPwGoW/w4ceJE9OzZ0+T3Z1AhImplevbsiXnz5pnlvRlUiMjqcEW9dBhUiIhaCRsbmwcKhrW1tU1ug0GFiKyODWSwMfOzGc39/uawcOFCg6BSW1uLwsJC7NixA7169cK4ceNMaoNBhYiolVi0aFGD565du4YBAwbA29vbpDa4ToWIrE79mIq5D2vi6uqKuXPn4r333jPpfRhUiIgIANCuXTsUFBSY9B4MKkREhB9//BGrVq0y+fYXx1SIyOpw8aNxPXr0MHrb7saNGygvL4eDgwN27NhhUhsMKkRErcTw4cMNgopMJkOnTp3Qs2dPhISEwMnJyaQ2GFSIyOrI/vfP3G20NJs3bzZ7GxxTISJqxbRaLYqLi6HT6UR5PwYVIrI6nFL8m3PnzmHLli24fv26Xnl5eTkiIiLg4OAAV1dXODs745NPPjG5PQYVIiIrtnz5cixYsAAdO3bUK58zZw5UKhW6d++OyZMnQ6FQIDo6mgP1RER34+yv3xw+fBjjxo3Ty6wuX76MtLQ0DBw4EAcPHkSbNm1w48YNPPnkk/i///s/TJw4scntMVMhIrJiV65cgY+Pj17Z119/DZlMhujoaLRpU5dbdOzYERERETh58qRJ7TFTISKrI/vflpLmbqMl0Gq1aNu2rV7ZoUOHANRNMf69Rx55BDdv3jSpvZbxrRARUZP07NkT3333nfC6trYW+/fvh4+PD7p27apXt6ysDM7Ozia1x0yFiKyODSwwptJC1qnMnDkTsbGx8PX1xaBBg5Camori4mK89tprBnW//fZbbtNCREQNe+WVV5CdnY34+HjIZDLodDoMHz7c4HHCly9fxp49e7B48WKT2mNQISLrI7PA435bRqKCtm3bYufOnTh+/DguXLiA7t27Y8CAAQb1NBoNtm3bhmHDhpnUHoMKEVErEBAQgICAgAbPe3l5wcvLy+R2GFSIyOpw7y/pcPYXERGJhpkKEVkdrqiXDjMVIiISDTMVIrI6lthFuKXsUmxpzFSIiEg0zFSIyOrY/O+fudtoaUaNGnXP8zKZDHZ2dnjkkUcwcuRITJ06Vdhw8kExqBARtRJarRZXrlzBhQsX0KlTJ3h4eAAACgsLcf36dXh5eUGpVCI3Nxfr16/HBx98gOzsbHTp0uWB22h5oZaI6D745EfjFi9ejOvXryMlJQXFxcX497//jX//+98oLi7Gpk2bcP36daxevRq//vorNm7ciP/85z+Ij49vVBuNCiqbN2+GTCbD8ePHG9VIcxUZGWn0fyh3P3uAiMgazJs3Dy+88ALCw8Mhl8uFcrlcjpkzZyIyMhIxMTGQyWSIjIzEiy++iF27djWqjVZ/+0uhUGDDhg16ZUqlUqLeEJEYOPvLuB9++AHh4eENnvfw8MD//d//Ca/79euHlJSURrVh1UFFq9WiqqoKdnZ2DdZp06YNwsLCLNgrIiJpuLq6IiMjAy+//DJsbPRvVGm1WqSlpeGhhx4SykpLS+Hk5NSoNkQfU6mqqsLChQvRr18/KJVKtGvXDkOHDkVOTo5QR6fTwcPDAxMmTDC4vrKyEkqlEnPmzBHKNBoNEhIS4OXlBYVCAXd3d8TFxUGj0ehdK5PJEBUVhdTUVPTu3RsKhQJ79+69b59ra2uhVqtN+NRE1JzYCM9+NO/R0rz++us4ePAgBg8ejI0bN+LgwYM4ePAgkpOTMWjQIBw6dAhvvPGGUD89PR39+/dvVBuiZypqtRobNmzAjBkzMGvWLNy8eRPJyckYM2YMjh07Bn9/f8hkMoSFhWHp0qUoKyvTi4Q7d+6EWq0WsgetVovx48fj0KFDmD17Nnx9fXH69GkkJSXh3Llz2LFjh177+/fvR1paGqKiotClSxdhdkND7ty5A0dHR9y5cwedOnXCjBkz8OGHH6J9+/ZifzVERJL685//DBsbGyxcuBB/+tOfhFt4Op0OnTt3xqpVq/DnP/8ZQN0f80lJSff9HXo30YNKp06dUFhYCFtbW6Fs1qxZ8PHxwerVq5GcnAwAiIiIwJIlS5CWloa5c+cKdVUqFTw8PDBkyBAAwLZt25CdnY2DBw8KZQDQp08fzJ07F0eOHMGgQYOE8rNnz+L06dPw8/O7b19dXV0RFxeHJ554AlqtFnv37sWaNWtw6tQpHDhwoMH52RqNRi9LYpZDRC3Fyy+/jD/96U84fvw4Ll68CADo3r07AgIC9J5lr1AoDJ5h/yBEDypyuVyYVaDVanHjxg1otVoEBATgxIkTQj1vb28EBgYiNTVVCCplZWXYs2cP4uLihAianp4OX19f+Pj4oKSkRLi+fhFPTk6OXlAZPnz4AwUUAEhMTNR7HRISAm9vb7z99tvIyMhASEhIg9e9++67D9QGEVkeB+rvrW3bthg4cCAGDhwo+nubZaA+JSUFy5cvR35+Pqqrq4XyHj166NWLiIhAVFQULl68iO7duyM9PR3V1dV6sxPOnz+PM2fOwNnZ2WhbxcXFeq/vbqOxYmJisGDBAmRnZzcYVOLj4/H6668Lr9VqNdzd3U1ql4jIUvLy8vDTTz/h+vXr0Ol0BucjIiKa/N6iBxWVSoXIyEhMnDgRsbGxcHFxgVwuR2JiIi5cuKBXNyQkBDExMUhNTcX8+fOhUqkQEBCAXr16CXW0Wi0effRRrFixwmh7d/8yt7e3N6n/9vb26Ny5M8rKyhqso1AooFAoTGqHiMyHW98bd+HCBYSFheHYsWNGgwlQl4E1q6CSkZEBT09PZGZm6qWHCQkJBnWdnJwQFBSE1NRUhIaG4vDhw1i5cqVenZ49e+LUqVMYPXq0RdLNmzdvoqSkpMHMiIiopZozZw5Onz6NlStXYujQoejUqZPobZhlTAWom01QHwRyc3Nx9OhRdOvWzaB+eHg4Jk+ejNjYWMjlcoNbTtOnT8fu3buxfv16zJ49W+9cRUUFtFot2rVr1+h+VlZWorq6Gh06dNArf++996DT6fDMM880+j2JqHng44SNO3z4MObPn49XX33VbG00Kahs3LjR6PqP6OhojBs3DpmZmZg0aRKCgoJQUFCAtWvXws/PD7du3TK4JigoCJ07d0Z6ejrGjh0LFxcXvfPh4eHCDLGcnBwMHjwYtbW1yM/PR1paGrKyshAQENDoz1BUVITHH38cM2bMELZlycrKwu7du/HMM88YXUNDRNSSdenSxew7hjQpqHz66adGyyMjIxEZGYmioiKsW7cOWVlZ8PPzg0qlQnp6Og4cOGBwja2tLYKDg7FmzRqj2wfY2Nhgx44dSEpKwpYtW7B9+3Y4ODjA09MT0dHR8Pb2bspHQMeOHTFu3Djs27cPKSkpqK2thZeXF95//33MmzfPYLUpEbUcNjIb2MjMvPW9md/fHObOnQuVSoU///nPent/iUmma2i0xoJiYmKQnJyMoqIiODg4SN2dRlOr1VAqlSgqvQpHR0epuyMph2d73b9SK1Gx55zUXZCcWq1GVydXlJeXW+Rno/5n8YPDS2DXvuHtmcRQeasSbw1+22KfTQzp6en44IMPoNFo8OKLL8Ld3d1ocJk8eXKT25B876/KykqoVCpMmTKlRQYUImp+uE7FuODgYOH/nzdvntE6MpkMtbW1TW5DsqBSXFyM7OxsZGRkoLS0FNHR0VJ1hYioVfj9HozmIllQycvLQ2hoKFxcXLBq1Sr4+/tL1RUisjrmn/2FFjj7qynbrjSWZEFlxIgRDS6+ISKilknyMRUiIrFxRX2dkSNHwsbGBllZWWjTpo2wZ+K9yGQyfPPNN01us+XNiSMiaoE0Gg3efPNNuLm5wd7eHoGBgdi3b1+j3+epp54Snh11PzqdDlqtVnit1Wqh0+nuefy+flMwUyEiq9McV9RHRkYiIyMDf/nLX/CHP/wBmzdvxrPPPoucnBy9x3rcS2ZmJo4ePfrAbd69NtDYWkGxMVMhIjKzY8eO4fPPP0diYiKWLVuG2bNnY//+/ejevTvi4uIe6D0qKyvxxhtv4M033zRzb03DTIWIrI6NzPxjHjaNePuMjAzI5XK9/Qvt7Ozw0ksvYf78+bh8+fJ9H5+xdOlSaLVazJs3DwsXLmxqtwHUbZx78eLFBre+HzZsWJPfm0GFiMjMTp48CW9vb4OV9/XPf//+++/vGVQuXbqEDz74ABs3bjTp8R6lpaWIiorCl19+aXSBY/1GwC1y8SMRkbnIZDaQmXlvrvr3v/tx4saet3Tt2jW4uroavEd92dWrV+/Z1htvvIHHH3+8wQcHPqhZs2Zh586deO2111rO1vdERK3J3RlGQkICFi1apFdWUVFh9MF+dnZ2wvmG5OTk4Msvv0Rubq7Jff3HP/6BmJgYLF261OT3agiDChFZHUvO/rp8+bLebS1jwcPe3h4ajcagvLKyUjhvTE1NDV577TWEh4fjySefNLnPDg4O8PDwMPl97oWzv4iITODo6Kh3GAsqrq6uuHbtmkF5fZmbm5vR996yZQvOnj2LOXPmoLCwUDiAusH2wsJC3Llz54H7GhYWhu3btz9w/aZgpkJEVqe5raj39/dHTk4O1Gq1XlZTf0urob0PL126hOrqagwePNjg3JYtW4RnTE2cONHo9SdOnNB7PW3aNBw8eBDPPPMMZs+e3eDW90888cQDfjJDDCpERGY2depUfPTRR/jss8+ELec1Gg02bdqEwMBAYVzm0qVLuHPnjvA02pCQEKMBZ9KkSXj22Wcxa9YsBAYGNthuQECAwRb99VOIja3m5+wvIiIjmtvzVAIDAzFt2jTEx8ejuLgYXl5eSElJQWFhIZKTk4V6EREROHjwoPCL38fHRwgwd+vRo0eDGUq9TZs2PXAfxcKgQkRkAVu2bMGCBQuwdetWXL9+HX379sXXX39t0kLD+5k5c6bZ3rshDCpERBZgZ2eHZcuWYdmyZQ3WedC9uZr62JCamhrcuXOnwccfq9VqODg4oE2bpocGzv4iIqtjA5lFjpbmtddew6BBgxo8P3jwYLzxxhsmtcGgQkTUSuzduxdTp05t8PzUqVOxe/duk9rg7S8isjrNbaC+ubh69SoefvjhBs+7ubnhypUrJrXBTIWIqJXo3Lkzzp492+D5M2fONDje8qAYVIjI6tRvKGnuo6V55plnsG7dOpw8edLg3IkTJ/DZZ59h7NixJrXB218kqo+WRkvdBSJqwHvvvYe9e/eif//+GD9+PHr37g0A+PHHH7Fz5064uLjgvffeM6kNBhUisjqWmJ3VEmd/ubm54fjx43jrrbfw1VdfCfuAOTo6IjQ0FO+//36D+5A9KAYVIqJWxNXVFSkpKdDpdPj1118BAM7OzqJNPGh5NwWJiO6jfvaXuY+W5sUXXxQ2sZTJZHBxcYGLi4vwWY4dO4YXX3zRpDYYVIiIWonNmzfjwoULDZ4vKChASkqKSW3w9hcRWSHzP6QLLXBM5X6uXr3a4APDHhSDChGRFfvqq6/w1VdfCa8/++wzZGdnG9S7ceMGsrOzTX7CJIMKEVkdGSywor6FZCp5eXlIT08HUDeOkpubi3//+996dWQyGdq1a4dhw4ZhxYoVJrXHoEJEZMXi4+MRHx8PALCxsUFycjKef/55s7XHoEJEVofrVIzTarVmb4Ozv4iISDQMKkRkdbj3V8P27NmDp556Cp07d0abNm0gl8sNDlO0zG+FiIga7csvv8S4cePwyy+/ICQkBFqtFjNmzEBISAjs7e3Rt29fLFy40KQ2OKZCRFZHZoF1Ki1l9tfvJSYmon///jh06BCuX7+OTz/9FC+++CJGjRqFwsJCDBgwAD169DCpDWYqREStRF5eHkJCQiCXy4Xn0FdXVwMAPDw88Morr+DDDz80qQ1mKkRkdWQy8z+ZsQVu/QUHBwfY2toCADp27AiFQoFr164J57t27YqCggKT2mCmQkTUSvTq1Qt5eXnCa39/f2zduhU1NTWorKzEtm3b0K1bN5PaYFAhIqsjs9C/lmbSpEn46quvoNFoAABvv/02Dhw4gI4dO8LZ2Rnffvst3nrrLZPa4O0vIqJWYt68eZg3b57wety4cThw4AAyMzMhl8sRFBSEkSNHmtQGgwoRWR1LPO+kJT1PpbKyEl999RUKCgrQpUsXBAUFwdXVFQAwdOhQDB06VLS2GFSIiKxYcXExBg0ahIKCAuh0OgB1A/Y7duzAH//4R9Hb45gKEZEVe++991BYWIiYmBh8/fXXWLlyJezt7TFnzhyztMdMhYisDjeU/M0//vEPRERE4KOPPhLKunbtiueffx5nz55Fr169RG2PmQoRkRW7dOkShgwZolc2ZMgQ6HQ6/PLLL6K3x0yFiKwOB+p/o9FoYGdnp1dW/7qmpkb09hhUiIisXGFhIU6cOCG8Li8vBwCcP38eHTt2NKj/xBNPNLktBhUisjqy/42qmLuNlmLBggVYsGCBQfkrr7yi91qn00Emk6G2trbJbTGoEBFZsU2bNlm0vUYFlc2bN+OFF17Av/71LwQEBJirTxal1Wqxbt06rFu3DmfPnoWDgwMee+wxJCUl4bHHHpO6e0TUBBxT+c3MmTMt2l6rz1RefPFFpKamIiIiAlFRUbh9+zZOnjyJ4uJiqbtGRNTiWHVQ0Wq1qKqqMpj5UC8tLQ0pKSnIzMzEpEmTLNw7IjIXPqRLOqKPNFVVVWHhwoXo168flEol2rVrh6FDhyInJ0eoo9Pp4OHhgQkTJhhcX1lZCaVSqbfaU6PRICEhAV5eXlAoFHB3d0dcXJyw02Y9mUyGqKgopKamonfv3lAoFNi7d2+DfV2xYgX69++PSZMmQavV4vbt2yJ8A0RErZfoQUWtVmPDhg0YMWIEPvzwQyxatAi//vorxowZg++//x5A3S//sLAw7NmzB2VlZXrX79y5E2q1GmFhYQDqso3x48fjo48+wnPPPYfVq1dj4sSJSEpKQnBwsEH7+/fvR0xMDIKDg/Hxxx/Dw8OjwX4eO3YMTz75JObPnw+lUon27dvD09MTaWlpon4nRGRZNjKZRQ4yJPrtr06dOqGwsFB4uhgAzJo1Cz4+Pli9ejWSk5MBABEREViyZAnS0tIwd+5coa5KpYKHh4ewAnTbtm3Izs7GwYMH9VaF9unTB3PnzsWRI0cwaNAgofzs2bM4ffo0/Pz87tnPCxcuQKfT4fPPP0ebNm2wdOlSKJVKfPzxxwgJCYGjoyOeeeYZo9dqNBq9LEmtVjfiGyIisl6iZypyuVwIKFqtFmVlZaipqUFAQIDe4htvb28EBgYiNTVVKCsrK8OePXsQGhoqzKxIT0+Hr68vfHx8UFJSIhyjRo0CAL3bagAwfPjw+wYUALh16xYAoLS0FF999RVefvllPP/88/jmm2/QuXNnLF68uMFrExMToVQqhcPd3f0Bvx0isgQ+pEs6Zlm9k5KSgr59+8LOzg6dO3eGs7Mzdu3aJazirBcREYHDhw/j4sWLAOoCSHV1NcLDw4U658+fx3/+8x84OzvrHd7e3gBgMEurR48eD9RHe3t7oX5gYKBQ3r59ezz33HM4duxYg1sYxMfHo7y8XDguX778QG0SEVk70W9/qVQqREZGYuLEiYiNjYWLiwvkcjkSExNx4cIFvbohISGIiYlBamoq5s+fD5VKhYCAAL1dM7VaLR599FGsWLHCaHt3Zwn1weJ+3NzcANTt1nk3FxcXVFdX4/bt21AqlQbnFQoFFArFA7VDRJbHdSrSET2oZGRkwNPTE5mZmXpfekJCgkFdJycnBAUFITU1FaGhoTh8+DBWrlypV6dnz544deoURo8eLep/RDc3Nzz00EO4cuWKwbmrV6/Czs4OHTp0EK09IqLWwCxjKgCEJ4wBQG5uLo4ePWq0fnh4OPLy8hAbGwu5XI6QkBC989OnT8eVK1ewfv16g2srKipMmgYcHByMy5cvY9++fUJZSUkJvvrqK4waNQo2Ni1nbx8i+r36J6qY7+CTQ4xrUqayceNGo+s/oqOjMW7cOGExYVBQEAoKCrB27Vr4+fkJg+O/FxQUhM6dOyM9PR1jx46Fi4uL3vnw8HBhhlhOTg4GDx6M2tpa5OfnIy0tDVlZWU3eMiY+Ph5paWmYMmUKXn/9dSiVSqxduxbV1dV4//33m/SeREStWZOCyqeffmq0PDIyEpGRkSgqKsK6deuQlZUFPz8/qFQqpKen48CBAwbX2NraIjg4GGvWrNEboK9nY2ODHTt2ICkpCVu2bMH27dvh4OAAT09PREdHCwP2TdG1a1ccOnQI8+bNQ1JSEqqrqzFw4ECoVCru+0XUgnFMRToy3e/vU0kkJiYGycnJKCoqgoODg9TdaTS1Wg2lUomi0qtwdHSUujuSWvPjGqm70Gz8+dE/S90FyanVanR1ckV5eblFfjbqfxa/zPsc7TqY93fJ7Zt3MMUvxGKfraWQfO+vyspKqFQqTJkypUUGFCJqfviMeulIFlSKi4uRnZ2NjIwMlJaWIjo6WqquEBGRSCQLKnl5eQgNDYWLiwtWrVoFf39/qbpCRFaGYyrSkSyojBgxAs1gOIeIiEQk+ZgKEZHY+DwV6XD1DhERiYZBhYiIRMPbX0RkdThQLx1mKkREJBpmKkRkdeqG6c37NzMH6o1jpkJERKJhpkJEVsdGJoONmcc8zP3+LRUzFSIiEg0zFSKyOlz8KB1mKkREJBpmKkRkdbhORTrMVIiISDTMVIjI6nBMRTrMVIiISDTMVIjI6nBMRTrMVIiISDTMVIjI6tj875+52yBD/FaIiEg0zFSIyOpwTEU6zFSIiEg0zFRIVK/0eUXqLhBxnYqEmKkQEZFomKkQkfWxwJgKOKZiFDMVIiISDTMVIrI6HFORDjMVIiISDTMVIrI6zFSkw0yFiIhEw0yFiKyPTGb+2Vmc/WUUMxUiIhINgwoREYmGt7+IyOpwoF46zFSIiEg0zFSIyOpw63vpMFMhIiLRMFMhIqvDMRXpMFMhIiLRMFMhIqsjg/kzCeYpxjFTISIi0TBTISKrI4MFZn8xVzGKmQoREYmGQYWIrI7MQv8aQ6PR4M0334Sbmxvs7e0RGBiIffv23fe6zMxMBAcHw9PTEw4ODujVqxfeeOMN3Lhxo4nfjnkxqBARWUBkZCRWrFiB0NBQfPzxx5DL5Xj22Wdx6NChe143e/ZsnDlzBmFhYVi1ahWeeeYZfPLJJxg4cCAqKios1PsHxzEVIrI6zW2dyrFjx/D5559j2bJlmDdvHgAgIiICffr0QVxcHI4cOdLgtRkZGRgxYoReWb9+/TBz5kykpqbiT3/6U5P6by7MVIiIzCwjIwNyuRyzZ88Wyuzs7PDSSy/h6NGjuHz5coPX3h1QAGDSpEkAgDNnzojeV1MxqBCR1anf+8vcx4M6efIkvL294ejoqFfev39/AMD333/fqM9XVFQEAOjSpUujrrME3v4iIjKBWq3We61QKKBQKPTKrl27BldXV4Nr68uuXr3aqDY//PBDyOVyTJ06tZG9Nb9GZSqbN2+GTCbD8ePHzdUfi7rXXyBPPfWU1N0joiay5Owvd3d3KJVK4UhMTDToT0VFhUGgAepugdWff1Dbtm1DcnIy3njjDfzhD39o4jdkPq06U9m6datB2fHjx/Hxxx/j6aeflqBHRNTSXL58We+2lrHgYW9vD41GY1BeWVkpnH8Q3377LV566SWMGTMGS5YsaWKPzcuqg4pWq0VVVZXw18DdwsLCDMoOHDgAmUyGGTNmmLt7RGQmlnyeiqOjo8FYyd1cXV1x5coVg/Jr164BANzc3O7b3qlTpzB+/Hj06dMHGRkZaNOmef76Fn2gvqqqCgsXLkS/fv2gVCrRrl07DB06FDk5OUIdnU4HDw8PTJgwweD6yspKKJVKzJkzRyjTaDRISEiAl5cXFAoF3N3dERcXZxD5ZTIZoqKikJqait69e0OhUGDv3r0P3HeNRoMvv/wSw4cPxyOPPNKET09EZMjf3x/nzp0zGH/Jzc0Vzt/LhQsX8Mwzz8DFxQW7d+9G+/btzdVVk4keVNRqNTZs2IARI0bgww8/xKJFi/Drr79izJgxwgwHmUyGsLAw7NmzB2VlZXrX79y5E2q1WsgitFotxo8fj48++gjPPfccVq9ejYkTJyIpKQnBwcEG7e/fvx8xMTEIDg7Gxx9/DA8Pjwfu++7du3Hjxg2EhoY2+fMTkfQsOabyIKZOnYra2lp89tlnQplGo8GmTZsQGBgId3d3AMClS5eQn5+vd21RURGefvpp2NjYICsrC87OzuJ8SWYiev7UqVMnFBYWwtbWViibNWsWfHx8sHr1aiQnJwOoW/izZMkSpKWlYe7cuUJdlUoFDw8PDBkyBEDdoFR2djYOHjwolAFAnz59MHfuXBw5cgSDBg0Sys+ePYvTp0/Dz8+v0X1PTU2FQqG474wKjUajlyXd/dcHEdHvBQYGYtq0aYiPj0dxcTG8vLyQkpKCwsJC4XciUPd78eDBg9DpdELZM888g59++glxcXE4dOiQ3gr8rl27NrtJRaIHFblcDrlcDqAuy7hx4wa0Wi0CAgJw4sQJoZ63tzcCAwORmpoqBJWysjLs2bMHcXFxwv3K9PR0+Pr6wsfHByUlJcL1o0aNAgDk5OToBZXhw4c3KaCo1Wrs2rULzz77LDp27HjPuomJiXj33Xcb3QYRWUZjM4mmttEYW7ZswYIFC7B161Zcv34dffv2xddff41hw4bd87pTp04BAJYuXWpwbvjw4dYfVAAgJSUFy5cvR35+Pqqrq4XyHj166NWLiIhAVFQULl68iO7duyM9PR3V1dUIDw8X6pw/fx5nzpxpMOUrLi7We313Gw/qyy+/RGVl5QPd+oqPj8frr78uvFar1UL6SkRkjJ2dHZYtW4Zly5Y1WOfAgQMGZb/PWloC0YOKSqVCZGQkJk6ciNjYWLi4uEAulyMxMREXLlzQqxsSEoKYmBikpqZi/vz5UKlUCAgIQK9evYQ6Wq0Wjz76KFasWGG0vbt/mT/o1Ly7paamQqlUYty4cfeta2xxExE1H5ac/UX6RA8qGRkZ8PT0RGZmpt6XnpCQYFDXyckJQUFBSE1NRWhoKA4fPoyVK1fq1enZsydOnTqF0aNHm+0/4rVr15CTk4PIyEgGCyIiE4g++6t+POX3KVtubi6OHj1qtH54eDjy8vIQGxsLuVyOkJAQvfPTp0/HlStXsH79eoNrKyoqcPv2bZP7/Pnnn0Or1XLWFxGRiZqUqWzcuNHo+o/o6GiMGzcOmZmZmDRpEoKCglBQUIC1a9fCz88Pt27dMrgmKCgInTt3Rnp6OsaOHQsXFxe98+Hh4cIMsZycHAwePBi1tbXIz89HWloasrKyEBAQ0JSPIUhNTYWbm5vR3UCJqOVpjgP1rUWTgsqnn35qtDwyMhKRkZEoKirCunXrkJWVBT8/P6hUKqSnpxsdhLK1tUVwcDDWrFmjN0Bfz8bGBjt27EBSUhK2bNmC7du3w8HBAZ6enoiOjoa3t3dTPoLg7Nmz+Pe//43XX38dNjbctJmIyBQyXTOYWhATE4Pk5GQUFRXBwcFB6u40mlqthlKpRFHp1ftu10CtBwdy6342ujq5ory83CI/G/U/iycufYf2juZddX5LfQtPdBtgsc/WUkj+p3llZSVUKhWmTJnSIgMKERH9RrIdyYqLi5GdnY2MjAyUlpYiOjpaqq4QkbWxwJRiMBM1SrKgkpeXh9DQULi4uGDVqlX33VCNiIiaP8mCyogRI1rcSlEiailk/zvM3QbdTfIxFSIish7N8ykvREQm4DYt0mGmQkREomGmQkRWhyvqpcNMhYiIRMNMhYisDjMV6TBTISIi0TBTISKrw9lf0mGmQkREomGmQkRWp249vbnHVMgYZipERCQaZipEZHU4+0s6zFSIiEg0zFSIyOpw9pd0mKkQEZFomKkQkdXhmIp0mKkQEZFomKkQkdXhmIp0mKkQEZFoGFSIiEg0vP1FRFaHA/XSYaZCRESiYaZCRFZIBvNv+chMxRhmKkREJBpmKkRkdZinSIeZChERiYaZChFZHS5+lA4zFSIiEg0zFSKyQhxVkQozFSIiEg0zFSKyOsxTpMNMhYiIRMNMhYisEHMVqTBTISIi0TBTISKrw3Uq0mGmQkREomFQISIi0TCoEBGRaDimQkRWh09+lA4zFSIiEg0zFSKyOsxUpMNMhYiIRMOgQkREomFQISIi0XBMhYisDlfUS4eZChERiYZBhYiIRMOgQkREomFQISIi0TQqqGzevBkymQzHjx83V38sLi0tDQMGDEDHjh3RuXNnDB8+HLt27ZK6W0RkEpnZ//EhXca16kxl9erVCA4ORpcuXfDBBx9gwYIFKC8vx7hx45CZmSl194iIWhyrnlKs1WpRVVUFOzs7o+dXr16NJ598Ejt37hSmB7744ot4+OGHkZKSgsmTJ1uyu0QkGj5OWCqiZypVVVVYuHAh+vXrB6VSiXbt2mHo0KHIyckR6uh0Onh4eGDChAkG11dWVkKpVGLOnDlCmUajQUJCAry8vKBQKODu7o64uDhoNBq9a2UyGaKiopCamorevXtDoVBg7969DfZVrVbDxcVFb765o6Mj2rdvD3t7e1O+BiKiVkn0TEWtVmPDhg2YMWMGZs2ahZs3byI5ORljxozBsWPH4O/vD5lMhrCwMCxduhRlZWVwcnISrt+5cyfUajXCwsIA1GUb48ePx6FDhzB79mz4+vri9OnTSEpKwrlz57Bjxw699vfv34+0tDRERUWhS5cu8PDwaLCvI0aMQEZGBlavXo3nnnsOlZWVWL16NcrLyxEdHS32V0NEFsI8RTqiB5VOnTqhsLAQtra2QtmsWbPg4+OD1atXIzk5GQAQERGBJUuWIC0tDXPnzhXqqlQqeHh4YMiQIQCAbdu2ITs7GwcPHhTKAKBPnz6YO3cujhw5gkGDBgnlZ8+exenTp+Hn53ffvq5atQolJSV47bXX8NprrwEAunTpgm+++QYDBw5s8DqNRqOXJanV6vu2RUTUGoh++0sulwsBRavVoqysDDU1NQgICMCJEyeEet7e3ggMDERqaqpQVlZWhj179iA0NFS4JZWeng5fX1/4+PigpKREOEaNGgUAerfVAGD48OEPFFAAwMHBAb169cLMmTORnp6OjRs3wtXVFZMnT8Z///vfBq9LTEyEUqkUDnd39wf7cojIIuq3aTH3QYbMMlCfkpKC5cuXIz8/H9XV1UJ5jx499OpFREQgKioKFy9eRPfu3ZGeno7q6mqEh4cLdc6fP48zZ87A2dnZaFvFxcV6r+9u416mTZuGNm3aYOfOnULZhAkT8Ic//AFvv/02vvjiC6PXxcfH4/XXXxdeq9VqBhYiIpghqKhUKkRGRmLixImIjY2Fi4sL5HI5EhMTceHCBb26ISEhiImJQWpqKubPnw+VSoWAgAD06tVLqKPVavHoo49ixYoVRtu7+5f5gw6w//TTT9i7dy8+++wzvXInJycMGTIEhw8fbvBahUIBhULxQO0QkRQ4qiIV0YNKRkYGPD09kZmZqZceJiQkGNR1cnJCUFAQUlNTERoaisOHD2PlypV6dXr27IlTp05h9OjRoqabv/zyCwCgtrbW4Fx1dTVqampEa4uIqLUwy5gKUDdtuF5ubi6OHj1qtH54eDjy8vIQGxsLuVyOkJAQvfPTp0/HlStXsH79eoNrKyoqcPv27Sb108vLCzY2Nvjiiy/0+vrzzz/j22+/xeOPP96k9yUi6cksdJChJmUqGzduNLr+Izo6WliNPmnSJAQFBaGgoABr166Fn58fbt26ZXBNUFAQOnfujPT0dIwdOxYuLi5658PDw4UZYjk5ORg8eDBqa2uRn5+PtLQ0ZGVlISAgoNGfwdnZGS+++CI2bNiA0aNHY/Lkybh58ybWrFmDiooKxMfHN/o9iYhauyYFlU8//dRoeWRkJCIjI1FUVIR169YhKysLfn5+UKlUSE9Px4EDBwyusbW1RXBwMNasWaM3QF/PxsYGO3bsQFJSErZs2YLt27fDwcEBnp6eiI6Ohre3d1M+gvA5HnvsMSQnJwtB5Mknn8SWLVswbNiwJr8vETUHzCWkINP9/t6PRGJiYpCcnIyioiI4ODhI3Z1GU6vVUCqVKCq9CkdHR6m7Q80Ep5zW/Wx0dXJFeXm5RX426n8WL/1aYPb21Go1ujn3sNhnaykk3/ursrISKpUKU6ZMaZEBhYiaHz5OWDqSBZXi4mJkZ2cjIyMDpaWl3BaFiMgKSBZU8vLyEBoaChcXF6xatQr+/v5SdYWIiEQiWVAZMWIEmsFwDhERiUjyMRUiIrH99nRG87ZBhlr1kx+JiEhczFSIyApx7y+pMFMhIiLRMFMhIqvDPEU6zFSIiEg0zFSIyOpwRb10mKkQEZFoGFSIiEg0vP1FRFaIQ/VSYaZCRESiYaZCRFaHeYp0mKkQEZFomKkQkRViriIVZipERCQaBhUisjr1ix/NfTSGRqPBm2++CTc3N9jb2yMwMBD79u17oGuvXLmC6dOno2PHjnB0dMSECRPw008/NeWrMTsGFSIiC4iMjMSKFSsQGhqKjz/+GHK5HM8++ywOHTp0z+tu3bqFkSNH4uDBg5g/fz7effddnDx5EsOHD0dpaamFev/gOKZCRGRmx44dw+eff45ly5Zh3rx5AICIiAj06dMHcXFxOHLkSIPXrlmzBufPn8exY8fw5JNPAgDGjh2LPn36YPny5Xj//fct8hkeFDMVIiIzy8jIgFwux+zZs4UyOzs7vPTSSzh69CguX758z2uffPJJIaAAgI+PD0aPHo20tDSz9rspGFSIyOrILPTvQZ08eRLe3t5wdHTUK+/fvz8A4Pvvvzd6nVarxQ8//ICAgACDc/3798eFCxdw8+bNB/9iLIC3v0Sg0+kAADfVzes/LkmLu9j+9jNR/zNiKWoL/CzWt6FWq/XKFQoFFAqFXtm1a9fg6upq8B71ZVevXjXaRllZGTQazX2v7dWrV+M/gJkwqIig/i+FP/RoPv9hiZqTmzdvQqlUmr0dW1tbPPTQQ/iDh7fZ2wKA9u3bw93dXa8sISEBixYt0iurqKgwCDRA3S2w+vPG1Jc35VqpMKiIwM3NDZcvX0aHDh341ynR7+h0Oty8eRNubm4Wac/Ozg4FBQWoqqqySHs6nc7gZ95YALC3t4dGozEor6ysFM4bU1/elGulwqAiAhsbGzzyyCNSd4OoWbJEhvJ7dnZ2wl/xzYWrqyuuXLliUH7t2jUAaDDoOjk5QaFQCPUac61UOFBPRGRm/v7+OHfunMH4S25urnDeGBsbGzz66KM4fvy4wbnc3Fx4enqiQ4cOovfXFAwqRERmNnXqVNTW1uKzzz4TyjQaDTZt2oTAwEBhXObSpUvIz883uPZf//qXXmA5e/Ys9u/fj2nTplnmAzSCTGfpaRlERK3Q9OnTsX37dsTExMDLywspKSk4duwYvvnmGwwbNgwAMGLECBw8eFBvttzNmzfx+OOP4+bNm5g3bx7atm2LFStWoLa2Ft9//z2cnZ2l+khGcUyFiMgCtmzZggULFmDr1q24fv06+vbti6+//loIKA3p0KEDDhw4gJiYGCxevBharRYjRoxAUlJSswsoADMVIiISEcdUiIhINAwqREQkGgYVIiISDYMKERGJhkGFiIhEw6BCRESiYVAhIiLRMKgQEZFoGFSIiEg0DCpERCQaBhUiIhINgwoREYmGQYWIiETz/0IUE/oYucskAAAAAElFTkSuQmCC", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "# draw the success_rate across layers and positions\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "data = success_rate\n", + "\n", + "fig, ax = plt.subplots(figsize=(6, 6))\n", + "\n", + "cmap = plt.cm.Greens.copy()\n", + "cmap.set_bad(color='white')\n", + "\n", + "im = ax.imshow(data, cmap=cmap, vmin=0, vmax=1)\n", + "\n", + "fontsize = 12\n", + "\n", + "x_labels = ['$e_1$', '$r_1$', '$r_2$']\n", + "ax.set_xticks(np.arange(len(x_labels)))\n", + "ax.set_xticklabels(x_labels, fontsize=fontsize)\n", + "ax.xaxis.set_ticks_position('top')\n", + "ax.tick_params(top=True, labeltop=True)\n", + "\n", + "y_labels = [f'Layer {i+1}' for i in range(data.shape[0])]\n", + "ax.set_yticks(np.arange(len(y_labels)))\n", + "ax.set_yticklabels(y_labels, fontsize=fontsize)\n", + "\n", + "cbar = plt.colorbar(im, ax=ax)\n", + "cbar.set_label('Patching Success Rate', fontsize=fontsize)\n", + "cbar.ax.tick_params(labelsize=fontsize)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "latent", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.19" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/data_preparation.ipynb b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/data_preparation.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b3bc2a2bca1dc787212e0ebb30d3a3f9ef4004e5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/data_preparation.ipynb @@ -0,0 +1,985 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "71e73838", + "metadata": {}, + "source": [ + "# utils" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "668e64b1", + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "import numpy as np\n", + "import random\n", + "from tqdm.auto import tqdm\n", + "import itertools\n", + "import os\n", + "from copy import deepcopy\n", + "import matplotlib.pyplot as plt\n", + "\n", + "def build_dicts(entities):\n", + " entity2ind = dict()\n", + " ind2entity = []\n", + " for i in range(len(entities)):\n", + " entity = entities[i]\n", + " if not (entity in ind2entity):\n", + " ind2entity.append(entity)\n", + " entity2ind[entity] = len(ind2entity) - 1\n", + " return ind2entity, entity2ind\n", + "\n", + "def choose(arr, ratio_or_count):\n", + " if type(ratio_or_count) == float:\n", + " num = round(ratio_or_count*len(arr))\n", + " elif type(ratio_or_count) == int:\n", + " num = ratio_or_count\n", + " else:\n", + " assert False\n", + " if num >= len(arr):\n", + " return arr\n", + " rand_inds = np.random.choice(len(arr), num, replace=False).tolist()\n", + " return [arr[i] for i in rand_inds]\n", + " \n", + "def split(arr, ratio_or_count):\n", + " if type(ratio_or_count) == float:\n", + " num = round(ratio_or_count*len(arr))\n", + " elif type(ratio_or_count) == int:\n", + " num = ratio_or_count\n", + " else:\n", + " assert False\n", + " train, test = [], []\n", + " rand_inds = np.random.choice(len(arr), num, replace=False).tolist()\n", + " for i in tqdm(range(len(arr))):\n", + " if i in rand_inds:\n", + " train.append(arr[i])\n", + " else:\n", + " test.append(arr[i])\n", + " return [train, test]\n", + "\n", + "def form_items(c, t):\n", + " \"\"\"\n", + " return format:\n", + " {\n", + " \"input_text\": \"\", \n", + " \"target_text\": \"\",\n", + " }\n", + " \"\"\"\n", + " input_text = \"\".join(c)\n", + " target_text = input_text + \"\".join([t, \"\"])\n", + " item = {\n", + " \"input_text\": input_text,\n", + " \"target_text\": target_text\n", + " }\n", + " return item" + ] + }, + { + "cell_type": "markdown", + "id": "1fcedc07", + "metadata": {}, + "source": [ + "# Base Configuration" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "8d4fd9c5", + "metadata": {}, + "outputs": [], + "source": [ + "def build_base_dataset(num_entities, num_relations, out_degree=20):\n", + " \n", + " entities = [\"\".format(i) for i in range(num_entities)]\n", + " ind2entity, entity2ind = build_dicts(entities)\n", + "\n", + " relations = [\"\".format(i) for i in range(num_relations)]\n", + " ind2relation, relation2ind = build_dicts(relations)\n", + "\n", + " atomic_dict = dict() # {h1: [(r1, t1), (r2, t2), ...], ...}\n", + " atomic_facts = [] # [{\"input_text\": \"...\", \"target_text\": \"...\"}, ...]\n", + " atomics = [] # [(h1,r1,t1), (h2,r2,t2), ...]\n", + "\n", + " for i in tqdm(range(num_entities)):\n", + " # for each subject entity, randomly select some outgoing relations to some random object entity\n", + " num_rows = out_degree\n", + " selected_rows = np.random.choice(num_relations, size=num_rows, replace=False).tolist()\n", + " for row_idx in selected_rows:\n", + " col_idx = np.random.randint(num_entities) # pick some random tail entity for each selected (h,r)\n", + " h,r,t = ind2entity[i], ind2relation[row_idx], ind2entity[col_idx] # h and t might be same here\n", + " atomic_facts.append(form_items([h, r], t))\n", + " atomics.append((h,r,t))\n", + " if h not in atomic_dict:\n", + " atomic_dict[h] = []\n", + " atomic_dict[h].append((r, t))\n", + " \n", + " # split ID/OOD\n", + " OOD_ratio = 0.05\n", + " OOD_facts, ID_facts = split(atomics, round(len(atomics)*OOD_ratio)) # randomly\n", + " OOD_facts, ID_facts = set(OOD_facts), set(ID_facts)\n", + "\n", + " id_atomic_facts = [form_items([h, r], t) for (h,r,t) in ID_facts]\n", + " ood_atomic_facts = [form_items([h, r], t) for (h,r,t) in OOD_facts]\n", + "\n", + " train_2hop_ii, test_2hop_ii, test_2hop_io, test_2hop_oi, test_2hop_oo = [], [], [], [], []\n", + " \n", + " for ent in tqdm(entities, desc=\"2-hop: \"):\n", + " for (r1, b) in atomic_dict[ent]:\n", + " for (r2, t) in atomic_dict[b]:\n", + " if (ent, r1, b) in ID_facts and (b, r2, t) in ID_facts:\n", + " if np.random.uniform() > 0.05:\n", + " train_2hop_ii.append(form_items([ent, r1, r2], t))\n", + " else:\n", + " test_2hop_ii.append(form_items([ent, r1, r2], t))\n", + " \n", + " elif (ent, r1, b) in ID_facts and (b, r2, t) in OOD_facts:\n", + " test_2hop_io.append(form_items([ent, r1, r2], t))\n", + " \n", + " elif (ent, r1, b) in OOD_facts and (b, r2, t) in ID_facts:\n", + " test_2hop_oi.append(form_items([ent, r1, r2], t))\n", + " \n", + " elif (ent, r1, b) in OOD_facts and (b, r2, t) in OOD_facts:\n", + " test_2hop_oo.append(form_items([ent, r1, r2], t))\n", + "\n", + " return (\n", + " entities, relations, # vocab\n", + " id_atomic_facts, ood_atomic_facts,\n", + " \n", + " # 2-hop\n", + " train_2hop_ii, # train\n", + " test_2hop_ii, test_2hop_io, test_2hop_oi, test_2hop_oo, # test\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a5af1d81", + "metadata": {}, + "outputs": [], + "source": [ + "NUM_ENTITY_IN = 2000\n", + "NUM_RELATION = 200\n", + "\n", + "(\n", + " entities, relations, # vocab\n", + " id_atomic_facts, ood_atomic_facts,\n", + " \n", + " # 2-hop\n", + " train_2hop_ii, # train\n", + " test_2hop_ii, test_2hop_io, test_2hop_oi, test_2hop_oo, # test\n", + ") = build_base_dataset(NUM_ENTITY_IN, NUM_RELATION)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "6fb49399", + "metadata": {}, + "outputs": [], + "source": [ + "vocab = []\n", + "vocab = vocab + entities + relations\n", + "# special tokens\n", + "# actually only \"\" used as \n", + "vocab = vocab + [\"\", \"\", \"\", \"\", \"\", \"\"]\n", + "\n", + "# For predict_during_training: cut test group\n", + "test_size = 3000\n", + "# atomic\n", + "test_id_atomic = choose(id_atomic_facts, test_size)\n", + "test_ood_atomic = choose(ood_atomic_facts, test_size)\n", + "# 2-hop\n", + "test_2hop_ii = choose(test_2hop_ii, test_size)\n", + "test_2hop_io = choose(test_2hop_io, test_size)\n", + "test_2hop_oi = choose(test_2hop_oi, test_size)\n", + "test_2hop_oo = choose(test_2hop_oo, test_size)\n", + "\n", + "train_atomics = id_atomic_facts + ood_atomic_facts\n", + "\n", + "phi = 7.2 # Train-II / ID Triples\n", + "train_2hop_ii = choose(train_2hop_ii, phi * len(id_atomic_facts))\n", + "\n", + "dataset_name = \"base_configuration.{}.{}.{}\".format(NUM_ENTITY_IN, NUM_RELATION, phi)\n", + "os.makedirs(\"../data/{}\".format(dataset_name), exist_ok=True)\n", + "\n", + "probes = []\n", + "\n", + "for item in test_id_atomic:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"ID Triples\"\n", + "\n", + "for item in test_ood_atomic:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"OOD Triples\"\n", + "\n", + "for item in choose(train_2hop_ii, test_size):\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Train-II'\n", + "\n", + "for item in test_2hop_ii:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"Test-II\"\n", + "\n", + "for item in test_2hop_io:\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Test-IO'\n", + "\n", + "for item in test_2hop_oi:\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Test-OI'\n", + "\n", + "for item in test_2hop_oo:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"Test-OO\"\n", + "\n", + "with open(\"../data/{}/train.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(train_atomics + train_2hop_ii, f)\n", + "\n", + "# evaluate_during_training\n", + "with open(\"../data/{}/valid.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(test_2hop_oo, f)\n", + "\n", + "# predict_during_training\n", + "with open(\"../data/{}/test.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(probes, f)\n", + "\n", + "# add vocab\n", + "with open(\"../data/{}/vocab.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(vocab, f)" + ] + }, + { + "cell_type": "markdown", + "id": "ec8beb4f", + "metadata": {}, + "source": [ + "# 3-hop" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "77585c5e", + "metadata": {}, + "outputs": [], + "source": [ + "def build_3_hop(num_entities, num_relations, out_degree=10):\n", + "\n", + " entities = [\"\".format(i) for i in range(num_entities)]\n", + " ind2entity, entity2ind = build_dicts(entities)\n", + "\n", + " relations = [\"\".format(i) for i in range(num_relations)]\n", + " ind2relation, relation2ind = build_dicts(relations)\n", + "\n", + " atomic_dict = dict() # {h1: [(r1, t1), (r2, t2), ...], ...}\n", + " atomic_facts = [] # [{\"input_text\": \"...\", \"target_text\": \"...\"}, ...]\n", + " atomics = [] # [(h1,r1,t1), (h2,r2,t2), ...]\n", + "\n", + " for i in tqdm(range(num_entities)):\n", + " # for each subject entity, randomly select some outgoing relations to some random object entity\n", + " num_rows = out_degree\n", + " selected_rows = np.random.choice(num_relations, size=num_rows, replace=False).tolist()\n", + " for row_idx in selected_rows:\n", + " col_idx = np.random.randint(num_entities) # pick some random tail entity for each selected (h,r)\n", + " h,r,t = ind2entity[i], ind2relation[row_idx], ind2entity[col_idx] # h and t might be same here\n", + " atomic_facts.append(form_items([h, r], t))\n", + " atomics.append((h,r,t))\n", + " if h not in atomic_dict:\n", + " atomic_dict[h] = []\n", + " atomic_dict[h].append((r, t))\n", + " \n", + " # split ID/OOD\n", + " OOD_ratio = 0.2 # This ratio can't be too low in 3-hop dataset\n", + " OOD_facts, ID_facts = split(atomics, round(len(atomics)*OOD_ratio)) # randomly\n", + " OOD_facts, ID_facts = set(OOD_facts), set(ID_facts)\n", + "\n", + " id_atomic_facts = [form_items([h, r], t) for (h,r,t) in ID_facts]\n", + " ood_atomic_facts = [form_items([h, r], t) for (h,r,t) in OOD_facts]\n", + " \n", + " (\n", + " train_3hop_iii, \n", + " test_3hop_iii, test_3hop_iio, test_3hop_ioi, test_3hop_ioo, # startwiths i\n", + " test_3hop_oii, test_3hop_oio, test_3hop_ooi, test_3hop_ooo, # startwiths o\n", + " ) = [], [], [], [], [], [], [], [], []\n", + "\n", + " for ent in tqdm(entities, desc=\"3-hop: \"):\n", + " for (r1, b1) in atomic_dict[ent]:\n", + " for (r2, b2) in atomic_dict[b1]:\n", + " for (r3, t) in atomic_dict[b2]:\n", + " if (ent, r1, b1) in ID_facts and (b1, r2, b2) in ID_facts and (b2, r3, t) in ID_facts:\n", + " if np.random.uniform() > 0.05:\n", + " # 1000000 * 0.8 * 0.8 * 0.8 * 0.95 = 486400\n", + " train_3hop_iii.append(form_items([ent, r1, r2, r3], t))\n", + " else:\n", + " # 1000000 * 0.8 * 0.8 * 0.8 * 0.05 = 25600\n", + " test_3hop_iii.append(form_items([ent, r1, r2, r3], t))\n", + " \n", + " # 1000000 * 0.8 * 0.8 * 0.2 = 128000\n", + " elif (ent, r1, b1) in ID_facts and (b1, r2, b2) in ID_facts and (b2, r3, t) in OOD_facts:\n", + " test_3hop_iio.append(form_items([ent, r1, r2, r3], t))\n", + "\n", + " # 1000000 * 0.8 * 0.2 * 0.8 = 128000\n", + " elif (ent, r1, b1) in ID_facts and (b1, r2, b2) in OOD_facts and (b2, r3, t) in ID_facts:\n", + " test_3hop_ioi.append(form_items([ent, r1, r2, r3], t))\n", + "\n", + " # 1000000 * 0.8 * 0.2 * 0.2 = 32000\n", + " elif (ent, r1, b1) in ID_facts and (b1, r2, b2) in OOD_facts and (b2, r3, t) in OOD_facts:\n", + " test_3hop_ioo.append(form_items([ent, r1, r2, r3], t))\n", + " \n", + " # 1000000 * 0.2 * 0.8 * 0.8 = 128000\n", + " elif (ent, r1, b1) in OOD_facts and (b1, r2, b2) in ID_facts and (b2, r3, t) in ID_facts:\n", + " test_3hop_oii.append(form_items([ent, r1, r2, r3], t))\n", + " \n", + " # 1000000 * 0.2 * 0.8 * 0.2 = 32000\n", + " elif (ent, r1, b1) in OOD_facts and (b1, r2, b2) in ID_facts and (b2, r3, t) in OOD_facts:\n", + " test_3hop_oio.append(form_items([ent, r1, r2, r3], t))\n", + " \n", + " # 1000000 * 0.2 * 0.2 * 0.8 = 32000\n", + " elif (ent, r1, b1) in OOD_facts and (b1, r2, b2) in OOD_facts and (b2, r3, t) in ID_facts:\n", + " test_3hop_ooi.append(form_items([ent, r1, r2, r3], t))\n", + " \n", + " # 1000000 * 0.2 * 0.2 * 0.2 = 8000\n", + " elif (ent, r1, b1) in OOD_facts and (b1, r2, b2) in OOD_facts and (b2, r3, t) in OOD_facts:\n", + " test_3hop_ooo.append(form_items([ent, r1, r2, r3], t))\n", + "\n", + "\n", + " return (\n", + " entities, relations, # vocab\n", + " id_atomic_facts, ood_atomic_facts,\n", + "\n", + " # 3-hop\n", + " train_3hop_iii, # train\n", + " test_3hop_iii, test_3hop_iio, test_3hop_ioi, test_3hop_ioo,\n", + " test_3hop_oii, test_3hop_oio, test_3hop_ooi, test_3hop_ooo, # test\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c7259c86", + "metadata": {}, + "outputs": [], + "source": [ + "NUM_ENTITY_IN = 1000\n", + "NUM_RELATION = 100\n", + "\n", + "(\n", + " entities, relations, # vocab\n", + " id_atomic_facts, ood_atomic_facts,\n", + "\n", + " # 3-hop\n", + " train_3hop_iii, # train\n", + " test_3hop_iii, test_3hop_iio, test_3hop_ioi, test_3hop_ioo,\n", + " test_3hop_oii, test_3hop_oio, test_3hop_ooi, test_3hop_ooo, # test\n", + ") = build_3_hop(NUM_ENTITY_IN, NUM_RELATION)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "bada93b7", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "vocab size: 1106\n" + ] + } + ], + "source": [ + "vocab = []\n", + "vocab = vocab + entities + relations\n", + "# special tokens\n", + "# actually only \"\" used as \n", + "vocab = vocab + [\"\", \"\", \"\", \"\", \"\", \"\"]\n", + "\n", + "print(\"vocab size:\", len(vocab))\n", + "\n", + "# For predict_during_training: cut test group\n", + "test_size = 1000\n", + "# atomic\n", + "test_id_atomic = choose(id_atomic_facts, test_size)\n", + "test_ood_atomic = choose(ood_atomic_facts, test_size)\n", + "\n", + "# 3-hop\n", + "test_3hop_iii = choose(test_3hop_iii, test_size)\n", + "test_3hop_iio = choose(test_3hop_iio, test_size)\n", + "test_3hop_ioi = choose(test_3hop_ioi, test_size)\n", + "test_3hop_ioo = choose(test_3hop_ioo, test_size)\n", + "test_3hop_oii = choose(test_3hop_oii, test_size)\n", + "test_3hop_oio = choose(test_3hop_oio, test_size)\n", + "test_3hop_ooi = choose(test_3hop_ooi, test_size)\n", + "test_3hop_ooo = choose(test_3hop_ooo, test_size)\n", + "\n", + "train_atomics = id_atomic_facts + ood_atomic_facts\n", + "\n", + "phi = 12 # Train-III / ID Triples\n", + "dataset_name = \"3hop.{}.{}.{}\".format(NUM_ENTITY_IN, NUM_RELATION, phi)\n", + "os.makedirs(\"../data/{}\".format(dataset_name), exist_ok=True)\n", + "\n", + "train_3hop_iii_cut = choose(train_3hop_iii, round(phi * len(train_atomics)))\n", + "\n", + "probes = []\n", + "\n", + "for item in test_id_atomic:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"ID Triples\"\n", + "\n", + "for item in test_ood_atomic:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"OOD Triples\"\n", + "\n", + "for item in choose(train_3hop_iii_cut, test_size):\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Train-III'\n", + "\n", + "for item in test_3hop_iii:\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Test-III'\n", + "\n", + "for item in test_3hop_iio:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"Test-IIO\"\n", + "\n", + "for item in test_3hop_ioi:\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Test-IOI'\n", + "\n", + "for item in test_3hop_ioo:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"Test-IOO\"\n", + "\n", + "for item in test_3hop_oii:\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Test-OII'\n", + "\n", + "for item in test_3hop_oio:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"Test-OIO\"\n", + "\n", + "for item in test_3hop_ooi:\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Test-OOI'\n", + "\n", + "for item in test_3hop_ooo:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"Test-OOO\"\n", + "\n", + "with open(\"../data/{}/train.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(train_atomics + train_3hop_iii_cut, f)\n", + "\n", + "# evaluate_during_training\n", + "with open(\"../data/{}/valid.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(test_3hop_ooo, f)\n", + "\n", + "# predict_during_training\n", + "with open(\"../data/{}/test.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(probes, f)\n", + "\n", + "# add vocab\n", + "with open(\"../data/{}/vocab.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(vocab, f)" + ] + }, + { + "cell_type": "markdown", + "id": "3f070b54", + "metadata": {}, + "source": [ + "# Base Configuration with Second-Hop Ablation" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "8a8e9130", + "metadata": {}, + "outputs": [], + "source": [ + "def build_second_hop_ablation(num_entities, num_relations, out_degree=20):\n", + " \n", + " entities = [\"\".format(i) for i in range(num_entities)]\n", + " ind2entity, entity2ind = build_dicts(entities)\n", + "\n", + " relations = [\"\".format(i) for i in range(num_relations)]\n", + " ind2relation, relation2ind = build_dicts(relations)\n", + "\n", + " atomic_dict = dict() # {h1: [(r1, t1), (r2, t2), ...], ...}\n", + " atomic_facts = [] # [{\"input_text\": \"...\", \"target_text\": \"...\"}, ...]\n", + " atomics = [] # [(h1,r1,t1), (h2,r2,t2), ...]\n", + "\n", + " for i in tqdm(range(num_entities)):\n", + " # for each subject entity, randomly select some outgoing relations to some random object entity\n", + " num_rows = out_degree\n", + " selected_rows = np.random.choice(num_relations, size=num_rows, replace=False).tolist()\n", + " for row_idx in selected_rows:\n", + " col_idx = np.random.randint(num_entities) # pick some random tail entity for each selected (h,r)\n", + " h,r,t = ind2entity[i], ind2relation[row_idx], ind2entity[col_idx] # h and t might be same here\n", + " atomic_facts.append(form_items([h, r], t))\n", + " atomics.append((h,r,t))\n", + " if h not in atomic_dict:\n", + " atomic_dict[h] = []\n", + " atomic_dict[h].append((r, t))\n", + " \n", + " # split ID/OOD\n", + " OOD_ratio = 0.05\n", + " OOD_facts, ID_facts = split(atomics, round(len(atomics)*OOD_ratio)) # randomly\n", + " OOD_facts = set(OOD_facts)\n", + "\n", + " second_hop_restricted_ratio = 0.05\n", + " second_hop_restricted_id, normal_id = split(ID_facts, round(len(ID_facts) * second_hop_restricted_ratio))\n", + " second_hop_restricted_id, normal_id = set(second_hop_restricted_id), set(normal_id)\n", + " ID_facts = set(ID_facts)\n", + "\n", + " id_atomic_facts = [form_items([h, r], t) for (h,r,t) in ID_facts]\n", + " ood_atomic_facts = [form_items([h, r], t) for (h,r,t) in OOD_facts]\n", + "\n", + " # We don't involve OOD here\n", + " train_2hop_ii, test_2hop_ii, test_2hop_second_hop_restricted = [], [], []\n", + " \n", + " for ent in tqdm(entities, desc=\"2-hop: \"):\n", + " for (r1, b) in atomic_dict[ent]:\n", + " for (r2, t) in atomic_dict[b]:\n", + " if (ent, r1, b) in OOD_facts or (b, r2, t) in OOD_facts:\n", + " continue\n", + "\n", + " if (b, r2, t) in second_hop_restricted_id:\n", + " # (ent, r1, b) from second_hop_restricted_id or normal_id; (b, r2, t) from second_hop_restricted_id\n", + " test_2hop_second_hop_restricted.append(form_items([ent, r1, r2], t))\n", + " else:\n", + " # (ent, r1, b) from second_hop_restricted_id or normal_id; (b, r2, t) from normal_id\n", + " if np.random.uniform() > 0.005:\n", + " train_2hop_ii.append(form_items([ent, r1, r2], t))\n", + " else:\n", + " test_2hop_ii.append(form_items([ent, r1, r2], t))\n", + "\n", + " return (\n", + " entities, relations, # vocab\n", + " id_atomic_facts, ood_atomic_facts,\n", + " \n", + " # 2-hop\n", + " train_2hop_ii, # train\n", + " test_2hop_ii, test_2hop_second_hop_restricted, # test\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "825f8c4f", + "metadata": {}, + "outputs": [], + "source": [ + "NUM_ENTITY_IN = 2000\n", + "NUM_RELATION = 200\n", + "\n", + "(\n", + " entities, relations, # vocab\n", + " id_atomic_facts, ood_atomic_facts,\n", + " \n", + " # 2-hop\n", + " train_2hop_ii, # train\n", + " test_2hop_ii, test_2hop_second_hop_restricted, # test\n", + ") = build_second_hop_ablation(NUM_ENTITY_IN, NUM_RELATION)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "d6e0f3c8", + "metadata": {}, + "outputs": [], + "source": [ + "vocab = []\n", + "vocab = vocab + entities + relations\n", + "# special tokens\n", + "# actually only \"\" used as \n", + "vocab = vocab + [\"\", \"\", \"\", \"\", \"\", \"\"]\n", + "\n", + "# For predict_during_training: cut test group\n", + "test_size = 3000\n", + "# atomic\n", + "test_id_atomic = choose(id_atomic_facts, test_size)\n", + "test_ood_atomic = choose(ood_atomic_facts, test_size)\n", + "# 2-hop\n", + "test_2hop_ii = choose(test_2hop_ii, test_size)\n", + "test_2hop_second_hop_restricted = choose(test_2hop_second_hop_restricted, test_size)\n", + "\n", + "train_atomics = id_atomic_facts + ood_atomic_facts\n", + "\n", + "phi = 7.2 # Train-II / ID Triples\n", + "train_2hop_ii = choose(train_2hop_ii, phi * len(id_atomic_facts))\n", + "\n", + "dataset_name = \"second_hop_ablation_configuration.{}.{}.{}\".format(NUM_ENTITY_IN, NUM_RELATION, phi)\n", + "os.makedirs(\"../data/{}\".format(dataset_name), exist_ok=True)\n", + "\n", + "probes = []\n", + "\n", + "for item in test_id_atomic:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"ID Triples\"\n", + "\n", + "for item in test_ood_atomic:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"OOD Triples\"\n", + "\n", + "for item in choose(train_2hop_ii, test_size):\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Train-II'\n", + "\n", + "for item in test_2hop_ii:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"Test-II\"\n", + "\n", + "for item in test_2hop_second_hop_restricted:\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Test-II-SR'\n", + "\n", + "\n", + "with open(\"../data/{}/train.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(train_atomics + train_2hop_ii, f)\n", + "\n", + "# evaluate_during_training\n", + "with open(\"../data/{}/valid.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(test_2hop_oo, f)\n", + "\n", + "# predict_during_training\n", + "with open(\"../data/{}/test.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(probes, f)\n", + "\n", + "# add vocab\n", + "with open(\"../data/{}/vocab.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(vocab, f)" + ] + }, + { + "cell_type": "markdown", + "id": "897e2597", + "metadata": {}, + "source": [ + "# Unanchored OOD Configuration & Decoding Preference Configuration\n", + "  without ID Triples" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1eba2359", + "metadata": {}, + "outputs": [], + "source": [ + "NUM_ENTITY_IN = 2000\n", + "NUM_RELATION = 200\n", + "\n", + "# Reuse the build_base_dataset functions\n", + "(\n", + " entities, relations, # vocab\n", + " id_atomic_facts, ood_atomic_facts,\n", + " \n", + " # 2-hop\n", + " train_2hop_ii, # train\n", + " test_2hop_ii, test_2hop_io, test_2hop_oi, test_2hop_oo, # test\n", + ") = build_base_dataset(NUM_ENTITY_IN, NUM_RELATION)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "67376197", + "metadata": {}, + "outputs": [], + "source": [ + "vocab = []\n", + "vocab = vocab + entities + relations\n", + "# special tokens\n", + "# actually only \"\" used as \n", + "vocab = vocab + [\"\", \"\", \"\", \"\", \"\", \"\"]\n", + "\n", + "# For predict_during_training: cut test group\n", + "test_size = 3000\n", + "# atomic\n", + "test_id_atomic = choose(id_atomic_facts, test_size)\n", + "test_ood_atomic = choose(ood_atomic_facts, test_size)\n", + "# 2-hop\n", + "test_2hop_ii = choose(test_2hop_ii, test_size)\n", + "test_2hop_io = choose(test_2hop_io, test_size)\n", + "test_2hop_oi = choose(test_2hop_oi, test_size)\n", + "test_2hop_oo = choose(test_2hop_oo, test_size)\n", + "\n", + "# ensure that ID triples do not appear in the training set\n", + "train_atomics = ood_atomic_facts\n", + "\n", + "phi = 7.2 # Train-II / ID Triples\n", + "train_2hop_ii = choose(train_2hop_ii, phi * len(id_atomic_facts))\n", + "\n", + "dataset_name = \"without_id.{}.{}.{}\".format(NUM_ENTITY_IN, NUM_RELATION, phi)\n", + "os.makedirs(\"../data/{}\".format(dataset_name), exist_ok=True)\n", + "\n", + "probes = []\n", + "\n", + "for item in test_id_atomic:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"ID Triples\"\n", + "\n", + "for item in test_ood_atomic:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"OOD Triples\"\n", + "\n", + "for item in choose(train_2hop_ii, test_size):\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Train-II'\n", + "\n", + "for item in test_2hop_ii:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"Test-II\"\n", + "\n", + "for item in test_2hop_io:\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Test-IO'\n", + "\n", + "for item in test_2hop_oi:\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Test-OI'\n", + "\n", + "for item in test_2hop_oo:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"Test-OO\"\n", + "\n", + "with open(\"../data/{}/train.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(train_atomics + train_2hop_ii, f)\n", + "\n", + "# evaluate_during_training\n", + "with open(\"../data/{}/valid.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(test_2hop_oo, f)\n", + "\n", + "# predict_during_training\n", + "with open(\"../data/{}/test.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(probes, f)\n", + "\n", + "# add vocab\n", + "with open(\"../data/{}/vocab.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(vocab, f)" + ] + }, + { + "cell_type": "markdown", + "id": "a755d4d5", + "metadata": {}, + "source": [ + "# Held-out ID Triple Configuration" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "0cc2bbae", + "metadata": {}, + "outputs": [], + "source": [ + "def build_held_out_id(num_entities, num_relations, out_degree=20):\n", + " \n", + " entities = [\"\".format(i) for i in range(num_entities)]\n", + " ind2entity, entity2ind = build_dicts(entities)\n", + "\n", + " relations = [\"\".format(i) for i in range(num_relations)]\n", + " ind2relation, relation2ind = build_dicts(relations)\n", + "\n", + " atomic_dict = dict() # {h1: [(r1, t1), (r2, t2), ...], ...}\n", + " atomic_facts = [] # [{\"input_text\": \"...\", \"target_text\": \"...\"}, ...]\n", + " atomics = [] # [(h1,r1,t1), (h2,r2,t2), ...]\n", + "\n", + " for i in tqdm(range(num_entities)):\n", + " # for each subject entity, randomly select some outgoing relations to some random object entity\n", + " num_rows = out_degree\n", + " selected_rows = np.random.choice(num_relations, size=num_rows, replace=False).tolist()\n", + " for row_idx in selected_rows:\n", + " col_idx = np.random.randint(num_entities) # pick some random tail entity for each selected (h,r)\n", + " h,r,t = ind2entity[i], ind2relation[row_idx], ind2entity[col_idx] # h and t might be same here\n", + " atomic_facts.append(form_items([h, r], t))\n", + " atomics.append((h,r,t))\n", + " if h not in atomic_dict:\n", + " atomic_dict[h] = []\n", + " atomic_dict[h].append((r, t))\n", + " \n", + " # split ID/OOD\n", + " OOD_ratio = 0.05\n", + " OOD_facts, ID_facts = split(atomics, round(len(atomics)*OOD_ratio)) # randomly\n", + " OOD_facts = set(OOD_facts)\n", + "\n", + " held_out_ratio = 0.05\n", + " held_out_id, retained_id = split(ID_facts, round(len(ID_facts) * held_out_ratio))\n", + " held_out_id, retained_id = set(held_out_id), set(retained_id)\n", + "\n", + " ID_facts = set(ID_facts)\n", + "\n", + " held_out_id_atomic_facts = [form_items([h, r], t) for (h,r,t) in held_out_id]\n", + " retained_id_atomic_facts = [form_items([h, r], t) for (h,r,t) in retained_id]\n", + " ood_atomic_facts = [form_items([h, r], t) for (h,r,t) in OOD_facts]\n", + "\n", + " train_2hop_ii, test_2hop_ii, test_2hop_io, test_2hop_oi, test_2hop_oo = [], [], [], [], []\n", + " \n", + " for ent in tqdm(entities, desc=\"2-hop: \"):\n", + " for (r1, b) in atomic_dict[ent]:\n", + " for (r2, t) in atomic_dict[b]:\n", + " if (ent, r1, b) in ID_facts and (b, r2, t) in ID_facts:\n", + " if np.random.uniform() > 0.05:\n", + " train_2hop_ii.append(form_items([ent, r1, r2], t))\n", + " else:\n", + " test_2hop_ii.append(form_items([ent, r1, r2], t))\n", + " \n", + " elif (ent, r1, b) in ID_facts and (b, r2, t) in OOD_facts:\n", + " test_2hop_io.append(form_items([ent, r1, r2], t))\n", + " \n", + " elif (ent, r1, b) in OOD_facts and (b, r2, t) in ID_facts:\n", + " test_2hop_oi.append(form_items([ent, r1, r2], t))\n", + " \n", + " elif (ent, r1, b) in OOD_facts and (b, r2, t) in OOD_facts:\n", + " test_2hop_oo.append(form_items([ent, r1, r2], t))\n", + "\n", + " return (\n", + " entities, relations, # vocab\n", + " held_out_id_atomic_facts, retained_id_atomic_facts, ood_atomic_facts,\n", + " \n", + " # 2-hop\n", + " train_2hop_ii, # train\n", + " test_2hop_ii, test_2hop_io, test_2hop_oi, test_2hop_oo, # test\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8a214fd8", + "metadata": {}, + "outputs": [], + "source": [ + "NUM_ENTITY_IN = 2000\n", + "NUM_RELATION = 200\n", + "\n", + "(\n", + " entities, relations, # vocab\n", + " held_out_id_atomic_facts, retained_id_atomic_facts, ood_atomic_facts,\n", + " \n", + " # 2-hop\n", + " train_2hop_ii, # train\n", + " test_2hop_ii, test_2hop_io, test_2hop_oi, test_2hop_oo, # test\n", + ") = build_held_out_id(NUM_ENTITY_IN, NUM_RELATION)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "ab950a2e", + "metadata": {}, + "outputs": [], + "source": [ + "vocab = []\n", + "vocab = vocab + entities + relations\n", + "# special tokens\n", + "# actually only \"\" used as \n", + "vocab = vocab + [\"\", \"\", \"\", \"\", \"\", \"\"]\n", + "\n", + "# For predict_during_training: cut test group\n", + "test_size = 3000\n", + "# atomic\n", + "test_held_out_id_atomic = choose(held_out_id_atomic_facts, test_size)\n", + "test_retained_id_atomic = choose(retained_id_atomic_facts, test_size)\n", + "test_ood_atomic = choose(ood_atomic_facts, test_size)\n", + "# 2-hop\n", + "test_2hop_ii = choose(test_2hop_ii, test_size)\n", + "test_2hop_io = choose(test_2hop_io, test_size)\n", + "test_2hop_oi = choose(test_2hop_oi, test_size)\n", + "test_2hop_oo = choose(test_2hop_oo, test_size)\n", + "\n", + "# ensure that held_out_id_atomic_facts do not appear in the training set\n", + "train_atomics = retained_id_atomic_facts + ood_atomic_facts\n", + "\n", + "phi = 7.2 # Train-II / ID Triples\n", + "train_2hop_ii = choose(train_2hop_ii, phi * len(retained_id_atomic_facts + held_out_id_atomic_facts))\n", + "\n", + "dataset_name = \"held_out_id_configuration.{}.{}.{}\".format(NUM_ENTITY_IN, NUM_RELATION, phi)\n", + "os.makedirs(\"../data/{}\".format(dataset_name), exist_ok=True)\n", + "\n", + "probes = []\n", + "\n", + "for item in test_held_out_id_atomic:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"Held-out ID Triples\"\n", + "\n", + "for item in test_retained_id_atomic:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"Retained ID Triples\"\n", + "\n", + "for item in test_ood_atomic:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"OOD Triples\"\n", + "\n", + "for item in choose(train_2hop_ii, test_size):\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Train-II'\n", + "\n", + "for item in test_2hop_ii:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"Test-II\"\n", + "\n", + "for item in test_2hop_io:\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Test-IO'\n", + "\n", + "for item in test_2hop_oi:\n", + " probes.append(deepcopy(item))\n", + " probes[-1]['type'] = 'Test-OI'\n", + "\n", + "for item in test_2hop_oo:\n", + " probes.append(deepcopy(item))\n", + " probes[-1][\"type\"] = \"Test-OO\"\n", + "\n", + "with open(\"../data/{}/train.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(train_atomics + train_2hop_ii, f)\n", + "\n", + "# evaluate_during_training\n", + "with open(\"../data/{}/valid.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(test_2hop_oo, f)\n", + "\n", + "# predict_during_training\n", + "with open(\"../data/{}/test.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(probes, f)\n", + "\n", + "# add vocab\n", + "with open(\"../data/{}/vocab.json\".format(dataset_name), \"w\", encoding='utf-8') as f:\n", + " json.dump(vocab, f)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "latent", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.19" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/logit_lens.ipynb b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/logit_lens.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..40757edaeab961087a49fcee932281084dc70d72 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/logit_lens.ipynb @@ -0,0 +1,201 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "3e5ae1a2", + "metadata": {}, + "outputs": [], + "source": [ + "from transformers import GPT2Config, GPT2LMHeadModel, GPT2Tokenizer\n", + "import torch\n", + "\n", + "model_path1 = \"phase_I_model_path\"\n", + "model_path2 = \"phase_II_model_path\"\n", + "model_path3 = \"phase_III_model_path\"\n", + "\n", + "device = \"cuda:0\"\n", + "\n", + "tokenizer = GPT2Tokenizer.from_pretrained(model_path1)\n", + "tokenizer.padding_side = \"left\"\n", + "tokenizer.pad_token = tokenizer.eos_token\n", + "tokenizer.pad_token_id = tokenizer.eos_token_id\n", + "\n", + "model1 = GPT2LMHeadModel.from_pretrained(model_path1).to(device)\n", + "model2 = GPT2LMHeadModel.from_pretrained(model_path2).to(device)\n", + "model3 = GPT2LMHeadModel.from_pretrained(model_path3).to(device)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7ab9f3d1", + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "with open('../data/base_configuration.2000.200.7.2/test.json', 'r') as f:\n", + " datas = json.load(f)\n", + "\n", + "# queries and answers(e2)\n", + "id_queries = [] # [(query, e2), ...]\n", + "ood_queries = []\n", + "\n", + "for data in datas: \n", + " if data[\"type\"] == \"OOD Triples\":\n", + " e1, r, e2 = data[\"target_text\"].strip('<>').split('><')[:-1]\n", + " ood_queries.append((data[\"input_text\"], f\"<{e2}>\"))\n", + " if data[\"type\"] == \"ID Triples\":\n", + " e1, r, e2 = data[\"target_text\"].strip('<>').split('><')[:-1]\n", + " id_queries.append((data[\"input_text\"], f\"<{e2}>\"))" + ] + }, + { + "cell_type": "markdown", + "id": "d57b3d5b", + "metadata": {}, + "source": [ + "### Immediate probing " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b5c3d760", + "metadata": {}, + "outputs": [], + "source": [ + "import torch.nn.functional as F\n", + "from tqdm import tqdm\n", + "\n", + "# TODO: change the model and query type\n", + "model = model3\n", + "queries = ood_queries\n", + "\n", + "word_embedding = model.lm_head.weight.data\n", + "model.config.pad_token_id = model.config.eos_token_id\n", + "\n", + "correct_cnt = 0\n", + "\n", + "# layer 5 at r1 positon\n", + "target_token_index = 1\n", + "target_layer = 5\n", + "\n", + "for query, target in tqdm(queries):\n", + " decoder_temp = tokenizer([query], return_tensors=\"pt\", padding=True)\n", + " decoder_input_ids, decoder_attention_mask = decoder_temp[\"input_ids\"], decoder_temp[\"attention_mask\"]\n", + " decoder_input_ids, decoder_attention_mask = decoder_input_ids.to(device), decoder_attention_mask.to(device)\n", + "\n", + " with torch.no_grad():\n", + " outputs = model(\n", + " input_ids=decoder_input_ids,\n", + " attention_mask=decoder_attention_mask,\n", + " output_hidden_states=True\n", + " )\n", + "\n", + " all_hidden_states = outputs.hidden_states\n", + " word_embedding = model.lm_head.weight\n", + "\n", + " # decode\n", + " target_hidden_state = all_hidden_states[target_layer][:, target_token_index, :] # (batch_size, hidden_dim)\n", + " logits = torch.matmul(target_hidden_state, word_embedding.T) # (batch_size, vocab_size)\n", + " next_token = torch.argmax(logits, dim=-1) # (batch_size,)\n", + "\n", + " # check\n", + " if tokenizer.decode(next_token.item()) == target:\n", + " correct_cnt += 1\n", + "\n", + "print(correct_cnt / len(id_queries))" + ] + }, + { + "cell_type": "markdown", + "id": "8a252539", + "metadata": {}, + "source": [ + "### Full-run probing" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1f7fbf0f", + "metadata": {}, + "outputs": [], + "source": [ + "import torch.nn.functional as F\n", + "from tqdm import tqdm\n", + "\n", + "# TODO: change the model and query type\n", + "model = model3\n", + "queries = id_queries\n", + "\n", + "word_embedding = model.lm_head.weight.data\n", + "model.config.pad_token_id = model.config.eos_token_id\n", + "\n", + "target_query = queries[-1] # ramdom or fixed\n", + "\n", + "correct_cnt = 0\n", + "\n", + "# layer 5 at r1 positon\n", + "target_token_index = 1\n", + "target_layer = 5\n", + "\n", + "for query, target in tqdm(queries[:-1]):\n", + "\n", + " decoder_temp = tokenizer([query], return_tensors=\"pt\", padding=True)\n", + " decoder_input_ids, decoder_attention_mask = decoder_temp[\"input_ids\"], decoder_temp[\"attention_mask\"]\n", + " decoder_input_ids, decoder_attention_mask = decoder_input_ids.to(device), decoder_attention_mask.to(device)\n", + "\n", + " with torch.no_grad():\n", + " outputs1 = model(\n", + " input_ids=decoder_input_ids,\n", + " attention_mask=decoder_attention_mask,\n", + " output_hidden_states=True\n", + " )\n", + "\n", + " hidden_states_batch = outputs1.hidden_states # [1+num_layers, batch_size, seq_len, hidden_size]\n", + "\n", + " def hook_fn(module, input, output):\n", + " main_output = output[0].clone()\n", + " \n", + " main_output[0, target_token_index, :] = hidden_states_batch[target_layer][0, target_token_index, :]\n", + "\n", + " return (main_output,) + output[1:]\n", + "\n", + " handle = model.transformer.h[target_layer].register_forward_hook(hook_fn)\n", + "\n", + " decoder_temp = tokenizer([target_query], return_tensors=\"pt\", padding=True)\n", + " decoder_input_ids, decoder_attention_mask = decoder_temp[\"input_ids\"], decoder_temp[\"attention_mask\"]\n", + " target_decoder_input_ids, target_decoder_attention_mask = decoder_input_ids.to(device), decoder_attention_mask.to(device)\n", + "\n", + " with torch.no_grad():\n", + " outputs = model(\n", + " input_ids=target_decoder_input_ids,\n", + " attention_mask=target_decoder_attention_mask,\n", + " )\n", + "\n", + " handle.remove()\n", + "\n", + " # decode\n", + " logits = outputs.logits # [batch_size, seq_len, vocab_size]\n", + " predicted_token_ids = torch.argmax(logits, dim=-1) # [batch_size, seq_len]\n", + " decoded_text = tokenizer.batch_decode(predicted_token_ids, skip_special_tokens=True)\n", + " decoded_token = decoded_text[0].split()[1]\n", + "\n", + " # check\n", + " if decoded_token == target:\n", + " correct_cnt += 1\n", + "\n", + "print(correct_cnt / len(id_queries[:-1]))" + ] + } + ], + "metadata": { + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/training_dynamics.ipynb b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/training_dynamics.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bef9bfb4a069c52821c2a80e0930549ff5780a39 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/training_dynamics.ipynb @@ -0,0 +1,163 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "id": "3cedebcd", + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "import json\n", + "\n", + "def calculate_accuracy(file_path):\n", + " \"\"\"\n", + " :param file_path: the all_items.json under the checkpoint folder\n", + " :return: a dictionary with the accuracy of each type\n", + " \"\"\"\n", + " with open(file_path, 'r', encoding='utf-8') as file:\n", + " data = json.load(file)\n", + "\n", + " type_data = {}\n", + "\n", + " for entry in data:\n", + " entry_type = entry['type']\n", + " if entry_type not in type_data:\n", + " type_data[entry_type] = {'total': 0, 'correct': 0}\n", + " if entry['model_output'] == entry['target_text']:\n", + " type_data[entry_type]['correct'] += 1\n", + " type_data[entry_type]['total'] += 1\n", + "\n", + " results = {}\n", + " for entry_type, stats in type_data.items():\n", + " total = stats['total']\n", + " correct = stats['correct']\n", + " accuracy = (correct / total) * 100\n", + " results[entry_type] = {\n", + " 'total': total,\n", + " 'correct': correct,\n", + " 'accuracy': f\"{accuracy:.2f}%\"\n", + " }\n", + "\n", + " return results\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "aff462fd", + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from matplotlib.cm import get_cmap\n", + "\n", + "def extract_checkpoints_and_plot_results(base_dir, calculate_accuracy, max_checkpoint=None, xlog=True):\n", + " # get all checkpoint directories and sort them\n", + " checkpoint_dirs = sorted(\n", + " [d for d in os.listdir(base_dir) if d.startswith(\"checkpoint-\")],\n", + " key=lambda x: int(x.split('-')[1])\n", + " )\n", + " \n", + " # get the all_items.json file path\n", + " paths = []\n", + " checkpoints = []\n", + " for d in checkpoint_dirs:\n", + " checkpoint_num = int(d.split('-')[1])\n", + " if max_checkpoint is None or checkpoint_num <= max_checkpoint:\n", + " paths.append(os.path.join(base_dir, d, \"all_items.json\"))\n", + " checkpoints.append(checkpoint_num)\n", + "\n", + " # calculate accuracy for each checkpoint\n", + " results_list = [calculate_accuracy(test_file_path) for test_file_path in paths]\n", + "\n", + " accuracy_dict = {}\n", + "\n", + " for results in results_list:\n", + " for metric, values in results.items():\n", + " if metric not in accuracy_dict:\n", + " accuracy_dict[metric] = []\n", + " accuracy_dict[metric].append(float(values['accuracy'].strip('%')))\n", + "\n", + " plt.figure(figsize=(10, 6))\n", + "\n", + " num_metrics = len(accuracy_dict)\n", + " colormap = get_cmap(\"tab20\") # optional\n", + " colors = [colormap(i / num_metrics) for i in range(num_metrics)]\n", + "\n", + " for idx, (metric, accuracies) in enumerate(accuracy_dict.items()):\n", + " plt.plot(\n", + " checkpoints,\n", + " accuracies,\n", + " label=f'{metric.capitalize()}',\n", + " color=colors[idx],\n", + " linestyle='-',\n", + " linewidth=3\n", + " )\n", + "\n", + " plt.title('Model Accuracies at Different Checkpoints')\n", + " plt.xlabel('Checkpoints (Training Steps)')\n", + " plt.ylabel('Accuracy (%)')\n", + "\n", + " if xlog:\n", + " plt.xscale('log')\n", + " else:\n", + " plt.xticks(ticks=checkpoints)\n", + " \n", + " plt.ylim(0, 110)\n", + " plt.grid(True)\n", + "\n", + " plt.legend()\n", + "\n", + " plt.tight_layout()\n", + " plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "753eb803", + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAA90AAAJOCAYAAACqS2TfAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuNSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/xnp5ZAAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQVR4nOzde5xM9f8H8Nc5c937xd4vdjfWNbGuEUkIRblTfUMhJQnRl8qtxLdyi5JLv0jRBSXd3LvJvVAhFsuyi132vrM71/P7Y+xkzNmrnZm9vJ6Pxzxm5vP5zDnvmR1j3vO5CZIkSSAiIiIiIiKiSie6OwAiIiIiIiKimopJNxEREREREZGTMOkmIiIiIiIichIm3UREREREREROwqSbiIiIiIiIyEmYdBMRERERERE5CZNuIiIiIiIiIidh0k1ERERERETkJEy6iYiIiIiIiJyESTcRkRsJgoBZs2aV+3Hnz5+HIAhYs2ZNpcdUE/30008QBAE//fSTu0NxixEjRiA2NtauLC8vD6NGjUJYWBgEQcCECRMAAFevXsXAgQNRp04dCIKAxYsXuzzeqmDEiBHw9vZ2+Xnvu+8+3HnnnS4/b23/N0JE5ExMuomo1luzZg0EQYAgCNizZ49DvSRJiI6OhiAI6N27txsirBzff/89BEFAREQELBaLu8OhG06cOIFZs2bh/PnzZWo/a9Ys2/tVEAR4enqibt266NOnD1avXg29Xl+m48ydOxdr1qzBs88+i48//hhPPPEEAGDixInYtm0bpk2bho8//hg9e/as6FNzumXLlpX7h6fCwkIsWrQI7dq1g5+fH7RaLRo0aIBx48bh9OnTzgm0hktNTcWsWbNw9OhRd4dCRFQlKd0dABFRVaHVarF+/Xp07NjRrvznn3/GpUuXoNFo3BRZ5Vi3bh1iY2Nx/vx57N69G926dXN3SC5z7733oqCgAGq12t2hODhx4gRmz56N++67z6E3uiTvv/8+vL29odfrkZKSgm3btuGpp57C4sWL8e233yI6OtrWdtWqVQ4/tOzevRt33303Zs6c6VD+yCOPYPLkybf1vFxh2bJlCAoKwogRI8rU/tq1a+jZsyd+//139O7dG4899hi8vb1x6tQpfPbZZ1i5ciUMBoNzg66ibuffSGpqKmbPno3Y2Fi0aNGi8oMjIqrmmHQTEd3w4IMPYsOGDViyZAmUyn8/HtevX49WrVrh2rVrbozu9uTn5+Prr7/GvHnzsHr1aqxbt67KJt35+fnw8vKq1GOKogitVlupx3S3gQMHIigoyHZ/xowZWLduHYYNG4ZBgwZh//79tjqVSuXw+LS0NDRp0kS23N/fv9LiNJlMsFgsVeIHjxEjRuDIkSPYuHEjBgwYYFf3+uuv45VXXnFTZO5XE/+NEBFVFRxeTkR0w6OPPorr169jx44dtjKDwYCNGzfisccek31Mfn4+XnzxRURHR0Oj0aBhw4aYP38+JEmya6fX6zFx4kQEBwfDx8cHDz/8MC5duiR7zJSUFDz11FMIDQ2FRqNB06ZN8eGHH97Wc/vqq69QUFCAQYMGYejQofjyyy9RWFjo0K6wsBCzZs1CgwYNoNVqER4ejv79++Ps2bO2NhaLBe+88w6aNWsGrVaL4OBg9OzZE4cPHwZQ8nzzW+ewFw2VPnHiBB577DEEBATYRhr8+eefGDFiBO644w5otVqEhYXhqaeewvXr12Vfs5EjRyIiIgIajQZxcXF49tlnbb2Wxc1XPXDgAHr27Ak/Pz94enqic+fO+O233+za5ObmYsKECYiNjYVGo0FISAi6d++OP/74o8TX/MKFCxg7diwaNmwIDw8P1KlTB4MGDbIbRr5mzRoMGjQIANClSxfbkPGKzqt9/PHHMWrUKBw4cMDufXzznO6i1yIpKQnfffed7ZxF0ywkScJ7771nKy+SlZWFCRMm2N7r9evXx5tvvmnXg170t58/fz4WL16MevXqQaPR4MSJEwCAf/75BwMHDkRgYCC0Wi1at26NLVu22D2Hojh+++03TJo0CcHBwfDy8kK/fv2Qnp5uaxcbG4vjx4/j559/tsV63333FfvaHDhwAN999x1GjhzpkHADgEajwfz58x3KU1JS0LdvX3h7eyM4OBiTJ0+G2Wy2a2OxWLB48WI0bdoUWq0WoaGhGDNmDDIzMx2O98MPP6Bz587w8fGBr68v2rRpg/Xr1xcbNwBs374dnp6eePTRR2EymQBY/y2NGzcO69atQ8OGDaHVatGqVSv88ssvDo8/cuQIevXqBV9fX3h7e6Nr1652P8oA8v9GiuaXnzhxAl26dIGnpyciIyPx1ltv2T2uTZs2AIAnn3zS7v0EAImJiRgwYADCwsKg1WoRFRWFoUOHIjs7u8TnTERUk7Cnm4johtjYWLRv3x6ffvopevXqBcD6BTk7OxtDhw7FkiVL7NpLkoSHH34YP/74I0aOHIkWLVpg27ZtmDJlClJSUrBo0SJb21GjRuGTTz7BY489hg4dOmD37t146KGHHGK4evUq7r77btsX6uDgYPzwww8YOXIkcnJybItdlde6devQpUsXhIWFYejQoZg6dSq++eYbW8IHAGazGb1798auXbswdOhQvPDCC8jNzcWOHTvw999/o169egCAkSNHYs2aNejVqxdGjRoFk8mEX3/9Ffv370fr1q0rFN+gQYMQHx+PuXPn2n6w2LFjB86dO4cnn3wSYWFhOH78OFauXInjx49j//79toQwNTUVbdu2RVZWFp5++mk0atQIKSkp2LhxI3Q6XbE9rLt370avXr3QqlUrzJw5E6IoYvXq1bj//vvx66+/om3btgCAZ555Bhs3bsS4cePQpEkTXL9+HXv27MHJkyfRsmXLYp/ToUOHsHfvXgwdOhRRUVE4f/483n//fdx33304ceIEPD09ce+992L8+PFYsmQJXn75ZTRu3BgAbNcV8cQTT2DlypXYvn07unfv7lDfuHFjfPzxx5g4cSKioqLw4osvAgASEhJsc7u7d++OYcOG2R6j0+nQuXNnpKSkYMyYMahbty727t2LadOm4fLlyw6Lra1evRqFhYV4+umnodFoEBgYiOPHj+Oee+5BZGQkpk6dCi8vL3zxxRfo27cvNm3ahH79+tkd4/nnn0dAQABmzpyJ8+fPY/HixRg3bhw+//xzAMDixYvx/PPPw9vb29ZDHRoaWuzrUpTcF81dLwuz2YwePXqgXbt2mD9/Pnbu3IkFCxagXr16ePbZZ23txowZgzVr1uDJJ5/E+PHjkZSUhHfffRdHjhzBb7/9ZhtpsGbNGjz11FNo2rQppk2bBn9/fxw5cgRbt24t9oe9b7/9FgMHDsSQIUPw4YcfQqFQ2Op+/vlnfP755xg/fjw0Gg2WLVuGnj174uDBg7bF2I4fP45OnTrB19cXL730ElQqFVasWIH77rsPP//8M9q1a1fia5CZmYmePXuif//+GDx4MDZu3Ij//ve/aNasGXr16oXGjRvjtddew4wZM/D000+jU6dOAIAOHTrAYDCgR48e0Ov1eP755xEWFoaUlBR8++23yMrKgp+fX5n/FkRE1ZpERFTLrV69WgIgHTp0SHr33XclHx8fSafTSZIkSYMGDZK6dOkiSZIkxcTESA899JDtcZs3b5YASHPmzLE73sCBAyVBEKQzZ85IkiRJR48elQBIY8eOtWv32GOPSQCkmTNn2spGjhwphYeHS9euXbNrO3ToUMnPz88WV1JSkgRAWr16danP7+rVq5JSqZRWrVplK+vQoYP0yCOP2LX78MMPJQDSwoULHY5hsVgkSZKk3bt3SwCk8ePHF9umpNhufb4zZ86UAEiPPvqoQ9ui53qzTz/9VAIg/fLLL7ayYcOGSaIoSocOHSo2ph9//FECIP3444+28vj4eKlHjx62NkXnjIuLk7p3724r8/Pzk5577jmHY5dGLv59+/ZJAKS1a9fayjZs2GAXW2mKXrP09HTZ+szMTAmA1K9fP1vZ8OHDpZiYGLt2t76fiwBweL6vv/665OXlJZ0+fdqufOrUqZJCoZCSk5MlSfr3b+/r6yulpaXZte3atavUrFkzqbCw0FZmsVikDh06SPHx8bayon+P3bp1s/vbTJw4UVIoFFJWVpatrGnTplLnzp1lX4db9evXTwIgZWZmlqn98OHDJQDSa6+9ZleekJAgtWrVynb/119/lQBI69ats2u3detWu/KsrCzJx8dHateunVRQUGDX9ubn2blzZ6lp06aSJEnSpk2bJJVKJY0ePVoym812jwEgAZAOHz5sK7tw4YKk1Wrt/vZ9+/aV1Gq1dPbsWVtZamqq5OPjI9177722slv/jRTFcuv7Va/XS2FhYdKAAQNsZYcOHZL9N3/kyBEJgLRhwwaJiKg24/ByIqKbDB48GAUFBfj222+Rm5uLb7/9ttgeqO+//x4KhQLjx4+3K3/xxRchSRJ++OEHWzsADu1u7bWWJAmbNm1Cnz59IEkSrl27Zrv06NED2dnZpQ5plvPZZ59BFEW7IbWPPvoofvjhB7vhr5s2bUJQUBCef/55h2MU9Spv2rQJgiA4LL51c5uKeOaZZxzKPDw8bLcLCwtx7do13H333QBgex0sFgs2b96MPn36yPayFxfT0aNHkZiYiMceewzXr1+3vc75+fno2rUrfvnlF9uwaX9/fxw4cACpqanlek43x280GnH9+nXUr18f/v7+Ffo7llXRNle5ubmVdswNGzagU6dOCAgIsHtfduvWDWaz2WFI84ABAxAcHGy7n5GRgd27d2Pw4MHIzc21Pf769evo0aMHEhMTkZKSYneMp59+2u7v16lTJ5jNZly4cKFCzyEnJwcA4OPjU67H3fre7NSpE86dO2e7v2HDBvj5+aF79+52r02rVq3g7e2NH3/8EYB15EZubi6mTp3qMHda7n366aefYsiQIRgzZgxWrFgBUXT8yta+fXu0atXKdr9u3bp45JFHsG3bNpjNZpjNZmzfvh19+/bFHXfcYWsXHh6Oxx57DHv27LG9LsXx9vbGf/7zH9t9tVqNtm3b2r0GxSnqyd62bRt0Ol2p7YmIaioOLyciuklwcDC6deuG9evXQ6fTwWw2Y+DAgbJtL1y4gIiICIcv8UVDg4uSgwsXLkAURdvw7CINGza0u5+eno6srCysXLkSK1eulD1nWlpauZ/TJ598grZt2+L69eu2+dAJCQkwGAzYsGEDnn76aQDA2bNn0bBhQ7tF5G519uxZREREIDAwsNxxlCQuLs6hLCMjA7Nnz8Znn33m8LyL5oOmp6cjJyen3PsaJyYmAgCGDx9ebJvs7GwEBATgrbfewvDhwxEdHY1WrVrhwQcfxLBhw+ySGDkFBQW2hetSUlLs5vk7cz5rXl4egPInlyVJTEzEn3/+aZdI3+zWv8+tf88zZ85AkiRMnz4d06dPL/YYkZGRtvt169a1qw8ICAAA2XnSZeHr6wvA+mNEWReKK1qz4NY4bo4hMTER2dnZCAkJkT1G0WtTtC5CWd6rSUlJ+M9//oNBgwZh6dKlxbaLj493KGvQoAF0Op1t/rtOp3P4rAGsn1MWiwUXL15E06ZNiz1HVFSUw48CAQEB+PPPP0t9HnFxcZg0aRIWLlyIdevWoVOnTnj44Yfxn//8h0PLiahWYdJNRHSLxx57DKNHj8aVK1fQq1evSl3JuSRFPav/+c9/ik0G77rrrnIdMzExEYcOHQIg/wV93bp1tqS7shTXu3zr4lM3u7lXuMjgwYOxd+9eTJkyBS1atIC3tzcsFgt69ux52/uMFz3+7bffLnaLo6Ie48GDB6NTp0746quvsH37drz99tt488038eWXX9rm/st5/vnnsXr1akyYMAHt27eHn58fBEHA0KFDnbpP+t9//w0AqF+/fqUd02KxoHv37njppZdk6xs0aGB3/9a/Z9HznTx5Mnr06CF7jFvjvXnu8s2kWxYpLKtGjRoBAP766y/bvOPSFBfDzSwWC0JCQrBu3TrZ+uJ+qChJeHg4wsPD8f333+Pw4cMVXiuhMtzu32HBggUYMWIEvv76a2zfvh3jx4/HvHnzsH//fkRFRVVmqEREVRaTbiKiW/Tr1w9jxozB/v37bYs2yYmJicHOnTuRm5tr16v4zz//2OqLri0Wi60nucipU6fsjle0srnZbK607bzWrVsHlUqFjz/+2OHL8549e7BkyRIkJyejbt26qFevHg4cOACj0Si7xRQA1KtXD9u2bUNGRkaxvd1FPZJZWVl25eUZFpyZmYldu3Zh9uzZmDFjhq28qIe6SHBwMHx9fW2JZlkVjTrw9fUt02sdHh6OsWPHYuzYsUhLS0PLli3xxhtvlJh0b9y4EcOHD8eCBQtsZYWFhQ6vy+0My5fz8ccfA0CxyW1F1KtXD3l5eRV+XxaNClCpVJW6VV15Xrs+ffpg3rx5+OSTT8qcdJdFvXr1sHPnTtxzzz2yPx7d3A6w/ihS2g8iWq0W3377Le6//3707NkTP//8s2xv9K3/HgDg9OnT8PT0tCX7np6eDp81gPVzShRFu/3cK6q0v0OzZs3QrFkzvPrqq9i7dy/uueceLF++HHPmzLntcxMRVQec001EdAtvb2+8//77mDVrFvr06VNsuwcffBBmsxnvvvuuXfmiRYsgCIItISu6vnX181tXfFYoFBgwYAA2bdokm0TevF1SWRUN6RwyZAgGDhxod5kyZQoA69xRwDoP99q1aw7PB/i3V2vAgAGQJAmzZ88uto2vry+CgoIc5vkuW7aszHEX/UBwa2/ara+ZKIro27cvvvnmG9uWZXIx3apVq1aoV68e5s+fbxuOfbOi19psNjsMBQ8JCUFERAT0en2pz+HW8y9dutShx79oT/Jbk/GKWL9+PT744AO0b98eXbt2ve3jFRk8eDD27duHbdu2OdRlZWXZtrEqTkhICO677z6sWLECly9fdqivyHsbsL52ZX3d2rdvj549e+KDDz7A5s2bHeoNBgMmT55c7hgGDx4Ms9mM119/3aHOZDLZ4nvggQfg4+ODefPmOWzXJ/c+9fPzw7Zt22xb1N28bV+Rffv22a0PcPHiRXz99dd44IEHoFAooFAo8MADD+Drr7+226ru6tWrWL9+PTp27Ggbdn87insP5+TkOLw3mjVrBlEUS/33Q0RUk7Cnm4hIRklzfYv06dMHXbp0wSuvvILz58+jefPm2L59O77++mtMmDDB1rPVokULPProo1i2bBmys7PRoUMH7Nq1C2fOnHE45v/+9z/8+OOPaNeuHUaPHo0mTZogIyMDf/zxB3bu3ImMjIwyP4cDBw7gzJkzGDdunGx9ZGQkWrZsiXXr1uG///0vhg0bhrVr12LSpEk4ePAgOnXqhPz8fOzcuRNjx47FI488gi5duuCJJ57AkiVLkJiYaBvq/euvv6JLly62c40aNQr/+9//MGrUKLRu3Rq//PILTp8+XebYfX19ce+99+Ktt96C0WhEZGQktm/fjqSkJIe2c+fOxfbt29G5c2c8/fTTaNy4MS5fvowNGzZgz549stMDRFHEBx98gF69eqFp06Z48sknERkZiZSUFPz444/w9fXFN998g9zcXERFRWHgwIFo3rw5vL29sXPnThw6dMiuB1tO79698fHHH8PPzw9NmjTBvn37sHPnTtSpU8euXYsWLaBQKPDmm28iOzsbGo0G999/f7FzhIts3LgR3t7eMBgMSElJwbZt2/Dbb7+hefPm2LBhQ+kvcjlMmTIFW7ZsQe/evTFixAi0atUK+fn5+Ouvv7Bx40acP38eQUFBJR7jvffeQ8eOHdGsWTOMHj0ad9xxB65evYp9+/bh0qVLOHbsWLnjatWqFd5//33MmTMH9evXR0hICO6///5i269duxYPPPAA+vfvjz59+qBr167w8vJCYmIiPvvsM1y+fFl2r+6SdO7cGWPGjMG8efNw9OhRPPDAA1CpVEhMTMSGDRvwzjvvYODAgfD19cWiRYswatQotGnTxrYv/bFjx6DT6fDRRx85HDsoKAg7duxAx44d0a1bN+zZs8du3vudd96JHj162G0ZBsDuR7E5c+bYjjF27FgolUqsWLECer3ebr/t21GvXj34+/tj+fLl8PHxgZeXF9q1a4djx45h3LhxGDRoEBo0aACTyWQbdSO3VzoRUY3ljiXTiYiqkpu3DCuJ3BZLubm50sSJE6WIiAhJpVJJ8fHx0ttvv223BZAkSVJBQYE0fvx4qU6dOpKXl5fUp08f6eLFiw5baEmSdYuv5557ToqOjpZUKpUUFhYmde3aVVq5cqWtTVm2DHv++eclAHZbBd1q1qxZEgDp2LFjkiRZt7l65ZVXpLi4ONu5Bw4caHcMk8kkvf3221KjRo0ktVotBQcHS7169ZJ+//13WxudTieNHDlS8vPzk3x8fKTBgwdLaWlpxW4ZJrf91aVLl6R+/fpJ/v7+kp+fnzRo0CApNTVV9jW7cOGCNGzYMCk4OFjSaDTSHXfcIT333HOSXq+XJEl+OyRJsm5p1L9/f6lOnTqSRqORYmJipMGDB0u7du2SJMm6PdKUKVOk5s2bSz4+PpKXl5fUvHlzadmyZcW+pkUyMzOlJ598UgoKCpK8vb2lHj16SP/8848UExMjDR8+3K7tqlWrpDvuuENSKBSlbh9W9JoVXbRarRQVFSX17t1b+vDDD+225Cpyu1uGSZL1vT5t2jSpfv36klqtloKCgqQOHTpI8+fPlwwGgyRJ/74v3377bdnYz549Kw0bNkwKCwuTVCqVFBkZKfXu3VvauHGjrU1x/x7l/oZXrlyRHnroIcnHx0cCUKbtw3Q6nTR//nypTZs2kre3t6RWq6X4+Hjp+eeft23zJ0nW18zLy8vh8UWv/61WrlwptWrVSvLw8JB8fHykZs2aSS+99JKUmppq127Lli1Shw4dJA8PD8nX11dq27at9Omnn9rqb94yrMiZM2ek8PBwqXHjxrZ/K0V/p08++USKj4+XNBqNlJCQIPve+eOPP6QePXpI3t7ekqenp9SlSxdp7969dm2K2zLs1liKXptb309ff/211KRJE0mpVNo+m86dOyc99dRTUr169SStVisFBgZKXbp0kXbu3OlwTCKimkyQpAquSEJEREREbiEIAp577jnZ6SBERFS1cE43ERERERERkZMw6SYiIiIiIiJyEibdRERERERERE7C1cuJiIiIqhkuyUNEVH2wp5uIiIiIiIjISZh0ExERERERETkJh5cDMJlMOHLkCEJDQyGK/B2CiIiIiIjIGSwWC65evYqEhAQolbUjHa0dz7IUR44cQdu2bd0dBhERERERUa1w8OBBtGnTxt1huASTbgChoaEArH/48PBwN0dDRERERERUM12+fBlt27a15WC1AZNuwDakPDw8HFFRUW6OhoiIiIiIqGarTdN6a88zJSIiIiIiInIxJt1ERERERERETsKkm4iIiIiIiMhJOKe7jCwWCwoLC90dBrmJWq2uNVsaEBERERFR5WEWUQZ6vR4nTpyAxWJxdyjkRkFBQahbty4EQXB3KEREREREVE0w6S6FJEk4f/48lEol4uLiatUqe2RlsViQl5eHlJQUAEBMTIybIyIiIiIiouqCSXcpjEYj8vLyEBcXB29vb3eHQ25S9LdPSUlBZGQkh5oTEREREVGZsNu2FCaTCQCg0WjcHAm5W1HibTAY3BwJERERERFVF0y6y4jzeIlTC4iIiIiIqLyYRRARERERERE5CZNuqnRr1qyBv79/uR4zYsQI9O3b1ynxEBERERERuQuT7hrq1iR2xIgREAQBgiBApVIhNDQU3bt3x4cffljiVmixsbG2x8ldRowY4fCYIUOG4PTp0054VkRERERERNULl2CuRXr27InVq1fDbDbj6tWr2Lp1K1544QVs3LgRW7ZskV2R+9ChQzCbzQCAvXv3YsCAATh16hR8fX0BAB4eHnbtjUYjPDw8HMqJiIiIiIhqIybd5TB10584dTXXrTE0DPXB/wbcVaHHajQahIWFAQAiIyPRsmVL3H333ejatSvWrFmDUaNGOTwmODjYdjswMBAAEBISAn9/f5w/fx7h4eH47LPPsGzZMhw4cADLly8HAEyYMAFZWVkAgFmzZmHz5s149tlnMWfOHFy/fh29e/fGqlWr4OfnJxurxWLBm2++iZUrV+LKlSto0KABpk+fjoEDBwIAMjMzMW7cOGzfvh15eXmIiorCyy+/jCeffLJCrw0REREREZEzMOkuh1NXc3EkOcvdYVSq+++/H82bN8eXX34pm3SXxdSpU7FgwQIkJCRAq9Vi27ZtDm3OnDmDL774At988w1ycnIwcuRIjB07FuvWrZM95rx58/DJJ59g+fLliI+Pxy+//IL//Oc/CA4ORufOnTF9+nScOHECP/zwA4KCgnDmzBkUFBRUKH4iIiIiIiJnYdJNaNSoEf78888KP37ChAno379/iW0KCwuxdu1aREZGAgCWLl2Khx56CAsWLLD1vhfR6/WYO3cudu7cifbt2wMA7rjjDuzZswcrVqxA586dkZycjISEBLRu3RqAde45ERERERFRVcOkmyBJ0m3tQ16U+Jakbt26toQbANq3bw+LxYJTp045JN1nzpyBTqdD9+7d7coNBgMSEhIAAM8++ywGDBiAP/74Aw888AD69u2LDh06VPg5EBEREREROQOTbsLJkycRFxdX4cd7eXlVYjRAXl4eAOC7776zS9QB67x0AOjVqxcuXLiA77//Hjt27EDXrl3x3HPPYf78+ZUaCxERERER0e1g0l0ODUN93B1Cpcewe/du/PXXX5g4cWKlHvdWycnJSE1NRUREBABg//79EEURDRs2dGjbpEkTaDQaJCcno3PnzsUeMzg4GMOHD8fw4cPRqVMnTJkyhUk3ERERERFVKUy6y6Giq4ZXFXq9HleuXLHbMmzevHno3bs3hg0b5tRza7VaDB8+HPPnz0dOTg7Gjx+PwYMHOwwtBwAfHx9MnjwZEydOhMViQceOHZGdnY3ffvsNvr6+GD58OGbMmIFWrVqhadOm0Ov1+Pbbb9G4cWOnPgciIiIiIqLyYtJdi2zduhXh4eFQKpUICAhA8+bNsWTJEgwfPhyiKDr13PXr10f//v3x4IMPIiMjA71798ayZcuKbf/6668jODgY8+bNw7lz5+Dv74+WLVvi5ZdfBgCo1WpMmzYN58+fh4eHBzp16oTPPvvMqc+BiIiIiIiovARJkiR3B+Fuly5dQnR0NC5evIioqCi7Op1Oh5MnT6Jx48bw9PR0U4TVW9E+3UePHnV3KLeF7wUiIiIiottTUu5VUzm3e5OIiIiIiIioFmPSTUREREREROQkTLrJ6WbNmlXth5YTERERERFVBJNuIiIiIiIiIidh0k1ERERERETkJEy6iYiIiIiIiJyESTcRERERERGRkzDpJiIiIiIiInISJt1ERERERERETsKkm6qsESNGoG/fvuV6TGxsLBYvXuyUeIiIiIiIiMqLSXcNdvHiRTz11FOIiIiAWq1GTEwMXnjhBVy/ft2h7fHjxzF48GAEBwdDo9GgQYMGmDFjBnQ6nV272NhYCIIAQRDg4eGB2NhYDB48GLt37y42jvPnz9seU9xlzZo1Do975513ZMuJiIiIiIiqCybdNdS5c+fQunVrJCYm4tNPP8WZM2ewfPly7Nq1C+3bt0dGRoat7f79+9GuXTsYDAZ89913OH36NN544w2sWbMG3bt3h8FgsDv2a6+9hsuXL+PUqVNYu3Yt/P390a1bN7zxxhuysURHR+Py5cu2y4svvoimTZvalQ0ZMsTW3mw2w2KxwM/PD/7+/k55fYiIiIiIiFxB6e4AqpUtzwNpJ90bQ0hj4OGlpTZ77rnnoFarsX37dnh4eAAA6tati4SEBNSrVw+vvPIK3n//fUiShJEjR6Jx48b48ssvIYrW32FiYmLQoEEDJCQkYNGiRfjvf/9rO7aPjw/CwsJsx7z33nsRHh6OGTNmYODAgWjYsKFdLAqFwtYeALy9vaFUKm1la9aswYQJE7B27VpMnToVp0+fxpkzZzBr1ixkZWVh8+bNAID77rsPd955JwDg448/hkqlwrPPPovXXnsNgiDIvg5ZWVmYPHkyvv76a+j1erRu3RqLFi1C8+bNAQDHjh3DhAkTcPjwYQiCgPj4eKxYsQKtW7cu9TUmIiIiIiIqDZPu8kg7CVw65O4oSpWRkYFt27bhjTfesCXcRcLCwvD444/j888/x7Jly3D06FGcOHEC69evtyXcRZo3b45u3brh008/tUu65bzwwgt4/fXX8fXXX+Oll14qd8w6nQ5vvvkmPvjgA9SpUwchISGy7T766COMHDkSBw8exOHDh/H000+jbt26GD16tGz7QYMGwcPDAz/88AP8/PywYsUKdO3aFadPn0ZgYCAef/xxJCQk4P3334dCocDRo0ehUqnKHT8REREREZEcJt01UGJiIiRJQuPGjWXrGzdujMzMTKSnp+P06dO2suLa7tmzp9RzBgYGIiQkBOfPn69QzEajEcuWLbP1QBcnOjoaixYtgiAIaNiwIf766y8sWrRINunes2cPDh48iLS0NGg0GgDA/PnzsXnzZmzcuBFPP/00kpOTMWXKFDRq1AgAEB8fX6H4iYiIiIiI5HBOdw0mSZJT2pZ0jOKGeZdGrVbjrrvuKrXd3XffbXeO9u3bIzExEWaz2aHtsWPHkJeXhzp16sDb29t2SUpKwtmzZwEAkyZNwqhRo9CtWzf873//s5UTERERERFVBibdNVD9+vUhCAJOnpSff37y5EkEBAQgODgYDRo0sJUV17aoTUmuX7+O9PR0xMXFVShmDw+PCifsxcnLy0N4eDiOHj1qdzl16hSmTJkCAJg1axaOHz+Ohx56CLt370aTJk3w1VdfVWocRERERERUe3F4eXmEyA/Brmox1KlTB927d8eyZcswceJEu3ndV65cwbp16zBs2DAIgoAWLVqgUaNGWLRoEYYOHWo3r/vYsWPYuXMn5s2bV+o533nnHYiiWO59tcvrwIEDdvf379+P+Ph4KBQKh7YtW7bElStXoFQqERsbW+wxGzRogAYNGmDixIl49NFHsXr1avTr16+yQyciIiIiolqISXd5lGHV8Kri3XffRYcOHdCjRw/MmTMHcXFxOH78OKZMmYLIyEjb9l6CIOD//u//0L17dwwYMADTpk1DWFgYDhw4gBdffBHt27fHhAkT7I6dm5uLK1euwGg0IikpCZ988gk++OADzJs3D/Xr13fq80pOTsakSZMwZswY/PHHH1i6dCkWLFgg27Zbt25o3749+vbti7feegsNGjRAamoqvvvuO/Tr1w9NmzbFlClTMHDgQMTFxeHSpUs4dOgQBgwY4NTnQEREREREtQeT7hoqPj4ehw8fxsyZMzF48GBkZGQgLCwMffv2xcyZMxEYGGhr26FDB+zfvx+zZ89Gr169kJubi7p162L48OGYNm2abRGyIjNmzMCMGTOgVqsRFhaGu+++G7t27UKXLl2c/ryGDRuGgoICtG3bFgqFAi+88AKefvpp2baCIOD777/HK6+8gieffBLp6ekICwvDvffei9DQUCgUCly/fh3Dhg3D1atXERQUhP79+2P27NlOfx5ERERERFQ7CFJlrKBVzV26dAnR0dG4ePEioqKi7Op0Oh1OnjyJxo0bw9PT000REmDdp7tFixZYvHixW87P9wIRERER0e0pKfeqqbiQGhEREREREZGTMOkmIiIiIiIichLO6aZq46effnJ3CEREREREROXCnm4iIiIiIiIiJ2HSTUREREREROQkbk26f/nlF/Tp0wcREREQBAGbN2+2q5ckCTNmzEB4eDg8PDzQrVs3JCYm2rXJyMjA448/Dl9fX/j7+2PkyJHIy8tz4bMgIiIiIiIiZygtZ5Tz008/oWXLltBoNKhfvz7WrFnj9DhL4takOz8/H82bN8d7770nW//WW29hyZIlWL58OQ4cOAAvLy/06NEDhYWFtjaPP/44jh8/jh07duDbb7/FL7/8Uuy+zURERERERFR9lJYz3iopKQkPPfQQunTpgqNHj2LChAkYNWoUtm3b5uRIi+fWhdR69eqFXr16ydZJkoTFixfj1VdfxSOPPAIAWLt2LUJDQ7F582YMHToUJ0+exNatW3Ho0CG0bt0aALB06VI8+OCDmD9/PiIiIlz2XIjoJroM4J/vgOuJgEINaHwBra/1+ubbRddqL0AQ7I9hMQOGfOvFqLvpOg8w6ADJDCg01uMrVIBSA7OoQAEsyJfM0ElmFEKCqPGDSuMDlaiCUlRCpVBBKVivVaIKoiBCgOD4HCwWQJ8FUZcFQZ8DFGbduGTDrMtEXlYGjIX/jqqRJAl6WJALI3IlE6DUwNMzCN6eIfD2CYXWOxQqnzowihrk5OYiJzcHurwc6PLyUKDLRaHJgnxJg3yLGpkSkGE2QSflwd+SDj9LGrzM1+FpTofKnANIEiRJggTAIgGAAK02DGFhLdCkcWcExNxtfW1vMJtNKNRno0CfhcLCbBQaclCoz0GBIReFhnwUGvJQaMxHgTEfOqMOOmMBdEYdCsx6FJj0KDTrYZTMsJ4JN71agt194aYy+7aC3f3iH39z66K2N7eWKRNu8/FlPP+tjy26bWsrlNa25FjKfV8QIQGQBBGAAAkCJEGEdKOVVFSPG/VCURvhRpm1TsLN5UUXEZJgfW9ZLEZIkhEWy42LZILZYoJFst62SOYbl39vSzDDLJlhhuXGfQvMkgXSjehEAIJkvRalm+5L9nXWa+nGtQBRkiBKAkTrPYiS9dp6W3HjtgKCpACg+Pe2oIBZUsMsqGGCBkZorNeC9sZ9LYyCFgZoYRQ8YIAGaqkAHsiGh5QDLXKhlvKgQR5UyIcKOiglHRRCARSSAaIgQCFZv1CJABQAlBBuug1YIEIvKKAXlNBDAT0UMAjWa70gwgARBkEBoyDCAOu1EQJMggCjIMIsiFCIIhSiAKUoWK8VN64FEaLKB4I6CKImCCq1H7RKD3gqtVAKGhiMIvRGBQxGEQUG4cbFDJ05D4XmHBRacmCQcqCXcgGYEKCpg3DvMNT1jUD9OpGI9veFUmHGFd1FpOqScVmXjKsFqRAFAcEeQQjxCkaoVzDCvEKgN6iRnmNBWpYFqVkWXM8vhElMg0lxFXqkoUBKAwQzbqYSNPBTB6OOJhR1PELgo/aAqNRBUOhgFnQQLGooLHVg0gfAYPCGUqmHQpkHQZkHiyRBsHjDbPQBzD4I8PBEHW81Aj1VuKy7iD+v/45zOf9AEvTw91RBIVr//UgSoDOYoBY9EOkThgifUKTlp+N05hlcybsMi6SEIGlgMosoMOmgN+ugFrUI84pAgCoYmToJV3MKYEAmLMprkESd7e/iL2kRo1PBS1Lc+DcKWN/9RbcBCdK/5YI1Hoso2dVJsNZbhBtlttu3Pl6CBQIskABBsj7mxrmkG7ctgmR93oIASQAgiNYGAARYPytsnzLSv7cludvSjfvWDxHrv2rpxmeHZP2MUooKqBQiVAol1AoF1EoF1Dfd1iiV0CgV0CgU0ChVUIgiBEGAQlBAgABREK23BeunrFkyw2QxwWQxwWgxWm9LJlvZzRejZITJXNTOCLPJBMFogbLQDJXeDFWhxXqtN0NVaIbKIEGtN0Ott1gvBjO0ehM0BjMsIlCgEVGoUaBArbBea63XhWoRhVprnV4jQq8RAUEBjVkFlUkFtVEJtVEJpVEBpVGEwihCYRSgNAgQjYASJihhhML6Lx4ijBAtRgiSEYLFCFhMgGCBRaWESa2ERaWApFLColZCUisBtRqSSgmlwQxVnhEqnR5qnR5qnQGaQiO0BUZoC03QFpqh1Zvh8+b/cPfdD6K6KilnlLN8+XLExcVhwYIFAIDGjRtjz549WLRoEXr06OGsMEtUZVcvT0pKwpUrV9CtWzdbmZ+fH9q1a4d9+/Zh6NCh2LdvH/z9/W0JNwB069YNoijiwIED6NevnztCJ6pRJElCjiEHFskCURDt/jO8+VqEACTvB35fA5zYDJisI1LMAHSCgHxRhE4UoBNE5IvW+/mCAJ0oWm8rtchXKGEq+hIPC4wAzIIA003XJkGASQAMgoB8wXrMfFFEgSCgQHTO4B0PiwUaSYJWkqC1SPCQJGglCwAgRxSRLSqQrRBhvPmHAz2A/H/vaiwWeEkSPCwSVJIEFW5cS4BKkqATBWQqFMgQReiLnocA67d2BQBVaVEmA9nJwP4t8NprgYcE6AWgUBDs4yKqTPa/oriIufQmtYXlxrUZQGFJDYtR9Plyk+sAzuQByAOQCkhmD0AshHAjcXOK/NKb2JEkaA3W/E+v/vcNKFkU8M1TIihHQp63Hul+sPtBV7RIaHxRQttTEhpesh6jUA3oVUBTPdAxF/ApBAwKa3mh+t9TaoyAh/5PKC3AVX/gfKgAnQbw1QFehRI89dbbgdVkhqMFAATAcuPlkQTYkn2528C/bS035ee2tjfdr2yi9feEf3+cs9y4f1NdUZld28oPpdo6m3wcqMZJd3nt27fPLocEgB49emDChAnuCQhVOOm+cuUKACA0NNSuPDQ01FZ35coVhISE2NUrlUoEBgba2sjR6/XQ6/W2+7m5uQAAk8kEo9Fo19ZkMsFiscjW1TZ33nknxo4di7Fjx7o7FLeoLe8FSZKQlJ2E36/+jj/S/sCRtCPI1meX6bGidKNfLTIKihu/7OudlAjL0TjpuBYRKID1UhyxtPOL1u+V+YqSGlnd7vMwiUBuWeMiIiqJwgJAXWqz2yFYJARlA+GZEtRmoEBlTaYNSiAkW0LUNQlR14CQLAk+OmtirLzx20uOB5DuD+RpBUSnSwjMM904qhLpfsCxWAEFWiDmKlDvigSvW3+c0NnfNWusv0N4WeDYVmlNLEN0QEiS/HMxV7MPXOGWa1nSLddVTdEP1DeRwJ/nbmbOzqlS311NJuu/09zcXOTk5NjKNRoNNJrb/0d05coV2RwyJycHBQUF8PDwuO1zlFeVTbqdad68eZg9e7ZD+b59++Dp6Sn7mNTUVGeHVeW99dZbAIDvv//ezZG4V215L3jBC53QCZ08OgGu/2wiIqLaJBBAXMlNjAAyblxu5Q0g88blZjcfsvjuGKKaryp9f9fprL92NWnSxK585syZmDVrlhsicr4qm3SHhYUBAK5evYrw8HBb+dWrV9GiRQtbm7S0NLvHmUwmZGRk2B4vZ9q0aZg0aZLtfkpKCpo0aYL27dsjMjLSrm1BQQFOnTqFhg0buuVXkYq4evWq7faXX36JN954A7///rutzNvbG15eXgCsvZpmsxlKpWveCnv27MFDDz2E5ORk+Pn5Odyvyqrje0GOzmDE0cvn8NulQ/j7+lFcyD8OvZTl7rCIiKgKU5ok3HVeQpvTEuKuSFCZgSsBAlLqAJcDBaQGAmoTEJINBGdbe64D8iT4FADehYCnvvRzEJFznO3XCg++stzdYdikpKQAAE6cOGGXe1VGLzdgzRFvzocAa37k6+vrtu/wVTbpjouLQ1hYGHbt2mVLsnNycnDgwAE8++yzAID27dsjKysLv//+O1q1agUA2L17NywWC9q1a1fssW8dulA0rEGpVEKlsp84aTQaIYoilEol3jj0BhKz7Lcsc7V4/3jM6jCrxDZRUVG2276+vtDr9bayn376CV26dMH333+PV199FX/99Re2b9+O6OhoTJo0Cfv370d+fj4aN26MefPm2c2HiI2NxYQJE2zzIQRBwKpVq/Ddd99h27ZtiIyMxIIFC/Dwww8XG5sgCCgoKLC91rfer8pufi9U9ViLXMvT48s/LuHwpXM4m3cM10wnYFInQlRluTs0qia0Fgu0N+aeA/ajDG+dvyc51Av/jkYU5OpvfaxgO96toxn/PR/np1d1RdNMlLbF0QTrPEsItsWgrAtG4d/bN64t/PNWKSqThBZnJbT/R0KrMxI8DPb1IdeAu9z7tYio0hmVEowqQLAAGgMgOmOiupPpVdY1CQo01otWZa5S312LOvt8fHzg6+tbSuvya9++vUPP/o4dO9C+fftKP1dZuTXpzsvLw5kzZ2z3k5KScPToUQQGBqJu3bqYMGEC5syZg/j4eMTFxWH69OmIiIhA3759AVhXouvZsydGjx6N5cuXw2g0Yty4cRg6dKhTVi5PzErEn+l/Vvpx3WHq1KmYP38+7rjjDgQEBODixYt48MEH8cYbb0Cj0WDt2rXo06cPTp06hbp16xZ7nNmzZ+Ott97C22+/jaVLl+Lxxx/HhQsXEBgY6MJnQ3JSswrw4P8tgcFnGxSadOvEXk3VX1jEuhCKdR1iQbpxgQgR1tWJRUEJQVBAlJQQzQoIZhEwiVCaRagsItSSCI1FhMYiQCtJ8BQK4QEdNGIBNIIe6hsXUTDBJADmGzPZjFBABw0KoEGBpEEB1CiABjqoUCCIMIgCJLUIQSVAUAqA0gKFQoSH0hueCh9oFd7wUPjA48ZtmA0wFGbAYMyE0ZgNgykXBnM+TDDCIgqQFAIsogCLCFgECzSiCnVUnghSeCBQoUEAFAgQ1dB6BkPlGwGlTySg8oNkUUCjUkCtECHeWIlXZ9Dj6MWzOHvhD2RmJUJvugoLjFBalFBACYWkggIqKAQ1FNBAKWigELVQiFqoRE8oFZ5QKr2gUnpBpfSBRu0DjcYPGrUPlBpvKNUeUKhUDgvMu5t1Bfd/0/Ib6/Pa6nBTbdH6vzc/1qEMEm4s0Ws7loSbjnPT+Wzl0i33i+5Jt9wvOo90c1vJ7rwO55QcYyhqKwrWJY9FSBAECwRJguLGeseiAAiSpWgd8htrkltsa5YrbO96CSKsjxVQ1B4QYLadQ6nQQlSooVR6QKFUQ1RqoVRooVBqoVRpoVRqoVSooRIVUArWVYiVCoU1BgjWa8F6bT2eAJVCtK30LMi8qSySBWbJbL22mCFBst63WGwrFhetYGxbyfjWFYyL6iXrtdlkgNlUAJOxEGZTASwmPUzmQphNhTCb9DCZ9TCbDTDfuFYq1FCrvaFReUOt8YVa4wuN1h9qrT80Sg9oFBqoFWooRaUtXrNkhtlitq20XFRmspisn2CiAkpBCaWohEJUQCEorLcFhbVOEqC0mKGEBKXFDIXFBKXZAqXFCNFitlv9vuidYbRYUKjXozA7Bbq8VBjyrkBfkA59wXUY9JkwmPUwKNUwKFQwKJUwKVTQiwqYRBF+FgkBZjP8TSYEmgzwN+ihKMhAOsxINyqhOKlF0Ek1NIVV7B9+JRHVFmgDjDBYBJhMAhRKCZ5aM5RaMySLAItRgMV80yJsCgmCSoJBEmDMVMGUo4QgAQqNxXpRWSCqJKg8zVD5mKBUW/79dLF9TAkyZbCtBG6bWW1X9m+ddMuvkbb7N45tV3ZTnSTza6b98W+J69aY7I5VjpjK6KYwULQy+s2HtX7Owfo5AusKaoJtEUfp39vCjSLhpjYABFGCqJIgKiWISsuNa+tFuFEmaFRASBwUEY2hCGsCBDcEtH6QCrMh5WTAknUd5pwMWHIyYc7Jhjk3F5a8XFjydbDoCmEp0AMWE0TRDEEwQxRMEBTWXx5NSsCoAAwqQK+wrlWgFiR4wAItJHhKFqjEG89DoQSUKkCphCSqYbGoYIYKZrMSZkkJs1kBs0UJk1mE2SwCHp4Qff2g8PWHKiAQmqAQeASFQOVTx36nGM865f/DVCGl5YzTpk1DSkoK1q5dCwB45pln8O677+Kll17CU089hd27d+OLL77Ad999566n4N6k+/Dhw+jSpYvtftGQ7+HDh2PNmjV46aWXkJ+fj6effhpZWVno2LEjtm7dCq1Wa3vMunXrMG7cOHTt2hWiKGLAgAFYsmSJy59LdfPaa6+he/futvuBgYFo3ry57f7rr7+Or776Clu2bMG4ceOKPc6IESPw6KOPAgDmzp2LJUuW4ODBg+jZs6fzgqcymfTNZzAHfXLr2iLlIkgSGhmMaFVYiACz5UavlGDrkbLAet9843aqFIhTUiSSEWL7Wg+LGpJFDcmiASwaaBWe8NV6IUDrg0APHwR5+SLU2xfhvv4I9/VFoKcW3hoVfLRK+GiV8FIrbcllcSRJQq7ehOt5BmTk629cG5BdYISXRokATzUCPFUI8FIjwFMNf08VtIIZ0F0HLEbAMwhQe0JvMiO30HTjYkRuoQkqhYioAA+E+mpt281URe0j2wJ3P2q7L0mSbEJDVNUV7ZIAwGFxJHIu/enTUHywAp4/bIdkNJX+ABcSFBZofE1QeZmtSa7aAskswJCnhCFPAYtBhNLLDI8AI9S+RhRmqJF3WQOz3vomEpXWJFsbaIR3RCE8gw0oepuhTrz8SfPTgMKyLSRarSg0gEoLqDwBpRZQeThey5UpbzxGpQWUHvbXRcdSqACT/salADAW2l+b9ICxwLrDya3XpkKH9pKxEIJRd2PLUB1gvs15Cgq19e8d0ggIvnEJaQwExFkT3lsU5fMiypk0SZJ161Ozwfo9w1x0MVi3AxOVgPKmbU8VauuF/2/LKi1nvHz5MpKTk231cXFx+O677zBx4kS88847iIqKwgcffOC27cIANyfd9913n62XQI4gCHjttdfw2muvFdsmMDAQ69evd0Z4NdrN26wB1l+QZs2ahe+++w6XL1+GyWRCQUGB3RtYzl133WW77eXlBV9fX9s8+6ZNm+LChQsAgE6dOuGHH36o5GdBxbmcXYA/876CQn5dwBKZC8Ng1t2BegVqfGr6BH4WS4nt8xW+OBLQC8dCHkGEbz3EKUVoVQpolCI8VArU8dYgyFuNYB8Ngrw10Koq/1u0IAjw1argq1UhLsirjI9SAL7hdiUapQIabwWCvKvZ8rMymHATUVkVnjyJtEWLkP/Lry49r6CwQO1jhsbXCLWvCRo/E5QaCywmwXYR1RK0fkaovMz/JsllooNkAUwFCkgSrI+/9WOxfnfgsc8BsZj/lyQJyEkF0k8CuVeAvDRAsgBhzYA7ulgTp+uJ1mTRLxrwDAQuHwPO/QToMqzHFRTWdqJ44/aN+0W3BfFGfWltxZvqFTfV33S7tHMptdaLC3cVuV0O/5OZTdYE3KgDDPnWhN12+0ZibrxRXlSm8gCCGpaYXFd+4IL1PK44Vy1QWs64Zs0a2cccOXLEiVGVD98JtVTRQmpFJk+ejB07dmD+/PmoX78+PDw8MHDgQBgMhmKOYHXr/BBBEGC5kaR9//33tu0JqvPCY9XRh3v/guhxvkxtzfoQqAzxCFI2wR0+d6Fe3TBEB3qgTca38DtQQsIdcw/QagS8Gj+MjiotOlZO6ERE5CKSwYBry1fg2sqVgKnsPduqiAiooqOhP3cW5vRrsm0Ufr5Q1fGBQmuGQsiDwpwBhbIQSg8L1D4mqH1MUGotZe/YU/sA978KXDoE/L2xTA8RRGuyLSsgDhiwqviEG7AmTn6R1ktxghva3w9vbr2QcyiUgOLGkGmiaoRJdznE+xcz/KgGxPDbb79hxIgR6NevHwBrz/f58+dv65gxMTGVEBmVl8FkwcZ/dkAIlP9F0FsMQ6x3c7QIaoV7o+9Gs/BoeGtkPgp+zpc/QdungTajHL9oEBFRtVF48iRSp70M/T//lKm9KiICPj17wrdnD2ibNbONpjFnZ0N/7hyMl1IgaDVQR0VBFRUFhY+P/QEsFiAzCchJAbJTrNe5lwEUJbbRgHcocOUv4NT3wIW9gHQjYY7rDDy8FAiIAfAM0HEi8MdHwNndwPUzKJFHgPUcBTdtNOYVDDz66Y06IiLnY9JdDqWtGl6dxcfH48svv0SfPn0gCAKmT59u67Gm6mXr8SsoVB2T/ce9sc9GNAwsY7Kce9mxTFAAPf9Xcs8AERFVWZLRiGsrVuLa8uWl924LArzvvx91RgyHR+vWstNWFH5+8ExIABISSj6WKAJ16lkvJYnrBLQfCxRkAWknAa0fEGq/ly/C7gQefNt6O/OCdTh3+j/WId0FmYAhD/CvCzTqDcQ/YO3yvnQQuHjAOm+2aX+H6UVERM7EpJsAAAsXLsRTTz2FDh06ICgoCP/9739tW6lR9fLRvn+g8HLcwyXKq17ZE27AOn/tVt6hTLiJiKoZyWJB4cmTyN+7FznffAv96dMlthe0Wvj164s6w4dDHRvrmiBv5eEPxJRhe5+AGKDV8NLbxXSwXoiI3IBJdw03YsQIjBgxwna/uIUIYmNjsXv3bruy5557zu7+rcPN5Y6TlZVVYjy3nr+0hRGofE5ezsGx64fgEeXYe9G7XneZR5QgJ9WxzCesgpEREZErGVNSkLd3L/L37oVu336YS/n/GQCgUKDOU08h8KknoQzg0GsiosrCpJuoBlm77wKU3sdl67rGdC3fweR6un04HI+IqKoy5+YiZ+tWZH+1GQV//FGux2oaNED4vLnwaNrUSdEREdVeTLqJaoicQiM2H0mGMs5xUZwwz3A0DCjH0HKzybo/6a3Y001EVKVIZjN0Bw4g66vNyN2xA1JhYfkOoFCgzuhRCBo7FqJa7ZwgiYhqOSbdRDXEpt8vwaA6A09FgUNdt5iu5du3OT/duhfprdjTTURUJejPnUP211uQvWULTJdlFr4sA018fYTPnQePZndWcnRERHQzJt1ENYAkSfh4/wUofU7I1t9f9/7yHVBu5XKAq70SEbmRKT0dOd9/j+wt36DwuPxUolKpVPBs0QI+PXvAf9Ag9m4TEbkAk26iGuC3M9dxLj0PXvUdv4T5afyQEFLKVi63kpvPDXB4ORGRi1ny85G7axeyt3yD/L17rftdl5MmPh5eHTrAq0N7eLZuDdHLywmREhFRcZh0E9UAa/edh6hNhajKdqjrHNUZSrGc/9RzZVYuBzi8nIjIRSRJQubatUhf+i4seXnlfrz2zjvh168vfLp3hyokxAkREhFRWTHpJqrmUrIKsPPkVSjryA81LPfQcqCEnm4m3UREzmbOyUHqyy8jb+eucj1OERQEv4cfhl/fR6Bt0MBJ0RERUXkx6Saq5tYfuACLBNn53FqFFh0iOpT/oHJzuhVqwIP7thIROVPhyZO49MIEGJOTy9ReUKvh3aUL/Pr1hXfHjhCU/GpHRFTV8JOZqBrTm8z4/NBFCKrrUGgde6fbR7SHh9Kj/AeW3aM7DCjPCuhERFQuWZs24cprr0PS60tt69m2Lfwe7gOfBx6AwtfXBdEREVFFMekmqsa2/n0F1/IMUAVW0qrlRWST7oiKHYuIiEpkKSzElddeR/aXX5bYThNfH74PPwy/hx6CKoKfyURE1YXo7gCo8gmCUOJl1qxZt3XszZs3l9pu1qxZaNGiRbH3qXKs3XcBAKD0dky6RUFE56jOFTuw3PByrlxORFTpDBcu4PzQR0tMuBWBgYhetQpxW7YgaPRoJtxERNUMe7proMuX/02YPv/8c8yYMQOnTp2ylXl7e7sjLKpkx1Oz8fuFTAiKPCg8zzvUJ4QkIEBbgTnYJj2gu+5YzkXUiIgqVc727bj88islrk7ukZCAyMWLoAoNdWFkRERUmZh0l8Pl6dOhP53o1hg0DeIR/vrrJbYJC/u3R9LPzw+CINiVffDBB1iwYAGSkpIQGxuL8ePHY+zYsQAAg8GASZMmYdOmTcjMzERoaCieeeYZTJs2DbGxsQCAfv36AQBiYmJw/vz5yn2CVGYf3+jlVnj/A0GQHOrvj67EoeUAe7qJiCqJRa9H2ptvIXP9+hLbBQ4fjpDJL0JQqVwUGREROQOT7nLQn05EwbFj7g7jtqxbtw4zZszAu+++i4SEBBw5cgSjR4+Gl5cXhg8fjiVLlmDLli344osvULduXVy8eBEXL14EABw6dAghISFYvXo1evbsCYVC4eZnU3tl64zYfDQFAKD0kd8qrEvdLhU7OLcLIyJyGn1SElImvQj9yZPFthG9vBA+dy58ezzgwsiIiMhZmHTXMjNnzsSCBQvQv39/AEBcXBxOnDiBFStWYPjw4UhOTkZ8fDw6duwIQRAQExNje2xwcDAAwN/f367nnFxvw+8XUWi0AIIBSi/H0RcNAhog2ie6YgeXm88NsKebiOg2ZX/9NS7Pfg2STldsG02DBoh8ZzE0cXEujIyIiJyJC6nVIvn5+Th79ixGjhwJb29v22XOnDk4e/YsAGDEiBE4evQoGjZsiPHjx2P79u0lHjM5OdnuWHPnznXFU6nVLBYJ6w5Y929Vep+GIJoc2lR41XKg+J5uXy7cQ0RUERadDqnTXkbqf6eWmHD7PfIIYj//jAk3EVENw57uWiTvxkItq1atQrt27ezqioaKt2zZEklJSfjhhx+wc+dODB48GN26dcPGjRtljxkREYGjR4/a7gcGBjoneLLZc+Yakq7lA5BftRy4jfncAHu6iYgqUeGpU0iZOAmGc+eKbSN4eCBs+nT49esLQRBcGB0REbkCk+5y0DSId3cItxVDaGgoIiIicO7cOTz++OPFtvP19cWQIUMwZMgQDBw4ED179kRGRgYCAwOhUqlgNpttbZVKJerXr1/hmKj8irYJA8xQ+jjOCQz3CkejwEYVP4Fc0q32BjQ+FT8mEVEtI0kSsj7/HFfn/Q+SXl9sO018PCIXL4KmXj0XRkdENZkkSfj75xRYzBKad63gdEOqVEy6y6G0VcOrg9mzZ2P8+PHw8/NDz549odfrcfjwYWRmZmLSpElYuHAhwsPDkZCQAFEUsWHDBoSFhcHf3x8AEBsbi127duGee+6BRqNBQEAFtqSiCruUqcPuf64CABSe5yEoChza3F/3/tvrKeEe3UREt0WflIQrM2dBd/Bgie38hwxB6LSpELVaF0VGRDVdXqYeP358EsknMiAqBEQ29EdQFDtO3I1zumuZUaNG4YMPPsDq1avRrFkzdO7cGWvWrEHcjfljPj4+eOutt9C6dWu0adMG58+fx/fffw9RtL5VFixYgB07diA6OhoJCQnufCq10roDybDc2B2suFXLb2toOSA/p5srlxMRlUoyGHBt+XIkPdK3xIRb9PZG5OJFCJ89iwk3EVWaxMNX8dnrB5B8IgMAYDFL2Ln6BMxGi5sjI0GSJMcNfmuZS5cuITo6GhcvXkRUVJRdnU6nw8mTJ9G4cWN4enq6KUKqCtz9Xig0mtHhf7uRkW8AIMGr/psQVVl2bXzVvvh5yM9QircxiGVeNKDPsS9rNggY8EHFj0lEVMMVHD2Ky9NnQJ/ouKPEzbR33onIRQuhjuaQTyKqHIX5Rvzy2WkkHroqW5/QvS46DKg600FLyr1qKg4vJ6omvv/r8o2EGxA1qQ4JNwDcF33f7SXc+jzHhBtgTzcRUTHMeXlIX7gImZ9+CpTSjxE4YgRCJk2EoFa7KDoiqukunsjArrUnkZ9V/NoRR3cmo+m9EfALZgeiuzDpJqomPt5/wXZb6eOEVcsBIE/+F1Im3UREjnJ37cKV116H6Woxn503KMPDET57FrzvvddFkRFRTWc0mLHvy7P466dLJbbz8lPj/uGNmXC7GZNuomrg75RsHEnOst2XS7o1Cg3aR7S/vRPlpMqXcyE1IiIb0/XruDJrNnJ37Ci5oSAg4In/IHj8C1B4e7kmOCKq8a6ez8HO1SeQdVVXYrv41iG499GG0HqpXBQZFYdJN1E1sHbfedttQZUBhdZxhfH24e3hqbrNXzHlFlED2NNNRHSDKTMTFx57HIYLF0psp2nYEOGvvwaPu+5yUWREVNNZLBL+2HYBB79JgmQpfjqLxlOJzo82RHybUBdGRyVh0k1UxWXpDPj66L890ErvYoaW173NoeWA/HZhAHu6iYgASCYTUl+cXGLCLWg0CBr3HOqMGAFBxd4lIrLSF5hwcMs5XDmXjcBIbzTrHImQGN8yPz4/W48dH55AyqnMEttFNwnE/U80hneA5nZDpkrEpJuoittw+BL0pn+3epDbKkwURHSO7nz7Jyu2p5tJNxFR+uLFyN+7t9h6z/Z3I3zWLKhjYlwYFRFVdRazBd8uPYYr57IBAGkXcvHP3suIbVYHbXrHlZp8X/j7OnZ9dAIFucZi2yhVIjoMqI87O0dCEIRKjZ9uH5NuoirMYpHwyYF/e1QERT4Unucd2rUIboFAbeDtn1Cup9sjAFB53P6xiYiqsZwffsD1D/5Ptk7h74+Qqf+F3yOP8MsuETn4+5cUW8J9s/N/Xcf5v64j9q4gtO0dh+C6Pnb1ZpMF+78+h6M7kks8fkisL7qNaIyAMK4dUVUx6Saqwn5OTMeF6/8ukqHwPglBcJzDUylDywH5nm7O5yaiWq7w1CmkvvyKbJ0yNBSxX3wBVWiIi6MiouqgINeAg98kldjm/J/XcP7Pa4hrHoQ2D1mT7+z0Amz/4G+kXcgt9nGCKKD1g7Fo3SsGokKs7NCpEjHpJqrCPtlnP2/QaVuFFcmVWb2cQ8uJqBYzZ2Xh0rjnIRUUONQJajWi3l3KhJuIirX/63PQ60xlapt07BqSjl1D3aaBuHw2G8ZCc7FtvQM0eGBkU4TX96+kSMmZmHQTVVEXM3TYfSrt3wLBAKVXokO7+IB4RPtG3/4JJYk93UREN5HMZqRMngLjxYuy9WEzZ8KjWTMXR0VE1UXahRyc+K2Y7VhLkHw8o8T6O1oEo8sTjbgVWDXCcQg1kCAIJV5mzZp1W8fevHlzmdt/9NFHaNOmDTw9PeHj44POnTvj22+/tWvz008/QRAEZGVlVTiumuiTAxcg3TSSXOmVCEF0XECj0nq5C7MAU6FjOXu6iaiWSl/8DvL37JGtC3jsUfgP6O/iiIioupAsEn79/DQgs7NXYIQXVBpFuY+pUIq4d2gD9BxzJxPuaoY93TXQ5cv/Lob1+eefY8aMGTh16pStzNvb2yVxTJ48Ge+++y7mzJmDvn37wmg04pNPPsEjjzyCd955B+PGjXNJHNVRodGMLw7Z96zIrVoOOHk+N8CebiKqlXK2bsX1Vatk6zxatULo1KkujoiIqpPTB6/gyrkch3KFSsRDz90FtUaJIzuT8dePl2DUFz+MvIh/qCd6jG6KoCifUttS1cOkuxx+/PgkrqfmuzWGOhFe6PJE4xLbhIX92zPp5+cHQRDsyj744AMsWLAASUlJiI2Nxfjx4zF27FgAgMFgwKRJk7Bp0yZkZmYiNDQUzzzzDKZNm4bY2FgAQL9+/QAAMTExOH/+vGwM+/fvx4IFC7BkyRI8//zztvI33ngDhYWFmDRpEh555BFER1fCsOga6Ns/LyNTd3OvthlK738c2oV5haFxYMnvhzLjHt1ERACAwtOni184LSQEUYsXQVCrXRwVEVUXhkIT9n55VrauZY8Y+Nax7grTvm89tOgWjaM7LuLPny7BVEzy3bhDODoNaVCh3nGqGph0l8P11HxcTXL8xao6WbduHWbMmIF3330XCQkJOHLkCEaPHg0vLy8MHz4cS5YswZYtW/DFF1+gbt26uHjxIi7emMt26NAhhISEYPXq1ejZsycUiuL/4X/66afw9vbGmDFjHOpefPFFLFy4EJs2bcKECROc9VSrtY/3nbe7r/A8D0Gpc2h3f/T9lbc9TbE93RGVc3wiomrAnJ1tXThN5/iZK6hUiFryDpTBwW6IjIiqi8PfnYcux+BQ7hOoRcsH6tqVeXir0b6fNfk+siMZf/10CSaDBQCg0ipw32MN0aAtO0CqOybdtczMmTOxYMEC9O9vnYcWFxeHEydOYMWKFRg+fDiSk5MRHx+Pjh07QhAExMTE2B4bfONLhr+/v13PuZzTp0+jXr16UMv0BERERMDX1xenT5+uxGdWcxy7mIVjl+z3cix21fLKGloOADnFLPTBnm4iqiUksxkpU6bAmCy/J27ojOnwaNHCtUERUbWSeSUfx3bLL754z6D6UKrlO608fNTo0L8+Eh6oi9TELBgLzYhrEQyNB9O1moALqdUi+fn5OHv2LEaOHAlvb2/bZc6cOTh71joEZsSIETh69CgaNmyI8ePHY/v27SUeMzk52e5Yc+fOtdVJkszKEVSqj/dfuKVEgtLbcT63r9oXLUNbVt6JZXu6BcCbW+EQUe2QvnQp8n/5VbbOf+gQBAwa5OKIiKg6kSQJezYkwmJ2/A4c1SgAd7QofZSMh7ca9RJC0Kh9OBPuGoR/yVokLy8PALBq1Sq0a9fOrq5oqHjLli2RlJSEH374ATt37sTgwYPRrVs3bNy4UfaYEREROHr0qO1+YGAgAKBBgwbYs2cPDAaDQ293amoqcnJy0KBBg8p6ajVGZr4B3xyz73EWNZchqrMc2t4bdS9UYiWuXCk3p9srGFBwdUwiqtlMGRm4tux9ZH7yiWy9R0ICwl5+2cVREVF1c/6v67LbfQmigE6DG1TelECqdph0l0OdCC93h3BbMYSGhiIiIgLnzp3D448/Xmw7X19fDBkyBEOGDMHAgQPRs2dPZGRkIDAwECqVCmbzv4s8KJVK1K9f3+EYQ4cOxZIlS7BixQq7hdQAYP78+VCpVBgwYECFn0tN9cXhi9CbLHZlLhlaDhSzRzeHlhNRzWXJz8f1NWuQ8X8fwiIzhxsAlMHBiHxnMRdOI6ISmYxm7PlCfurkXfdFIbAK5BHkPky6y6G0VcOrg9mzZ2P8+PHw8/NDz549odfrcfjwYWRmZmLSpElYuHAhwsPDkZCQAFEUsWHDBoSFhcHf3x8AEBsbi127duGee+6BRqNBQECA7Hnat2+PF154AVOmTIHBYLDbMuydd97B4sWLuXL5LcwWCZ8cuHVoufxWYWpRjXsi7qncAGSTbm4XRkQ1j2Q0InPDBlxb9j7M164V31ClQuSSd6AK4TQbIirZ0Z0XkXOt0KHcw0eFNn3i3BARVSVMumuZUaNGwdPTE2+//TamTJkCLy8vNGvWzLaKuI+PD9566y0kJiZCoVCgTZs2+P777yGK1un/CxYswKRJk7Bq1SpERkYWu2UYACxevBh33XUXli1bhldffRUKhQItW7bE5s2b0adPHxc82+rl59NpuJhRYFcmqDKg0DoO+24f0R6eKs/KO7nFAuTJJN2+TLqJqOaQJAm5W7cibfFiGC/IL5Z2s7BXX4VnQoILIiOi6iwvsxC//3Betu7uvvU4N5sgSFztCpcuXUJ0dDQuXryIqKgouzqdToeTJ0+icePG8PSsxCSHqh1nvxee+fh3bD1un/iqAvZAG/atQ9vZHWajf3z/yjt5XhowP96x/L5pwH1TK+88RERukr9/P9LmL0Dh33+X3lihQMikiagzcqTzAyOiam/7/x1H4qGrDuUhMT4Y+N/WEETO5b5ZSblXTcWfXYiqiD8vZTmUeQX8A/MtZQIEdI7qXLknl1tEDeCcbiKq9gpPnkTagoXI37OnTO19evZE8AvjoYnjcFAiKl1qYqZswg0AnYY2YMJNAJh0E1UJFouE9Dy9faEiH2bNWYe2CSEJqONRp3IDkN0uDJzTTUTVlkWvx5XZryH7yy/L1N6zbVuETH4RHnfd5eTIiKimsJgt+OWzRNm6Ru3DEBbn5+KIqKpi0k1UBWQXGGG8ZU9Hpfc/ABxnf1T6quUAe7qJqEaRJAmXxo9H/s+/lNpW07AhQia/CK+OHbmdDxGVy/FfU3E9Jc+hXK1VoH0/x919qPZi0k1UBaTl6h3K5FYtB4Au0V0qPwD2dBNRDZL12WelJtyqiAgET3gBvr17Q7ixWCgRUVnpcgzY//U52bo2vePg6cttBulfTLqJqoD0W5NuwQCll+Nwpfr+9VHXt27lByDX0y0qAc+gyj8XEZETGS5exNW35xdbr/D3R9Czz8D/0Uchcu9tIqqg3zYlwlBgcigPCPNEsy61Y3EwKjsm3URVQFqu/b6OSq9ECKLRoZ1ThpYDQI5M0u0dBrD3h4iqEcliQeq0aZB0Ooc6QatF4IjhqDNyJBQ+Pm6Ijohqikv/ZOD0gWIWTxvcAAoFvz+RPSbdRFXArT3dSp8Tsu2clnTL9XRzPjcRVTMZa9ei4PDvsnVRS5fCu1NHF0dERDWN2WjBz5+elq2r3zoE0U0CXRwRVQf8GYaoCrCf022GwvukQ5tQz1A0CWzinADk5nQz6SaiakR/LgnpixbL1vkPGcKEm4gqxZEdyci66jiaRq1VoOPAeDdERNUBk26iKuDmnm6F5wWISscP8/vr3u+clXXNRiA/3bGci6gRUTUhmUxInTYVkt5xUUpVZCRCpkxxQ1REVNNkpxfg8A/nZevaPXIHvPw1rg2Iqg0m3URVwM1zupXeLly1HADy0iC3NRl7uomourj+fx+i8NifsnXhc+dC4e3l4oiIqKaRJAm/fHYaZqPFoS64rg/u7MzF06h4TLprIEEQSrzMmjXrto69efPmUtvNmjULLVq0sCvLyMjAhAkTEBMTA7VajYiICDz11FNITk6ucDw1xb893ZLsfG4flQ9ah7V2zsmL2y7MN8I55yMiqkSFp04j/d13ZesChj0Br3ZtXRwREdVE546kI/n4dccKAej8WEOIohNGI1KNwYXUaqDLl/9dFOvzzz/HjBkzcOrUKVuZt7e3y2PKyMjA3XffDbVajeXLl6Np06Y4f/48Xn31VbRp0wb79u3DHXfc4fK4qoqiOd2i5gpEdaZD/b3R90Ilqpxz8txU+XL2dBNRFScZjUidNhUwOu72oI6JQcjEiW6IiohqGkOhCb9+4biVKwDc2SkSobG+Lo6Iqhsm3eWwfcUSXLt4wa0xBEXH4IEx40tsExb2b7Lk5+cHQRDsyj744AMsWLAASUlJiI2Nxfjx4zF27FgAgMFgwKRJk7Bp0yZkZmYiNDQUzzzzDKZNm4bY2FgAQL9+/QAAMTExOH/+fJnifuWVV5CamoozZ87YYqlbty62bduG+Ph4PPfcc/jhhx/K+jLUKIVGM3ILrfs8Kn3kh5bfH+2kVcuB4nu6OaebiKq4a8tXQH/CceFJiCLC/zcPooeH64Miohrn4LdJyM9yXDPCw0eFu/vW3k4jKjsm3eVw7eIFXE48VXrDKmzdunWYMWMG3n33XSQkJODIkSMYPXo0vLy8MHz4cCxZsgRbtmzBF198gbp16+LixYu4ePEiAODQoUMICQnB6tWr0bNnTygUijKd02Kx4LPPPsPjjz9ul/wDgIeHB8aOHYtXX30VGRkZCAysfdss3LyImtzQcrWoxj2R9zgvALntwgD2dBNRlVbw93FcW75ctq7OU0/CMyHBxRERUU107VIu/tx9SbbunoHx0Hg6aSQi1ShMumuZmTNnYsGCBejfvz8AIC4uDidOnMCKFSswfPhwJCcnIz4+Hh07doQgCIiJibE9Njg4GADg7+/vkDyXJD09HVlZWWjcuLFsfePGjSFJEs6cOYO2bWvf3LuioeWCMhMKreNQ77sj7oaXyomLAMn1dCu1gNbfeeckIroNFoMBl6dNBcxmhzpNfH0EPf+8G6IioppGskj4ef0pSBbHBWcjGwagQdtQN0RF1REXUqtF8vPzcfbsWYwcORLe3t62y5w5c3D27FkAwIgRI3D06FE0bNgQ48ePx/bt20s8ZnJyst2x5s6dW2xbSZJZIZtsPd1yvdyAk4eWA/I93T5hgDO2JyMiqgTXli6FPvGMY4VCgfB5/4Oo4bY9RHT7TvyWiivnchzKRYWAzo82cM5WrlQjsae7FsnLywMArFq1Cu3atbOrKxoq3rJlSyQlJeGHH37Azp07MXjwYHTr1g0bN26UPWZERASOHj1quy83PDw4OBj+/v44eVJm3h2AkydPQhAE1K9fvyJPq9pLv7FdmNLb8fURIKBzdGfnBiDX0+3DlcuJqGrSHTmC6//3oWxd0Jgx8LizqYsjIqKaqCDXgH1fnZWtS3igLgLCuBUhlR2T7nIIio4pvVEVjiE0NBQRERE4d+4cHn/88WLb+fr6YsiQIRgyZAgGDhyInj172uZbq1QqmG8azqdUKktNlkVRxODBg7Fu3Tq89tprdkPTCwoKsGzZMvTo0aNWzucG/u3pFrVXHeqaBzdHkEeQcwPIkVm9nPO5iagKshQU4PLUaYDFcZ9cTePGCHpmjBuiIqKaaO+XZ6DXmRzKfYO0aN0r1vUBUbXGpLscSls1vDqYPXs2xo8fDz8/P/Ts2RN6vR6HDx9GZmYmJk2ahIULFyI8PBwJCQkQRREbNmxAWFgY/P39AQCxsbHYtWsX7rnnHmg0GgQEBJTpvHPnzsWuXbvQvXt3vPXWW7jzzjuRlJSEV199FUajEe+9954Tn3XVZp3TbYagyHOoaxjY0LknNxYAhVmO5Vy5nIiqoLRFi2C4ILOLiEqFiP/9D4Ja7fqgiKjGSU3MxD/75Hd36TSkAZTqsi0mTFSEc7prmVGjRuGDDz7A6tWr0axZM3Tu3Blr1qxBXFwcAMDHxwdvvfUWWrdujTZt2uD8+fP4/vvvIYrWt8qCBQuwY8cOREdHI6EcK8PWqVMH+/fvR5cuXTBmzBjUq1cPgwcPRr169XDo0KFavUd3eq4egjIXguA45z3EM8S5Jy92uzD2dBNR1ZJ/8CAy134sWxc8bhy0DRu4OCIiqonMJgt+Wn9atu6OhGDENnPyCESqkQSJq1vh0qVLiI6OxsWLFxEVFWVXp9PpcPLkSTRu3Bienp5uipCqAme9F/os3YPj1/+CV9wyh7rX73kdfev3rbRzObiwD1jd07G8/wfAXYOcd14ionIw5+UjqW9fGC85btujvesuxK5fB0HJwXtEdPv+2HZBdi63SqPAY7PawTtA64aoapaScq+aij3dRG6WnquHqHJcGRNwRU839+gmoqov7e23ZRNuQaNBxP/mMeEmokqRc70Ah75Lkq1r2yeOCTdVGJNuIjeyWCRcy9NDUGbL1od4uGl4uS9XLyeiqiFvz2/I+vxz2brgiROgqcXTk4ioch38Jgkmg+NCjXUivXFXl9rRI0vOwaSbyI0ydQaYLBIEZTE93V7OTrplVi4HAO9Q556XiKgMzLm5uPzqq7J1Hq1bIXDYMBdHREQ1ldlswbkj6bJ1nR9rCFHBtIkqju8eIjdKK9ouTCbp9lB6wEfl49wA5Hq6Nb6Axtu55yUiKoOrb74J0xXHzynBwwMRc+dCEPk1hogqR1pSDox6s0N5ow7hCK/n54aIqCbh/1ZEblS0R7cgM6c72CMYgiA4NwC5pJvzuYmoCsj75Rdkb9wkWxcyZTLUdeu6OCIiqsku/pMpW96wHb8X0e1j0k3kRrakW6an2+mLqAHyC6kx6SYiNzPn5ODy9BmydZ7t70bAo4+6OCIiqukuncxwKFOqRITd4euGaKimYdJN5EYlDS93TdIt19Md7vzzEhGV4Or/3oTp6lWHctHTExFz5jh/FBAR1SqGAhOuJDl+FwuP94dSpXBDRFTTMOkmcqP0XD0g6iEo9A51oZ5OXsxMnwsY8hzL2dNNRG6U9/PPyP7yS9m6kJdegioy0sUREVFNl5qYBckiOZRHNQpwQzRUEzHpJnKjtNxCiMVsFxbsGezck+cUt0c3twsjIvcwZ2cXO6zcq0N7+A8Z7OKIiKg2uCgztBwAohsHujgSqqmYdNdAgiCUeJk1a9ZtHXvz5s1lbv/RRx+hTZs28PT0hI+PDzp37oxvv/3WoZ3ZbMaiRYvQrFkzaLVaBAQEoFevXvjtt98qHGt1kJ6rL367MGcPL5ebzw2wp5uI3ObqvP/BlJbmUC56eSGcw8qJyEnkFlHTeqsQFMndXKhyMOmugS5fvmy7LF68GL6+vnZlkydPdkkckydPxpgxYzBkyBD8+eefOHjwIDp27IhHHnkE7777rq2dJEkYOnQoXnvtNbzwwgs4efIkfvrpJ0RHR+O+++4rV5Jf3ZSUdDt9eLncfG6Ac7qJyC1yf/wR2cV83of89yWoIjgKh4gqX36WHpmX8x3KoxoFQBD5Qx9VDibdNVBYWJjt4ufnB0EQ7Mo+++wzNG7cGFqtFo0aNcKyZctsjzUYDBg3bhzCw8Oh1WoRExODefPmAQBiY2MBAP369YMgCLb7cvbv348FCxbg7bffxuTJk1G/fn00btwYb7zxBiZMmIBJkybh4sWLAIAvvvgCGzduxNq1azFq1CjExcWhefPmWLlyJR5++GGMGjUK+fmOH4Y1QXquHqLMdmGAC4aXs6ebiKoIc3Y2rsyYKVvndc898B80yMUREVFtcekfDi0n51O6O4DqJHNTIoxX3Zv8qUK9EDAgvsKPX7duHWbMmIF3330XCQkJOHLkCEaPHg0vLy8MHz4cS5YswZYtW/DFF1+gbt26uHjxoi05PnToEEJCQrB69Wr07NkTCkXxqzl++umn8Pb2xpgxYxzqXnzxRSxcuBCbNm3ChAkTsH79ejRo0AB9+vSRbfvll19ix44d6Nu3b4Wfd1VUYDAjV2+Cxr+Y4eUezh5eXlxPN5NuInKtq3PnwpSe7lAuensjfM7rHFZORE5z8aT8/txcRI0qE5PucjBezYchOdfdYdyWmTNnYsGCBejfvz8AIC4uDidOnMCKFSswfPhwJCcnIz4+Hh07doQgCIiJibE9NjjY2vPq7++PsLCSE7PTp0+jXr16UKvVDnURERHw9fXF6dOnbW0bN24se5yi8qK2Ncm/e3Q7LqQWqA2ESqFybgByPd0egYBS49zzEhHdJHf3bmR/vUW2LnTqf6EK55QXInIOSZJwUaan2y/YA751PNwQEdVUVXp4udlsxvTp0xEXFwcPDw/Uq1cPr7/+OiTp3yX9JUnCjBkzEB4eDg8PD3Tr1g2JiYlujLrqys/Px9mzZzFy5Eh4e3vbLnPmzMHZs2cBACNGjMDRo0fRsGFDjB8/Htu3by/xmMnJyXbHmjt3rq3u5r9TacrTtqZIyy0EANnh5cEeTh5aDsgn3b6cM0lErmPOysLlmcUMK+/UCX4DBrg4IiKqTTIv66DLNjiUR3FoeZXz3nvvITY2FlqtFu3atcPBgwdLbL948WI0bNgQHh4eiI6OxsSJE1FYWOiiaB1V6Z7uN998E++//z4++ugjNG3aFIcPH8aTTz4JPz8/jB8/HgDw1ltvYcmSJfjoo48QFxeH6dOno0ePHjhx4gS0Wq2bn0HVkpdn3ZN51apVaNeunV1d0VDxli1bIikpCT/88AN27tyJwYMHo1u3bti4caPsMSMiInD06FHb/cBA64dUgwYNsGfPHhgMBofe7tTUVOTk5KBBgwa2tidPnpQ9flF5Udua5N+ebsek2+krlwPySTeHlhORC115Yy7M6dccykUfH4S//hqHlRORU8n1cgNAdGMOLa9KPv/8c0yaNAnLly9Hu3btsHjxYvTo0QOnTp1CSIjjd+b169dj6tSp+PDDD9GhQwecPn0aI0aMgCAIWLhwoRueQRXv6d67dy8eeeQRPPTQQ4iNjcXAgQPxwAMP2H7ZkCQJixcvxquvvopHHnkEd911F9auXYvU1NQaveJ1RYWGhiIiIgLnzp1D/fr17S5xcXG2dr6+vhgyZAhWrVqFzz//HJs2bUJGhvVDSaVSwWw229oqlUq74xQl3UOHDkVeXh5WrFjhEMf8+fOhUqkw4EYPxtChQ5GYmIhvvvnGoe2CBQtQp04ddO/evVJfi6ogPU8PwAJB6ThlwelJtyTJz+lm0k1ELpK7axdyZD73ASB06lSoSpnGRER0uy7J7c8tAJENmHRXJQsXLsTo0aPx5JNPokmTJli+fDk8PT3x4Ycfyrbfu3cv7rnnHjz22GOIjY3FAw88gEcffbTU3nFnqtI93R06dMDKlStx+vRpNGjQAMeOHcOePXtsv1AkJSXhypUr6Natm+0xfn5+aNeuHfbt24ehQ4dWajyqUK9KPZ47Ypg9ezbGjx8PPz8/9OzZE3q9HocPH0ZmZiYmTZqEhQsXIjw8HAkJCRBFERs2bEBYWBj8/f0BWFcw37VrF+655x5oNBoEBMh/KLVv3x4vvPACpkyZAoPBgL59+8JoNOKTTz7BO++8g8WLFyM6OhqANenesGEDhg8fjrfffhtdu3ZFTk4O3nvvPWzZsgUbNmyAl5f7X/vKlpajh6DIhyBYHOqcvl1YQSZgdhxOxe3CiMgVTJmZuDxzlmydV+d74de/n2sDIqJax2y2IOV0lkN5SF0faL2cvK4OlZnBYMDvv/+OadOm2cpEUUS3bt2wb98+2cd06NABn3zyCQ4ePIi2bdvi3Llz+P777/HEE0+4KmwHVTrpnjp1KnJyctCoUSMoFAqYzWa88cYbePzxxwEAV65Ye+pCQ+0TlNDQUFudHL1eD71eb7ufm2vtaTSZTDAajXZtTSYTLBYLTCYTvB+OrYynddtujbE0Wq3W9pjhw4fD09MTS5YswYwZM+Dp6YmmTZti7NixMBqN8PX1xTvvvIOzZ89CFEW0bNkS3377LcxmM8xmM+bPn4+XX34ZDRo0QHh4OP7+++9iz/v222+jefPmWLVqFd544w0oFAo0b94cX331FXr16mX3PNatW4f3338fy5Ytw4svvgiNRoO2bdti9+7duPvuu8v9nJ3h5vdCZcSTkVsArSYHGjguXBasCXbuc85MAUSZ6Rde4UAVeK2JqGa7PO9/MOTmAhr7zz/R2xtBM2bAZDK5KTIiqi2unsuGyWyCcEs2FNnYr0p876zJij7jc3NzkZPz7zRLjUYDzS3/L1y7dg1ms1k23/vnn39kj//YY4/h2rVr6NixIyRJgslkwjPPPIOXX365kp9J2QlSFV7B6rPPPsOUKVPw9ttvo2nTpjh69CgmTJiAhQsXYvjw4bahA6mpqQi/aXXTwYMHQxAEfP7557LHnTVrFmbPnu1Qvn79enh6ejrt+RAREREREdVmOp0Ojz32mEP5zJkzMWvWLLuy1NRUREZGYu/evWjfvr2t/KWXXsLPP/+MAwcOOBznp59+wtChQzFnzhy0a9cOZ86cwQsvvIDRo0dj+vTplf58yqJK93RPmTIFU6dOtQ0Tb9asGS5cuIB58+Zh+PDhtm2rrl69apd0X716FS1atCj2uNOmTcOkSZNs91NSUtCkSRO0b98ekZGRdm0LCgpw6tQp2+p3VHtV9nth8Ip9SNTtgjb0O4e6tb3WIj6g4vuxl+rYZ8D3kx3LR3wHhDd33nmJqFYzZWXh/OAhMGc4zqP07tgREYsWcvE0InKJb5YcxZUk+8VslUoRT8xtD6VK4aaoaoeUlBQAwIkTJ+xyr1t7uQEgKCgICoUCV69etSu/evVqsVsYT58+HU888QRGjRoFwJpD5ufn4+mnn8Yrr7wCUXT9smZVOunW6XQOL4pCoYDFYp0DGxcXh7CwMOzatcuWZOfk5ODAgQN49tlniz3urUMXioY1KJVKqFT2cziMRiNEUZSto9qlst8LKdkGGLRZEKB3qAvzDXPu+y3/CmCR2TbBPxLg+5yInCRt3jzg8mXc+nVW9PVF5IwZUN2y2wURkTMYCky4cjYPksX+R76wBgHw8OTuR86mVFpTUB8fH/j6+pbYVq1Wo1WrVti1axf69u0LALBYLNi1axfGjRsn+5jickjAfdsUV+mku0+fPnjjjTdQt25dNG3aFEeOHMHChQvx1FNPAQAEQcCECRMwZ84cxMfH27YMi4iIsP1RiKois0XC9XwDlN6O24WpRBUCNE5eNVNuuzBBBLxcsD84EdVKOdu2I+f7H2Trwl55GapQF2yVSEQEIDUxC5LFMfmKbsT9uauiSZMmYfjw4WjdujXatm2LxYsXIz8/H08++SQAYNiwYYiMjMS8efMAWHPIhQsXIiEhwTa8fPr06ejTp48t+Xa1Kp10L126FNOnT8fYsWORlpaGiIgIjBkzBjNmzLC1eemll2zDBbKystCxY0ds3bqVe3RTlZaRb4DZIkFdzB7dTh9eKbddmFcIoKjSHwlEVE2ZMjJwRWYtFQDw7tIFvg8/7OKIiKg2uyi3VRiAKO7PXSUNGTIE6enpmDFjBq5cuYIWLVpg69attsXVkpOT7Xq2X331VQiCgFdffRUpKSkIDg62dea6S5VeSM1VLl26hOjoaFy8eBFRUVF2dTqdDidPnkTjxo25yFotV5nvhROpOXhwya/wjFsEhdZ+jkqL4Bb4+MGPb+v4pVrZBUj9w74svAUw5mfnnpeIaqVLEyYid+tWh3LRzw93fLMFqhD2chOR66yffQCZl/Ptyjx8VHjyzY4QRK4r4Wwl5V41letnkVdT/G2CitYSqAxpudb51KIy16EuxNMFXz7lerq5RzcROUHO1q2yCTcAhL36ChNuInKp/Cy9Q8INAFENA5hwk9Mw6S5F0UT/m/f1ptopLy8PgHVBh9uVnqsHBCMEpc6hzulJt8UM5F11LPdl0k1ElcuclYUrs1+TrfPu2hW+vXu7OCIiqu0u/VPc0HLO5ybn4QTOUqhUKnh7eyMlJQVqtdotS8yTe1ksFuTl5SElJQVBQUG2H2JuR1quHoLMfG7ABUl3fjogmR3L2dNNRJXs2qpVMGdmOpQr/PwQPmsmtwcjIpe7eNLxMwkAohpxPjc5D5PuUgiCgNjYWJw4cQKnTp1ydzjkRkFBQahbt26lHCs9Vw9RmS1b5/SkW27lcgDwkd/rkIioIoxXryLzk3WydaHTp0MZzN0SiMi1JEnCRZmebr8QD/jW8XBDRFRbMOkuA41Gg+bNm0Ov13Nudy2lVqsrpYe7SHqeHoLKcT434IqkW2Y+N8CebiKqVNeWvQ9JZmqWd+fO8H3oQTdERES1XeZlHXTZBodybhVGzsaku4xEUYSHB38Bo8qRnqOHUExPd6hnqHNPzp5uInIyw4ULyNq0ybFCEBD84iQOKycit+BWYeQunKBM5AbpeXqIxczpDvZ08pBL9nQTkZOlL1kKmEwO5b59ekPboIEbIiIikl9ETRCAyAZMusm5mHQTuUFaTqHsQmo+ah94KJ08okKup1tUAZ51nHteIqoVCv/5BznffedYoVQi+PnnXR8QEREAs9mClNNZDuXBMb7QeqlcHxDVKky6iVwsX29CvsEMQeWYdDt9aDkA5Mgk3T7h1p96iYhuU/qixbLlAYMHQR0d7dpgiIhuSEvKgVHvuHtLNFctJxdg0k3kYum51oWF5IaXB3u4YDVfueHlnM9NRJVA98cfyPv5Z4dyQatFnWeecUNERERWxc/n5iJq5HxMuolcLD1PD0CSHV7u9JXLAfnh5Uy6ieg2SZKE9IWLZOsCn3gCqhAXfL4RERXj0j+O+3MrVSLC7/BzQzRU2zDpJnKxtBw9oNBBEB0XGXJ60m0yALprjuVcRI2IblP+nj3QHT7sUC76+qLOqJFuiIiIyMpQYMKVJMfOjoh4fyhUTIfI+fguI3Kx9NzCYlcud3rSnXdVvpw93UR0GySLBWmL5Hu564wcCYUfe5KIyH1SErMgWSSH8ijuz00uwqSbyMXScvWyQ8sBFyTdxW0X5hvh3PMSUY2Wu20b9CdOOpQrgoIQ+MR/3BAREdG/LnF/bnIzJt1ELpaeW/we3U5fvTw3Vb6cPd1EVEGSyYT0d5bI1gU9+wxET08XR0REZO+izHxuDx8VgiK93RAN1UZMuolcLD1PD0GVLVvntp5uzukmogrK+uorGM6fdyhXRUUhYNAg1wdERHST/Cw9Mi/nO5RHNQyAIHK7VHINJt1ELpaWIz+8XCEoEKh18twiuZXLAfZ0E1GFWPR6XHtvmWxd8PPjIKjVLo6IiMjexX+4VRi5H5NuIhdLz5MfXl7How4UosK5J5fr6VZ5Ahpf556XiGqkzPWfwnTF8XNFE18fvr17uyEiIiJ7l046Di0HgGgm3VSMzp07Y+3atSgoKKi0YzLpJnIhs0XC9Tw9BJVj0u30+dxA8Xt0CxxeRUTlY87Lw/UVK2TrgidMgKBw8o+IRESlkCRJtqfbL8QDPoFaN0RE1UFCQgImT56MsLAwjB49Gvv377/tYzLpJnKh6/l6WCTIDi8P9gh2fgByPd2cz01EFZCxeg3MWVkO5R7Nm8P7/vtdHxAR0S0yL+ugyzY4lEdzqzAqweLFi5GamorVq1cjLS0N9957L5o0aYL58+fj6tVitt8tBZNuIhdKy9EDMENU5jnUOX0RNQDIkevpZtJNROVjyshAxurVsnXBEydC4OgZIqoCLnKrMKogpVKJ/v374+uvv8alS5fw2GOPYfr06YiOjkbfvn2xe/fuch2PSTeRC6Xn6SEoc2XrQr2cPLzckA/oZVZN5yJqRFRO11eshEWncyj36tABXne3c0NERESOLskMLRcEILIBk24qm4MHD2LmzJlYsGABQkJCMG3aNAQFBaF3796YPHlymY+jdGKMRHSL9Jzitwtz+vBybhdGRJXAePkyMj/9VLYueOJEF0dDRCTPbLYg5XSWQ3lwjC+0XirXB0TVRlpaGj7++GOsXr0aiYmJ6NOnDz799FP06NHDNpJrxIgR6NmzJ+bPn1+mYzLpJnKh4lYuB9y5Rzd7uomo7NLfew+SwXGOpE/37vBodqcbIiIicnQ1KQdGvdmhPLoRe7mpZFFRUahXrx6eeuopjBgxAsHBjh1jd911F9q0aVPmYzLpJnKhtJxC2UXUABesXl7sHt3s6SaistGfS0L2l185Vogigie84PqAiIiKcamY+dzcKoxKs2vXLnTq1KnENr6+vvjxxx/LfEzO6SZyIeucbvmkO9jTXcPL2dNNRGWTvmQJYLE4lPs98gg09eq5ISIiInmX/nHcn1upEhF2h58boqHqZObMmciS2Z0jJycH91dwdw4m3UQulJ6rhyizR7eH0gPeKm/nnpw93UR0GwqOH0fu1q0O5YJKheBxz7khIiIieYYCE64kOX7fioj3h0LF9IdK9vPPP8MgM42qsLAQv/76a4WOyeHlRC6UlquH4OW4kFqoZ6jzt9iRS7q1foDa07nnJaIaIX3RYtly/6FDoYqMdG0wREQlSEnMgmSRHMqjuD83leDPP/8EAEiShBMnTuDKlX9HiZrNZmzduhWRFfz/jkk3kQul5+oh+jn+8uqSPbrlhpezl5uIyiD/4EHk79njUC54eiLomTFuiIiIqHjFzuduwkXUqHgtWrSAIAgQBEF2GLmHhweWLl1aoWMz6SZykTy9CTqDCd4yw8udPp8bkO/p5nxuIiqFJElIX7hIti5w+DAo69RxcURERMWTJAnn/7rmUO7ho0KdCCdP5aNqLSkpCZIk4Y477sDBgwftVi1Xq9UICQmBQqGo0LGZdBO5SHquHhD1EETHOSJO7+mWJPZ0E1GF5P34EwqOHnUoV/j5oc5TT7k+ICKiElxPyUPOtUKH8qhGgRBEJ0/lo2otJiYGAGCRWTD0djHpJnKRtJzCYvfodvp2YfocwKhzLGdPNxGVQLJYkL54sWxdnadHQ+Hj49qAiIhKcfZIumz5HS1cMKqQqq0tW7agV69eUKlU2LJlS4ltH3744XIfn0k3kYtYtwtzXEQNAII9nPwfQU5xK5dHOPe8RFSt5Xz3HfSnTzuUK0NCEPD4426IiIioZOdkkm6FSkTdplxEjYrXt29fXLlyBSEhIejbt2+x7QRBgNlsLvfxmXQTuUhajh6CzHxuwAXDy4vdLow93UQkTzIYkL5EfsGYoLFjIWq1Lo6IiKhkmVfykZGa71Bet0kg1FqmPVS8m4eUO2N4OTeqI3KR9Dy9+4aXy83nBjinm4iKlbVpE4wXLzqUq2Lqwn9AfzdERERUsnNHixlansCh5VQ2RqMRXbt2RWJiYqUel0k3kYuk5eghFJN0B3kEOffk7OkmonKwFBTg2rL3ZeuCnx8PQaVycURERKWTG1ouigJimzn5exbVGCqVyrZfd2Vi0k3kItY53Y5Jd6A2ECqFk7/AFtfT7e3kHnYiqpYyPvkEpnTHL6+aRo3g+2AvN0RERFSy3IxCpF3IdSiPbBQArRd/KKSy+89//oP/+7//q9RjcnIDkYuk5RRC1Dom3U4fWg7I93R7BgFKtfPPTUTVijknB9c/kP+yETzhBQgif68noqpHrpcb4KrlVH4mkwkffvghdu7ciVatWsHLy8uufuHCheU+JpNuIhe5lqeH4O24ernTF1ED5JNuX87nJiJH1//vQ1iyHT+rPFq2hHfnzm6IiIiodGePpDkWCkBccw4tp/L5+++/0bJlSwDA6Vt28BCEiu31zqSbyAVMZguu5xfCS5nnUBfs6YJfYOWGl3MRNSK6henaNWSsXStbFzJpYoW/bBAROZMux4DLZx1/LAyv5wcvP40bIqLq7Mcff6z0Y3KMGJELXM83AIo8CILjFgRO7+m2WIpJurmIGhHZu7Z8BaSCAodyr3s7wbN1azdERERUuqRj6YDkWF4vwQWjCYnKgD3dRC6Qnlv8yuVOn9NdkAFYjI7l7OkmopsYU1KQ+fnnsnUhEya4NhgionIobj53XAsOLaeKOXz4ML744gskJyfDYDDY1X355ZflPh57uolcIC23EKLScdgTAAR7OHl4ObcLI6IySH9vGWB0/IHO98Fe0DZp4oaIiIhKV5hvxKV/Mh3KQ2J84FvHww0RUXX32WefoUOHDjh58iS++uorGI1GHD9+HLt374afn1+Fjsmkm8gFrD3djttYAC4YXl7cdmHs6SaiG/TnkpC9ebNjhUKBoOefd3k8RERldeGva7BYHMeW35HAVcupYubOnYtFixbhm2++gVqtxjvvvIN//vkHgwcPRt26dSt0TCbdRC6QlqOHoJLv6Xb68PKcVPlyJt1EdEP60iXW9R9u4d+/HzRxcW6IiIiobM5yqzCqZGfPnsVDDz0EAFCr1cjPz4cgCJg4cSJWrlxZoWMy6SZygfQ8PUSZOd1qUQ0/TcWGqZQZe7qJqASFJ04g94etDuWCSoWgZ591Q0RERGVjKDQh+USGQ3lghBcCwrxkHkFUuoCAAOTmWkeoRkZG4u+//wYAZGVlQafTVeiYXEiNyAXScuQXUgv2DHb+Fjxyc7oFBeDFxUWICEh75x3Zcv9Hh0IVEeHiaIiIyi75eAbMRsdROuzlpttx7733YseOHWjWrBkGDRqEF154Abt378aOHTvQtWvXCh2TSTeRC6TnySfdTh9aDsj3dHuHAqLC+ecmoipN9/vvyP/5F4dywdMTQU8/7YaIiIjK7tzRYoaWcz433YZ3330XhYWFAIBXXnkFKpUKe/fuxYABA/Dqq69W6JhMuolcIC23EGKQ45zuYE8X/Kcg19PNlcuJaj1JkpC2aJFsXeCwJ6AM4mgYIqq6zEYLzv91zaHcN0iLoChvN0RENUVgYKDttiiKmDp16m0fk0k3kZNJkoT0vFyoQgsd6py+cjkg39PN+dxEtV7+nt9QcPh3h3LR1xd1nnrKDREREZXdxX8yYCw0O5TfkRDi/Kl7VOPk5DiOSC2Or69vuY/PpJvIyfL0JuilLKhk6pw+vNxsAvLTHMt9mXQT1WaSJCG9mF7uOqNGQVGBLxRERK50rphVy+txaDlVgL+/f6k/1kiSBEEQYDY7/thTGibdRE6WlquHqJL/9czpPd35aYDkuMAIh5cT1W6523eg8MQJh3JFUBAC//O4GyIiIio7i9mCpGOOQ8u9/NQIjeWPhlR+P/74o1OPz6SbyMnSc+UXUQOAYA8n/xorN58b4PByolpMMpuRvmSJbF3QM89A9PR0cUREROWTmpiFwnyjQ/kdLYIhiBxaTuXXuXNnpx6fSTeRk6WVkHQ7fXh5sXt0s6ebqLbK/uYbGM6edShXRoTDf/AgN0RERFQ+xQ0t56rlVFF//vkn7rzzToiiiD///LPEtnfddVe5j8+km8jJ0nP1EJWOK5cDLli9nD3dRHQTyWDAtaXvytYFPzcOolrt4oiIiMpHskg4K7NVmNZLhYh4f9cHRDVCixYtcOXKFYSEhKBFixYQBAGSJDm045xuoioqLbcQgsycbl+1L7RKrXNPXmxPN5Nuotooc+NGGFNSHMrVcXHwe+RhN0RERFQ+V8/nQJdtcCiPax4EUSG6ISKqCZKSkhAcHGy7XdmYdBM5WXFzul2yXViOTE+3QgN4BDj/3ERUpVgKCnDt/fdl64JfGA9Bya8ERFT1neXQcnKCmJgY2duVhf/DEjmZdXi5Y9Lt9PncgPzwcp8wgPtXEtU6mevWwZzuuNqvpklj+DzwgBsiIiIqH0mScO6I41aoKq0C0Y0C3RAR1VSpqanYs2cP0tLSYLHY7wQ0fvz4ch+PSTeRk6XlFkLwc0y6nT6fG5AfXs6h5US1jjk3F9dWfSBbFzJhAgSRQzKJqOq7dikPOdcKHcpjmwVBoeLnGFWONWvWYMyYMVCr1ahTp47d/t2CIDDpJqqK0vIzIAQ4LrjgkuHlxfV0E1GtkrF6NSzZjgs6erRqBa9OndwQERFR+RW7ankLDi2nyjN9+nTMmDED06ZNg1hJP0rzJyEiJzKaLcg2OA7nBFwwvNykBwoyHMvZ001Uq5gyMpCx5iPZupCJE+x+wSciqsrOyaxarlCJqNuUQ8up8uh0OgwdOrTSEm6gnD3dFosFP//8M3799VdcuHABOp0OwcHBSEhIQLdu3RAdHV1pgRHVBNfzDMXu0R3s4eztwrhHNxEB11eugkWncyj36tgRnq1buyEiIqLyy7ySj4zUfIfyuk0CodZy8C5VnpEjR2LDhg2YOnVqpR2zTO/QgoICLFiwAO+//z4yMjLQokULREREwMPDA2fOnMHmzZsxevRoPPDAA5gxYwbuvvvuSguQqDpLyy2EKLNdGACEeDl5eDn36Caq9YxXriBz/XrZuuAJE1wbDBHRbZDr5QaAely1nCrZvHnz0Lt3b2zduhXNmjWDSqWyq1+4cGG5j1mmpLtBgwZo3749Vq1ahe7duzucGAAuXLiA9evXY+jQoXjllVcwevTocgdDVNMUt10Y4ILh5cUl3b5Muolqi2vL3odkcNzP1ueBB+BxZ1M3REREVDFy87lFUUBMsyA3REM12bx587Bt2zY0bNgQABwWUquIMiXd27dvR+PGjUtsExMTg2nTpmHy5MlITk6uUDBENU1aMUm3KCgQqHXy/KNih5cz6SaqDQwXLiBr0ybHClFE8PjnXR8QEVEF5VwvQNqFXIfyqEYB0Ho5dgYS3Y4FCxbgww8/xIgRIyrtmGWaHV5awn0zlUqFevXqVTggopokPVcPUeW4YnAdbRBEwcnrGBY7vJxzuolqg/Sl7wJmx50T/B5+GJr69d0QERFRxSQdlV+U9g4OLScn0Gg0uOeeeyr1mBX+1m8ymfDee+9h0KBB6N+/PxYsWIDCQsd984hqs7TcQtme7jBnz+cG5Hu61d6Axsf55yYityo8dQo5333nWKFSIWjcc64PiIjoNpw9kuZYKABxzZl0U+V74YUXsHTp0ko9ZoWX+hs/fjxOnz6N/v37w2g0Yu3atTh8+DA+/fTTyoyPqForbk630+dzA/I93d4uOC8RuV36O0sASXIoDxg0COqoKDdERERUMfnZelw+6zhqMKK+Pzx91W6IiGq6gwcPYvfu3fj222/RtGlTh/XMvvzyy3Ifs8xJ91dffYV+/frZ7m/fvh2nTp2CQqEAAPTo0YOrlhPd4mpuHkQvx+0tgj1d8MusTmaPbm8X9LATkVsVHD2KvN27HcoFrRZ1nhnjhoiIiCou6dg1wPE3RNzRgr3c5Bz+/v7o379/pR6zzEn3hx9+iI8++gjLli1DREQEWrZsiWeeeQYDBgyA0WjEqlWr0KZNm0oNjqi6S8u/Bng5lod4uiD5lUu6Pes4/7xE5FZp77wjWx74n8ehCuEPb0RUvRS3VRjnc5OzrF69utKPWeY53d988w0effRR3HfffVi6dClWrlwJX19fvPLKK5g+fTqio6Oxvpi9QIlqI0mScF0v/x+F04eXSxJQIJN0ewQ497xE5Fb5+/ZBt2+/Q7no7Y3AkSPdEBERUcUV5huR8k+mQ3lIjA98ArVuiIioYso1p3vIkCHo0aMHXnrpJfTo0QPLly/HggULnBUbUbWWU2iCWciSrXP68HKjDjDJLGzInm6iGkuSJKQtXixbF/jUk1AG8Ec3Iqpezv91DRaL49hy9nJTZWvZsiV27dqFgIAAJCQklLgf9x9//FHu45d7ITV/f3+sXLkSv/zyC4YNG4aePXvi9ddfh1bLX5uIbpZezMrlgAuGl8sNLQcATyfvDU5EbpP3448oPPanQ7kiIACBw4a7ISIiottz7oj8iMF6CZwqQ5XrkUcegUajAQD07du30o9f5qQ7OTkZkydPxsmTJ3HXXXdh/vz5+P333/HGG2+gefPmWLx4MXr16lXpARJVV2m5eogq+aTb6cPLddfly9nTTVQjSRYL0hctlq2rM+ZpKLxlFpcgIqrCDIUmJJ9w7EQIjPCCf6inGyKimmzmzJmytytLmed0Dxs2DOL/s3ff8VHU6R/AP7N9N8mm94TQm1KkF0VQEXs9y6ln+XnqYQFFT8TeTtTz1LNycpbTs516eBasKCAISi/Sa0jvyWb7zszvj00CYWYhCZvZ3eTz5pXXZp/v7OyTkGT3mW/T6fDXv/4VGRkZuOmmm2AymfDII4/g008/xdy5c3HppZeGPUGiWBVquzCL3oY4Yye/AVabzw0AVvZ0E3VFDV8uhHfnTkXckJWF5N//PgIZEREdm8LfaiD6JUWcQ8tJSx6Pp2Ux8Z0qr7Nt1eae7tWrV2PDhg3o06cPpk2bhl69erW0DRo0CEuXLsVrr73W4USIuppQRXeaJULbhQEcXk7UBcl+PypffFG1Le3m6dA1DZcjIoole9ZVqMb7sOimTjJr1iz4/X682PSa6vP5MG7cOGzZsgU2mw133303vv32W0yYMKHd525zT/fIkSPx4IMP4ttvv8Xs2bMxZMgQxTE33nhjuxMg6qoqHV7oVIrurPhOHloOHKHo5vByoq6m7r8L4C8sVMSNBT2QdOGFEciIiOjYBPwi9m1STpWzp1mQmhsfgYyoO/j2228xderUlvvvvvsuCgsLsXPnTtTW1uKSSy7BX/7ylw6du81F99tvvw2v14s77rgDxcXF+Mc//tGhJyTqLsobPBCM9Yp4dpwWRXeIOd0cXk7UpUheL6peeUW1Lf3W2yAYjRpnRER07Iq21sLvFRXxPidkHHFVaaJjUVhYiMGDB7fc//bbb/G73/0OBQUFEAQBM2fOxLp16zp07jYPLy8oKMDHH3/coSch6o7KG+sgGP2KeKdvFwaEmNMtANakzn9uItJM7fvvI1Beroib+/eH/eyzIpAREdGx271efdVyzuemzqTT6SDLB7eoW7lyJR544IGW+0lJSaitVe4b36Zzt+Ugp9PZrpO293iirqjMqXwjDGiwXRigPrzcmgTo9J3/3ESkCbHRiep/qK+lkn77TAi6Ng9mIyKKGpIoYe8GZdEdl2hCZk97BDKi7mLQoEH4/PPPAQC//fYbCgsLMWXKlJb2/fv3IzOzYyNW2/SK3LdvXzz55JMoLS0NeYwsy/juu+9w5pln4oUXXuhQMkRdSY1X/Sptp28XBqgPL+d8bqIupebtf0FUueJuGTYU8Ye8SSAiiiWFv9XA6wwo4r1PyICg49By6jx333035syZg1NPPRWnnnoqzjrrrFaLhy9cuBBjxozp0LnbNLx88eLFuPfee/Hwww9j2LBhGDVqFHJycmCxWFBbW4stW7ZgxYoVMBgMmDNnDm666aYOJUPUVfgCEpxiDawqbREbXs753ERdRqC2FjVvvKnalnHHHZzzSEQxa8vyEtU4h5ZTZ7vwwguxcOFCfPHFFzj99NNx2223tWq32Wy4+eabO3TuNvV0DxgwAJ988gl27NiBSy+9FMXFxfj4448xf/58LF68GLm5uZg/fz727duHm2++GXp9+IawFhcX46qrrkJqaiqsViuGDBmC1atXt7TLsowHH3wQ2dnZsFqtOO20045pDzWicKhq9EJncKi2adPTrVJ0s6ebqMuoef11SI2Nirht/DjEjRsXgYyIiI6ds96rump5fIoZOf2StE+IosbLL7+Mnj17wmKxYOzYsfj111+PeHxdXR1uueUWZGdnw2w2o3///li4cOFRn+fUU0/Fc889h9mzZ8Nms7Vqe+ihhzB58uQO5d/mhdQAoEePHrjzzjtx5513dujJ2qu2thYTJ07ElClT8NVXXyE9PR07d+5EcnJyyzFPP/00XnjhBfzrX/9Cr1698MADD2DatGnYsmULLBaLJnkSHa7C4YVgUK5cDghItWpQ/KoW3ezpJuoK/OUVqPn3u6ptGbffrm0yRERhtH1lGWRJVsQHjc+GjkPLu60PP/wQs2bNwrx58zB27Fg8//zzmDZtGrZv346MDOVaST6fD1OnTkVGRgY+/vhj5ObmYv/+/UhKStI++SbtKrq19tRTTyE/Px9vvnlwCN2h4+plWcbzzz+P+++/H+effz6A4NZmmZmZ+PTTT3H55ZdrnjMRENyjWzAq9+hOMCbBqOvkLXz8HsCvspihNVkZI6KYU/2PeZA9HkU8/tRTYR02LAIZEREdO1mWsfVnlfWjBGDghGztE6Ko8eyzz+KGG27AddddBwCYN28evvzyS7zxxhu45557FMe/8cYbqKmpwc8//wxj09aZPXv21DJlhaguuj/77DNMmzYNl1xyCZYsWYLc3FzcfPPNuOGGGwAAe/fuRVlZGU477bSWxyQmJmLs2LFYsWJFyKLb6/XC6/W23Hc4gsOAA4EA/H7lFk9E7VVZ74LV6IYe5lbxbEtu5/+MOSoBncooD2sawJ9vopjmKylB1f8+A8yt/7ZAEJB8yy18DSOimFW2ux711U4Ih1UnuQOSYbUb+PetCwkEggvlORwONDQc7KQym80wH/b65vP5sGbNGsyZM6clptPpcNppp2HFihWq5//ss88wfvx43HLLLfjf//6H9PR0XHHFFZg9e3ZYp0G3R1QX3Xv27MGrr76KWbNm4d5778WqVaswY8YMmEwmXHPNNSgrKwMAxdLtmZmZLW1q5s6di0ceeUQRX7FihWLsPlFHxAF4OOt61ba2zCc5ZsNUthGqBaDFcxNR53rwAdXw7p07gJ07NE6GiCh8cqeqRRuxcOEBrVOhTuRyuQAAgwcPbhV/6KGH8PDDD7eKVVVVQRRF1Xpv27Ztquffs2cPfvjhB1x55ZVYuHAhdu3ahZtvvhl+vx8PPfRQ+L6QdojqoluSJIwaNQpPPPEEAOCEE07A5s2bMW/ePFxzzTUdPu+cOXMwa9aslvvFxcUYPHgwxo8fj9zc3GPOm+iRzzfhq4abIAit5yVd0PcCzB4zu3OffN9y4P3LlPGL5gMDzuzc5yaiTuPbswd7L/89IEmtG/R69Pr4I5jy8yOTGBHRMfJ5Anj3gZUIBFr/fbPYjLji4bHQG9u09jPFiOLiYgDAli1bWtVeh/dyd5QkScjIyMBrr70GvV6PkSNHori4GH/961/bXHQHAgEsXrwYu3fvxhVXXIGEhASUlJTAbrcjPj6+3TlFddGdnZ2tuAIyaNAgfPLJJwCArKwsAEB5eTmysw/O9SgvL8fw4cNDnvfwoQvNwxoMBkPLuH+iY3HAUQ2foJxzmRaf1vk/Y75aQFI+N+JTAf58E8Ws8pdfgd7tVsSTLr0Ucb17RyAjIqLw2L6iAn6PDKD1Ymn9R2fDYgtPIUbRw2AIlqAJCQmw2+1HPDYtLQ16vR7l5eWt4uXl5S214OGys7NhNBpbDSUfNGgQysrK4PP5YDKZjvic+/fvxxlnnIHCwkJ4vV5MnToVCQkJeOqpp+D1ejFv3ry2fJmttPuyUc+ePfHoo4+isLCw3U/WXhMnTsT27dtbxXbs2IGCggIAwUXVsrKysGjRopb2hoYG/PLLLxg/fnyn50cUSrmrQjWuzXZhyq02AHDLMKIY5t78GxzffquICyYT0m6eHoGMiIjCZ2uIvbkHTeQCat2dyWTCyJEjW9V7kiRh0aJFIeu9iRMnYteuXZAOGRm2Y8cOZGdnH7XgBoCZM2di1KhRqK2thdVqbYlfeOGFrfJoj3YX3bfffjv++9//onfv3pg6dSo++OCDVouShdMdd9yBlStX4oknnsCuXbvw3nvv4bXXXsMtt9wCABAEAbfffjsef/xxfPbZZ9i0aROuvvpq5OTk4IILLuiUnIjaosZTqRrPsCm3NQg7V616nFuGEcWsyr//XTWefMUVMIa40k9EFAuqihyo2O9QxDN72ZGa0/5hvNT1zJo1C/Pnz8e//vUvbN26FdOnT4fT6WxZzfzqq69utdDa9OnTUVNTg5kzZ2LHjh348ssv8cQTT7TUkEfz008/4f7771cU6D179mwZGt9eHSq6169fj19//RWDBg3CbbfdhuzsbNx6661Yu3Zth5IIZfTo0ViwYAHef/99HH/88Xjsscfw/PPP48orr2w55u6778Ztt92GG2+8EaNHj0ZjYyO+/vpr7tFNESPLMhr86r3N6bb0zk8gVE83twwjikmuNWvg/OknRVxnsyH1xhsikBERUfhsWa6yTRiAwRNzNM6EotVll12GZ555Bg8++CCGDx+O9evX4+uvv25ZXK2wsBClpQd/jvLz8/HNN99g1apVGDp0KGbMmIGZM2eqbi+mRpIkiKKoiBcVFSEhIaFDX4Mgy7JyB/p28Pv9eOWVVzB79mz4/X4MGTIEM2bMwHXXXQdBiI1N7IuKipCfn48DBw4gLy8v0ulQjKtz+TDm1btgTvtR0bbs8mVINCd2bgL/vRHY+GHrmDkRmNP5U0KIKLxkWUbh1dfAtWqVoi11+p+QMXNmBLIiIgqPgF/EW7OXw+sKtIobzHpc99REmCxRvfwUdVC0116XXXYZEhMT8dprryEhIQEbN25Eeno6zj//fPTo0QNvvvlmu8/Z4Z9kv9+PBQsW4M0338R3332HcePG4frrr0dRURHuvfdefP/993jvvfc6enqimFXp8EJnqFfEDYIJdtORF4sIC7Webht7uYlikWvFCtWCW2e3I7VpWB0RUazas75SUXADQL+RGSy4KWL+9re/Ydq0aRg8eDA8Hg+uuOIK7Ny5E2lpaXj//fc7dM52/zSvXbsWb775Jt5//33odDpcffXVeO655zBw4MCWYy688EKMHj26QwkRxboKhxeCoUERtxtTtRn94apRxriIGlHMkWUZFc+rz+VOvf566I+y4isRUbTbGmJo+SAOLacIysvLw4YNG/DBBx9g48aNaGxsxPXXX48rr7yy1cJq7dHuonv06NGYOnUqXn31VVxwwQWq2x/16tULl19+eYcSIop1lQ4vBKOy6E6zajCfGwDcKkW3lYuoEcWaxh8Xw7NxoyKuT01FylVXqjyCiCh21Fe6UbRNufhrcpYNWb15UZEiy2Aw4Kqrrgrf+dr7gD179rRs2RVKXFxch8a6E3UFweHlyqI7O06D7cIA9nQTdQGyJIVcsTztxhugi4vTOCMiovDatiJ0L3esrAtFXdfOnTvx448/oqKiotXWYwDw4IMPtvt87S66KyoqUFZWhrFjx7aK//LLL9Dr9Rg1alS7kyDqSkoa6iDoPYp4nl2DvSZFP+BVFvzcLowotji++Qbe7dsVcUNmJpI4koyIYpwkydj6s7Lo1ukFDBjLbRApsubPn4/p06cjLS0NWVlZrS4CCYLQoaK73VuG3XLLLThw4IAiXlxc3Oa9z4i6suKGctV4drwWe3Sr9HIDLLqJYogcCKDyhRdV29KmT4fObNY4IyKi8Cr8rRrOOq8i3mtoGmx2k8ojiLTz+OOP4y9/+QvKysqwfv16rFu3ruWjo1tkt7vo3rJlC0aMGKGIn3DCCdiyZUuHkiDqSspcFarxTJsGw8vV5nMDnNNNFEPqP/8Cvr17FXFjXh6SLrowAhkREYVXyAXUTuQCahR5tbW1uOSSS8J6znYX3WazGeXlyp680tJSGAxc2p+oxlOpGs+wadHTrbJdGMCebqIYIft8qHrpJdW2tFtvgWBiDxARxTZXgw/7NlYp4vHJZuQP4vsVirxLLrkE3377bVjP2e4q+fTTT8ecOXPwv//9D4mJiQCAuro63HvvvZg6dWpYkyOKRQ1+9cI33abB6uUhh5dzITWiWFD33//CX1ysiJt690biuedGICMiovDatrIUkiQr4gMnZEOn4wJqFHl9+/bFAw88gJUrV2LIkCGK3bpmzJjR7nO2u+h+5plnMGnSJBQUFOCEE04AAKxfvx6ZmZl455132p0AUVfiDYjwohZqfVER7enm8HKiqCd5PKh65VXVtvTbboWg12ucERFReMmyrD60XAAGjddgwVmiNnjttdcQHx+PJUuWYMmSJa3aBEHQpujOzc3Fxo0b8e6772LDhg2wWq247rrr8Pvf/151z26i7qTS4YWgsl2YRZcAs16DxY9CzelmTzdR1Kv94AMEKpRrQpgHDkTCtGkRyIiIKLxKd9ejrtyliOcPTIY9zRqBjIiU9qqsq3KsOjQJOy4uDjfeeGO4cyGKecE9uusV8USTRkUvVy8nikmS04nq1+artqXPmAFB1+4lWIiIos7W5SWq8UETuYAadW0dXvlsy5YtKCwshM/naxU/77zzjjkpolhVEaKnO9WiwdByQL3oNsUDBm4xRBTNat75N8Qa5e+vZdhQxE+ZrHk+RETh5nMHsGuNymieOAN6D9Ng3RuiI5g1axYee+wxxMXFYdasWUc89tlnn233+dtddO/ZswcXXnghNm3aBEEQIMvBhRCaNw0XRbHdSRB1FRUNbghGhyKeFadR0a02vJzzuYmimtjQgOo33lBty5g5s+X1lYgolu1cXY6AT1LEB4zNgt7I0TwUWevWrYPf72/5PJSOvia3u+ieOXMmevXqhUWLFqFXr1749ddfUV1djTvvvBPPPPNMh5Ig6ioK66sgCMoLT3n2LG0SUFtIjUPLiaJa9ZtvQmpQjpCxjRkD2/jxEciIiCj8toTYm3swh5ZTFPjxxx9VPw+Xdl9WWrFiBR599FGkpaVBp9NBp9PhxBNPxNy5czu0khtRV1LsKFON97BrtCKn2vByFt1EUStQU4Paf72t2pZ+O3u5iahrqC5uRMU+5cXFjJ52pObGRyAjorZraGjAp59+im3btnX4HO0uukVRREJCAgAgLS0NJSXBBREKCgqwffv2DidC1BWUu5RzlQAgKy5TmwTUero5vJwoalXP/yckl3Il37hJJ8E2YkQEMiIiCr8tIRZQGzyR24RR9Ln00kvx0ksvAQDcbjdGjRqFSy+9FEOGDMEnn3zSoXO2u+g+/vjjsWHDBgDA2LFj8fTTT2P58uV49NFH0bt37w4lQdRV1HjUi25N9ugWA4BHuXI6twsjik7+8grUvveealv6jJkaZ0NE1DlEv4TtvyhHAhpMOvQbpVGnBFE7LF26FCeddBIAYMGCBZBlGXV1dXjhhRfw+OOPd+ic7S6677//fkhScBGERx99FHv37sVJJ52EhQsX4oUXXuhQEkRdRYNfpacZQLpNg1U5PXUAZGWcw8uJolL1P+ZB9noV8YSpU2E9/rgIZEREFH57NlTC6wwo4n1HZsBk7fBGSkSdpr6+HikpwffPX3/9NS6++GLYbDacffbZ2LlzZ4fO2e6f9GnTprV83rdvX2zbtg01NTVITk7m3DPq1mRZhkuqUfxSCdAjxaJB4Rtyj272dBNFG19RMWo/+ljZIAhIn3Gb9gkREXWSLctCDS3nAmoUnfLz87FixQqkpKTg66+/xgcffAAAqK2thcVi6dA529XT7ff7YTAYsHnz5lbxlJQUFtzU7dW5/IBeZQVifTJ0ggZbYahtFwYA1uTOf24iapeqV14BmrYmOZT9nHNg7tcvAhkREYVfQ5UbRdtqFfGkTBuy+iRGICOio7v99ttx5ZVXIi8vDzk5OZg8eTKA4LDzIUOGdOic7erpNhqN6NGjB/fiJlJR4fBCMCiL7kSjRj3NaouoAezpJooy3r17Uf/pp8oGvR7pt96ieT5ERJ1l68+htwljhx1Fq5tvvhljxozBgQMHMHXqVOh0wc6z3r17d3hOd7uHl993332499578c4777SMdScioDJE0Z1q1WARNeAIw8v5e0oUTapefAloWhvlUEkXXQhTQUEEMiIiCj9JkrFthbLo1ukEDBiXFYGMiNpu1KhRGDVqFGRZhizLEAQBZ599dofP1+4xry+99BKWLl2KnJwcDBgwACNGjGj1QdRdldQ3QGdwKuJZcVoV3ezpJop2nu3b0bBwoSIuGI1Imz49AhkREXWOA1tq0FirXCyy57A02OymCGRE1HZvv/02hgwZAqvVCqvViqFDh+Kdd97p8Pna3dN9wQUXdPjJiLqy/XXK7TAAIC9Bo6u5Ied0s6ebKFpUvvCiajzpsstgzOGiQkTUdWwNsTf3oAncm5ui27PPPosHHngAt956KyZOnAgAWLZsGf70pz+hqqoKd9xxR7vP2e6i+6GHHmr3kxB1B0UO9aK7Z5JGb6TVeroNFsBk0+b5ieiI3Js2oXHRIkVcsFiQdtONEciIiKhzuBp82LuhShGPSzKjx3EcgUfR7cUXX8Srr76Kq6++uiV23nnn4bjjjsPDDz/coaJbgyWVibqHcmeFalyznm6XcnVQDi0nih6Vz/9dNZ5y1ZUwpKdrnA0RUefZ/ksZJElWxAdNyIZOxwXUKLqVlpZiwoQJiviECRNQWqq+OODRtLvo1ul00Ov1IT+Iuqtqb6VqPMMWwTndHFpOFBVcq1bBuXy5Iq6Li0PK9ddHICMios4hyzKHllNM69u3L/7zn/8o4h9++CH6dXBbz3YPL1+wYEGr+36/H+vWrcO//vUvPPLIIx1KgqgraPBVq/5GaVZ0q83p5srlRBEnyzIq/h6il/uaa2BITtY4IyKizlO2pwG1ZS5FPG9gMuxp1ghkRNQ+jzzyCC677DIsXbq0ZU738uXLsWjRItVivC3aXXSff/75itjvfvc7HHfccfjwww9xPa/YUzflkpRFrx5W2IwazalW2zKMRTdRxDmX/wz36jWKuC4xESnXXat9QkREnShUL/fgiVwskmLDxRdfjF9++QXPPfccPv30UwDAoEGD8Ouvv+KEE07o0DnbXXSHMm7cONx4IxeCoe7J4xcREOoUv1Bxeo2KXkkK0dPNOd1EkSTLMipD9HKnXn899AkJGmdERNR5fJ4Adq5RrnFjthnQa3haBDIi6piRI0fi3//+d9jOF5aF1NxuN1544QXk5uaG43REMafS4YXO2KCI240aFb3eekCWlHHO6SaKqMYffoBn0yZFXJ+aipSrroxARkREnWfX6goEvKIiPmBsFgxGrv1E0a2kpAR33XUXGhqU7+nr6+vx5z//GeXl5R06d7t7upOTkyEIB1cdlGUZDocDNpstrFcDiGJJeYMHgkH5C5pm1WhFYrWh5QCHlxNFkCxJqPz7C6ptaTfdCJ2N2/kRUdeyJdQCahxaTjHg2WefRUNDA+x2u6ItMTERDocDzz77LJ566ql2n7vdRfdzzz3XqujW6XRIT0/H2LFjkczFYKibKqyrhqDzK+JZcZnaJBCy6ObwcqJIafjqK3h37FDEDVlZSLrssghkRETUeaqLG1G+V9kBkVGQgLS8+AhkRNQ+X3/9NebNmxey/eqrr8YNN9ygTdF97bXXtvtJiLq6/XXqV3ZzNdujW2W7MIDDy4kiRA4EUPXiS6ptadOnQ2c2a5wREVHn2rpcff9i9nJTrNi7dy969OgRsj0vLw/79u3r0LnbPaf7zTffxEcffaSIf/TRR/jXv/7VoSSIYl2Ro0w13itJo/0o1RZRAzi8nChC6v/3GXwqL8zG/HwkXXSh9gkREXUi0S9h+y/K90IGow79Rms06o/oGFmt1iMW1fv27YPV2rFt79pddM+dOxdpacrVBzMyMvDEE090KAmiWFfmVK7UCQC9kjW6uss53URRQ/b5UPXyy6pt6bfeAsFo1DgjIqLOtWdDJTxO5TS7viMzYLaGbbMkok41duxYvPPOOyHb3377bYwZM6ZD5273b0FhYSF69eqliBcUFKCwsLBDSRDFumpPJSAo4xm2DG0SCDW8nHO6iTRX+/HH8Jcop5yY+vSB/ZxzIpAREVHn2vozh5ZT7LvrrrswdepUJCYm4s9//jMyM4OjNMrLy/H000/jrbfewrffftuhc7e76M7IyMDGjRvRs2fPVvENGzYgNZVv8Kl7avBXA6bDgrKANKtGe1KqDS/XGQETFy4h0pLk8aD6VfVFWNJvuw2CnlvmEFHX0lDtxoGtyvchSZk2ZPdNjEBGRB0zZcoUvPzyy5g5cyaee+452O12CIKA+vp6GI1GvPjiizjllFM6dO52F92///3vMWPGDCQkJGDSpEkAgCVLlmDmzJm4/PLLO5QEUaxzicoXG6OQCINOoyFVaj3dtlRAUOl+J6JOU/ve+whUViri5sGDkHD61AhkRETUubb9XArIyvigCdmtdjwiigU33XQTzjnnHPznP//Brl27IMsy+vfvj9/97nfIy8vr8HnbXRE89thj2LdvH0499VQYDMGHS5KEq6++mnO6qVuSJBl+oVaxQIJNp+F8aletMsb53ESaEhudqJ4/X7UtfcYMCLp2L6NCRBTVJEnG1hXKoeU6nYAB4zTawYUozHJzc3HHHXeE9ZztLrpNJhM+/PBDPP7441i/fj2sViuGDBmCgoKCsCZGFCtqXT5Ar9yXMtGk4XQLtZ5ubhdGpKnad96GWKu8AGYdPhzxJ58cgYyIiDpX0bYaNNZ4FfGCIamIS+TWiETNOjz2tV+/fujXr184cyGKSWUNTgiGRkU81ZKuXRJqc7rZ002kGbG+HtVvvKnaln77TA6xJKIuacsy9QXUBnMBNaJW2j3W7eKLL8ZTTz2liD/99NO45JJLwpIUUSzZVV0GQVBOZsrSauVyWQ4xp5tFN5FWqt94E5LDoYjbxo1D3LhxEciIiKhzuRt92LtBuYZFXKIJPY7jexCiQ7W76F66dCnOOussRfzMM8/E0qVLw5IUUSzZV6d+lTfPrtFcJq8DkALKOLcLI9JEoLoaNSH29UyfMUPjbIiItLHjl3JIorLTYeD4bOj0XMOC6FDt/o1obGyEyXT43kiA0WhEQ4NyXitRV1fkKFON90zWaGiV2tBygHO6iTRS/dp8yC6XIh538iTYRpwQgYyIiDqXLMvYsrxEtW3QxGyNsyEKv7q6Ovzzn//EnDlzUFMTfK+9du1aFBcXd+h87S66hwwZgg8//FAR/+CDDzB48OAOJUEUy8qd5arxvikaFd1qQ8sB9nQTacBfXo7a999XbWMvNxF1VeX7GlBT4lTEc/snITHdFoGMiMJn48aN6N+/P5566ik888wzqKurAwD897//xZw5czp0znYvpPbAAw/goosuwu7du1s2B1+0aBHef/99fPTRRx1KgiiWVXmU85kAIDdBo+HlatuFAZzTTaSBqnnzIPt8injC6afDetxxEciIiKjzbV2uPrVuEBdQoy5g1qxZuPbaa/H0008jISGhJX7WWWfhiiuu6NA52110n3vuufj000/xxBNP4OOPP4bVasXQoUPx/fff42RuiULdUIO/GtAfFpSNsJvs2iTAnm6iiPAVFaHuo4+VDYKA9Bm3aZ8QEZEGfJ4Adq5SjvIzWQ3oc4KGO7cQdZJVq1bhH//4hyKem5uLsjL1aaVH06Etw84++2ycffbZivjmzZtx/PHHdygRoljlEpVFtwnJ2m0RFHJOd7I2z0/UTVW9/AoQUC5iaD/3HJj79o1ARkREnW/32gr4vaIi3n9MJgymw3shiGKP2WxWXatsx44dSE/v2IWlY15a0OFw4LXXXsOYMWMwbNiwYz0dUczxo04Rs+k0HNodsqebw8uJOot3zx7U/+9/yga9Hum33qp9QkREGgk1tJx7c1NXcd555+HRRx+F3+8HAAiCgMLCQsyePRsXX3xxh87Z4aJ76dKluPrqq5GdnY1nnnkGp5xyClauXNnR0xHFJLdPhKyvV8QTTRoO7Xap9HQLesCcqF0ORN1M1UsvAZKkiCdddBFMPXpEICMios5XW+ZE6W7l+560/Hik90hQeQRR7Pnb3/6GxsZGZGRkwO124+STT0bfvn2RkJCAv/zlLx06Z7uGl5eVleGtt97C66+/joaGBlx66aXwer349NNPuXI5dUuFtbUQ9F5FPNWi4ZwmtZ5uazKg4x6ZRJ3Bs20bGhZ+pYgLRiPSbp4egYyIiLTBXm7qDhITE/Hdd99h2bJl2LhxIxobGzFixAicdtppHT5nm4vuc889F0uXLsXZZ5+N559/HmeccQb0ej3mzZvX4ScninU7a4pU41lxmdoloTanm4uoEXWayhdeVI0nXX45jNncn5aIuiZRlLBtpbLo1ht06Ddaw/c9RBo58cQTceKJJ4blXG0uur/66ivMmDED06dPR79+/cLy5ESxbm+t+hXf3AQNX3zUtgzjfG6iTuHesAGNP/ygiAtWK9JuvCECGRERaWP/xmq4HX5FvPcJ6bDEGSOQEVHneOGFF1TjgiDAYrGgb9++mDRpEvT6ti8c2Oaie9myZXj99dcxcuRIDBo0CH/4wx9w+eWXt/mJiLqiIof6tgG9kjUcZqU2vJw93USdovLv6i/EKVddCUMHVzQlIooFW34uUY0PPpFDy6lree6551BZWQmXy4Xk5OBuQLW1tbDZbIiPj0dFRQV69+6NH3/8Efn5+W06Z5snfY4bNw7z589HaWkpbrrpJnzwwQfIycmBJEn47rvv4HA4OvZVEcWwskblPpUA0C8lT5sEZFl9eDm3CyMKO+evv8L588+KuC4+HqnXXx+BjIiItNFY60XhZuVFfnuaBbn9krRPiKgTPfHEExg9ejR27tyJ6upqVFdXY8eOHRg7diz+/ve/o7CwEFlZWbjjjjvafM52r7QUFxeH//u//8OyZcuwadMm3HnnnXjyySeRkZGB8847r72nI4ppNZ4q1Xiv5CxtEvC7gIBHGefwcqKwkmU5dC/3tddCn5SkbUJERBratqIUsqyMD5qQA0EnaJ8QUSe6//778dxzz6FPnz4tsb59++KZZ57BnDlzkJeXh6effhrLly9v8zmPaXnjAQMG4Omnn0ZRURHef//9YzkVUUyq9yuLbkGMg9lg1iYBte3CAA4vJwoz57JlcK9Zo4jrExORcu01EciIiEgbsiRjq8rQckEABo7n4pHU9ZSWliIQCCjigUAAZWXBqaU5OTntGukdlj2F9Ho9LrjgAnz22WfhOB1RzHCKyqLXCA2HdqvN5wYAK3u6icJFlmVUPv931bbUG/4IfXy8xhkREWmneGcdGqqUo+p6HJ+K+GSNOhmINDRlyhTcdNNNWLduXUts3bp1mD59Ok455RQAwKZNm9CrV682n5Mb+RIdAz/qFDGbXsOiW20+N8CebqIwcnz/PTy//aaI69PSkHzllRHIiIhIO1uWhVhAbQIXUKOu6fXXX0dKSgpGjhwJs9kMs9mMUaNGISUlBa+//joAID4+Hn/729/afM42r15ORK35RRGSvh6Hz2SyG9O0SyLk8HL2dBOFgyyKqAqxdUjaTTdBZ7VqnBERkXY8Tj/2rKtUxK0JRhQM5QV+6pqysrLw3XffYdu2bdixYweA4LTqAQMGtBwzZcqUdp2TRTdRB+2tLYcgSIp4qkXDbYM4p5uoUzUs/ArenbsUcUN2NpIuuzQCGRERaWfnqnKIAeV7nQHjsqHXc8AsdW0DBw7EwIEDw3IuFt1EHbSjqlg1nhWXqV0SoYaXc0430TGTAwFUvvSialvazdOhM5k0zoiISFtblocYWj6RC6hR11ZUVITPPvsMhYWF8Pl8rdqeffbZdp+PRTdRB+2rL1WN5yZoWHSrLqQmANYk7XIg6qLqP/0U/v2FirixRw8kXXCB9gkREWmostCBqgONinh2n0QkZ8VFICMibSxatAjnnXceevfujW3btuH444/Hvn37IMsyRowY0aFzclwIUQcVhSi6eyVpuLCI2vByaxKg02uXA1EXJPl8qHzlFdW29NtuhWA0apwREZG2QvVyD2IvN3Vxc+bMwV133YVNmzbBYrHgk08+wYEDB3DyySfjkksu6dA5WXQTdVCZq1w13i8tV7sk1Hq6ObSc6JjVffQRAiXKC2umvn1gP+usCGRERKSdgE/Ejl+V73OMZj36jMiIQEZE2tm6dSuuvvpqAIDBYIDb7UZ8fDweffRRPPXUUx06J4tuog6qdlcpYrKsR69kDV+M1OZ0cxE1omPir6hA1Qvqc7nTZ8yAoOdIEiLq2navq4TPHVDE+43OhMnC2anUtcXFxbXM487Ozsbu3btb2qqqlO//24K/NUQdVO9X/tIJoh0Wo4a/VmrDy7ldGFGHybKM0gcegFhfr2izDB6MhKlTI5AVEZG2tnJoOXVj48aNw7JlyzBo0CCcddZZuPPOO7Fp0yb897//xbhx4zp0ThbdRB3kEmsUY0WMcrLGSbCnmyic6j7+GM4lS1Xb0m+fCUEQNM6IiEhb9ZUuFO+oU8RTcuKQ2dOufUJEGnv22WfR2BhcRPCRRx5BY2MjPvzwQ/Tr169DK5cDLLqJOsyHOkXMptew6PZ7AL9TGbdqXPgTdRG+oiJUzH1StS3hjDMQd9JJGmdERKS9rcvVF4odNCGbFx6pyxNFEUVFRRg6dCiA4FDzefPmHfN5OaebqAO8oheyTlnwJhrTtEsi1B7d7OkmajdZFFFyzz2QXC5Fmz49DVkPPcg3m0TU5UmihK0rlEW3Ti9gwLisCGREpC29Xo/TTz8dtbW1YT0vi26iDthfp34VOMWSrl0SakPLAc7pJuqAmn+9DffqNapt2Y89BkMyR5AQUddX+FsNXPU+RbzXsHRY400RyIhIe8cffzz27NkT1nOy6CbqgJ3VxarxTJuWRbfKdmEAe7qJ2sm7cycqn39etS3pkt8hYfJkTfMhIoqUUHtzD+YCatSNPP7447jrrrvwxRdfoLS0FA0NDa0+OoJzuok6YF+Inu5cu4ZDr0INL+c+3URtJvv9KJl9D2SfsmfHmJuLjNn3RCArIiLtOeu92L9JeUE/PtmMvEF8b0Hdx1lnnQUAOO+881pNLZNlGYIgQBTFdp+TRTdRBxxoUC+6eyXlapdEyJ5uvjAStVXVq/Pg2bJF2SAIyHlyLvTxcdonRUQUAdtXlkGSZEV80IRs6HRc04K6jx9//DHs52TRTdQBZc5y1XjflBztknCFWOCBw8uJ2sS9cSOq/vEP1baUa6+FbfRojTMiIooMWZax9WeVDgUBGDiBQ8upezn55JPDfk7O6SbqgGpPlSImixb0SEnSLolQPd3cMozoqCSPByWz7wFUhoiZ+vZB+u0zI5AVEVFklO6uR125cveG/IHJsKdaI5ARUWT99NNPuOqqqzBhwgQUFwfXcnrnnXewbNmyDp2PRTdRB9T7VIruQCISzBoOHlGb021OBPRG7XIgilEVzz4L3969ygaDATlPPQWd2ax9UkREEbJ1mfoCaoMmajiCjyhKfPLJJ5g2bRqsVivWrl0Lr9cLAKivr8cTTzzRoXOy6CbqAKeoLHhNSNJ2H1+1LcNs7OUmOhrnypWoffsd1ba0m6fDetxxGmdERBQ5PncAu9ZWKOKWOCN6D9NwVxaiKPH4449j3rx5mD9/PozGg51ZEydOxNq1azt0ThbdRO0kyzL8qFPErTqNC1614eWcz010RKLDgZJ771VtswwZgrQbb9Q4IyKiyNq5uhwBn6SI9x+bCb2RpQJ1P9u3b8ekSZMU8cTERNTV1XXonPxNImqnBl8DZMGviNuNadomoja8nNuFER1R+RNzEShRLhYkmM3IeepJCAauL0pE3cuW5eo7sgzm0HLqprKysrBr1y5FfNmyZejdu3eHzhlTRfeTTz4JQRBw++23t8Q8Hg9uueUWpKamIj4+HhdffDHKy9VXliYKh9LGMtV4qkXjIViqw8tZdBOF4li0CPULFqi2Zdw5C+YOvpASEcWq6uJGVOxrUMQzetqRmhsfgYyI1L388svo2bMnLBYLxo4di19//bVNj/vggw8gCAIuuOCCNj/XDTfcgJkzZ+KXX36BIAgoKSnBu+++i7vuugvTp0/vUP4xU3SvWrUK//jHPzB06NBW8TvuuAOff/45PvroIyxZsgQlJSW46KKLIpQldQe7a9UXG8mMy9AuCdEPeJUvkhxeTqQuUFOD0gcfUm2zjR2L5Kuu0jgjIqLI27Jc/T3N4IncJoyix4cffohZs2bhoYcewtq1azFs2DBMmzYNFRXKtQgOtW/fPtx111046aST2vV899xzD6644gqceuqpaGxsxKRJk/DHP/4RN910E2677bYOfQ0xUXQ3NjbiyiuvxPz585GcfHDebH19PV5//XU8++yzOOWUUzBy5Ei8+eab+Pnnn7Fy5coIZkxd2Z4a9ReovIQs7ZJQ6+UGOLycSIUsyyh76CGI1cp1EHRxcch54i8QdDHxckhEFDaiX8L2X5Sj9wwmHfqNyoxARkTqnn32Wdxwww247rrrMHjwYMybNw82mw1vvPFGyMeIoogrr7wSjzzySLuHhAuCgPvuuw81NTXYvHkzVq5cicrKSjz22GMd/hpiYvLaLbfcgrPPPhunnXYaHn/88Zb4mjVr4Pf7cdppp7XEBg4ciB49emDFihUYN26c6vm8Xm/L0u8A4HA4AACBQAB+v3KuLtGhShvKYYZyO6Ge9kztfn4clYDOooxbUgH+DBO10rBwIeqW/gSobAOWft99QEYG//YTUbeze10FfF4/hMOqgT4jUiEYZP5dpE4TCAQABGuwhoaDIzfNZjPMh71W+3w+rFmzBnPmzGmJ6XQ6nHbaaVixYkXI53j00UeRkZGB66+/Hj/99FO78vv3v/+Niy66CDabDYMHD27XY0OJ+qL7gw8+wNq1a7Fq1SpFW1lZGUwmE5KSklrFMzMzUVamPu8WAObOnYtHHnlEEV+xYgVsNtsx50xd21j0wdikB5QNhXuwsHCPdokMe00ZKwOwcKF2ORDFikeVf/MBYDfA3xki6rZypypjTjRi4UIN389Qt+NyuQBAUdA+9NBDePjhh1vFqqqqIIoiMjNbj77IzMzEtm3bVM+/bNkyvP7661i/fn2H8rvjjjvwpz/9Ceeddx6uuuoqTJs2DXq9vkPnahbVRfeBAwcwc+ZMfPfdd7BYVHr1OmjOnDmYNWtWy/3i4mIMHjwY48ePR25ubtieh7qmSxfcggPu1nv0SYEEfHbB58i0K3vSOsW2hcACla2NrvgPUDBBmxyIopwsSSi69Va4flVetNUnJaHnfz6EIYVTMoio+3HUePDBY8qFqBLTrbhkzigIghCBrKi7KC4uBgBs2bKlVe11eC93RzgcDvzhD3/A/PnzkZbWsZ2FSktL8fXXX+P999/HpZdeCpvNhksuuQRXXnklJkzo2PvsqC6616xZg4qKCowYMaIlJooili5dipdeegnffPMNfD4f6urqWvV2l5eXIysr9Pzaw4cuNA9rMBgMrTZAJ1JT5SuDF95WMdGfjswkG4x6jeaF+moByaOMx6cC/BkmAgDU/PtdeH9aBrVr07n33wdrJucsElH3tOvXA5ADysJ60LhcmEymCGRE3YmhaXvOhIQE2O32Ix6blpYGvV6v2J0qVL23e/du7Nu3D+eee25LTJKklufdvn07+vTpc9T8zjnnHJxzzjlwuVxYsGAB3nvvPUyZMgV5eXnYvXt3m77OVuds9yM0dOqpp2LTpk2tYtdddx0GDhyI2bNnIz8/H0ajEYsWLcLFF18MILiZeWFhIcaPHx+JlKkbcIrKxZgMcpJ2BTcAuJQ5AODq5URNvHv3ouKZZ1TbEs8/D/apKmMqiYi6AUmSsfVn5d7cgk7AgHEaLgpL1AYmkwkjR47EokWLWrb9kiQJixYtwq233qo4fuDAgYr68f7774fD4cDf//535Ofnt+v5bTYbpk2bhtraWuzfvx9bt27t0NcR1UV3QkICjj/++FaxuLg4pKamtsSvv/56zJo1CykpKbDb7bjtttswfvz4kIuoER0Lv+SHX3YAh10ctuk0HqIaavVy7tNNBDkQQMk990D2KEeDGLKykHnffRHIiogoOhRtrUFjrVcR7zkkFXGJGk2TI2qHWbNm4ZprrsGoUaMwZswYPP/883A6nbjuuusAAFdffTVyc3Mxd+5cWCwWRf3YPCL68PiRNPdwv/vuu1i0aBHy8/Px+9//Hh9//HGHvoaoLrrb4rnnnoNOp8PFF18Mr9eLadOm4ZVXXol0WtRFVburAUFWxO1GjXuY1YpuYxxg4IslUfU/X4dnw0bVtpwn/gL9UYayERF1ZVuWK3u5AWDwxByNMyFqm8suuwyVlZV48MEHUVZWhuHDh+Prr79uWVytsLAQujBu/Xn55Zfjiy++gM1mw6WXXooHHnjgmEdRx1zRvXjx4lb3LRYLXn75Zbz88suRSYi6lXJXuWo8xZKubSJulaKbQ8uJ4Nm6FZUhXg+Sr7wScR1cAIWIqCtwN/qwd0OlIm5LNKHHcRwtR9Hr1ltvVR1ODijrw8O99dZb7XouvV6P//znP6qrlm/evLldPebNYq7oJoqkA/XqW9FlxmVom4janG5bsrY5EEUZyedDyd2zVfeqNxUUIOOuOyOQFRFR9Ni+sgySqByxN3B8NnRark1DFMXefffdVvcdDgfef/99/POf/8SaNWsgimK7z8nfLqJ22FtbohrPTdB44RG14eXs6aZuruqFF+DduVPZoNMh56knobNatU+KiChKyLL6AmoAMGhCtsbZEEW/pUuX4pprrkF2djaeeeYZnHLKKVi5cmWHzsWebqJ2KGxQf7HqlaTxPCi14eVWDguj7su1Zg2qX39DtS31hhtgHT5c24SIiKJM+b4G1JQ4FfHc/klIyrBFICOi6FNWVoa33noLr7/+OhoaGnDppZfC6/Xi008/xeDBgzt8XvZ0E7VDubNCEZMlI/ISNRzaLYmAu04ZZ083dVOS04mSe+YAsnLIpHngQKTfcnMEsiIiii5bQyygNogLqBEBAM4991wMGDAAGzduxPPPP4+SkhK8+OKLYTk3e7qJ2qHKo1x8RPYnItNu0S4Jdx0AZXHB7cKouyr/61/hP3BAEReMRuQ89RQEkykCWRERRQ+fJ4Cdq5SLwZqsBvQ5QePFYImi1FdffYUZM2Zg+vTp6NevX1jPzZ5uonao91UpYlLAjvQEDbfqUltEDWBPN3VLjUuXou6DD1Xb0mfOgGVAf40zIiKKPrvXVsDvVS7+1H9MJgwmvcojiLqfZcuWweFwYOTIkRg7dixeeuklVFUp3/t3BItuonZwisq51DopEfFmDQeNqM3nBgArVy+n7kWsq0PpffertllHjEDKdddpnBERUXQKNbSce3MTHTRu3DjMnz8fpaWluOmmm/DBBx8gJycHkiThu+++g8Ph6PC5WXQTtZHT74QIjyJu1aVAEATtEgnZ083h5dS9lD32OAKVyikfgs2GnCfnQtCz94aIqKbUidLd9Yp4Wn480nskRCAjougWFxeH//u//8OyZcuwadMm3HnnnXjyySeRkZGB8847r0PnZNFN1EblLuVcKABINGo8rFttuzCAw8upW2n46is0fPmlalvm3XfD1KOHxhkREUWn0NuEsZeb6GgGDBiAp59+GkVFRXj//fc7fB4W3URtVOFSrlwOACkWjRcgCdXTzS3DqJvwV1Sg7OFHVNviTjoJSZddqnFGRETRSRQlbF+pLLr1Bh36j8mMQEZEsUmv1+OCCy7AZ5991qHHs+gmaqOyRvWe7kxbhraJhJrTzZ5u6gZkWUbpAw9ArFcOldQlJiL78ce0ne5BRBTF9m+shtvhV8R7n5AOS5wxAhkRdU8suonaaF+d+vCs3ASNrxSrDS83WACTTds8iCKg7uOP4VyyVLUt64EHYMxkzw0RUbMty0tU44MnZmucCVH3xqKbqI0ONJSpxguSsrRNRK3oZi83dQO+oiJUzH1StS3hzDNgP/ssjTMiIopejhoPCn9TTkmzp1mQ2587nhBpiUU3URuVOZXDy6VAHLLtGq/8qTa8nPO5qYuTRREl99wDyeVStOnT05D14IMcVk5EdIh13xVClpXxQRNyIOj495JISyy6idqo2qPcmkgO2JGeYNY2EbWF1Gy8Yk1dW82/3oZ79RrVtpzHH4chmb8DRETNXA0+bFmmHFou6AQMHK/xCD0iYtFN1FZ1vipFTPYnIkPzopvDy6l78e7cicrnn1dtS7rkEsSffLK2CRERRbkNPxyA6JcU8f6jMxGfbIlARkTdG4tuojaQZAkusVYRlwN2pMSZNExE4vBy6lZknw/Fs2dD9vkUbca8PGTMnh2BrIiIopfX5cfmxUWqbSOmFWicDREBLLqJ2qTGUwMZyivGFl0yDHoNf4289YCszIM93dRVVc2bB++WrcoGQUDO3Cegj4/TPikioii2aUkxfB5REe89PB0pOfybSRQJLLqJ2qDcpb5Ht92Ypm0iakPLAcDGnm7qetwbN6LqH6+ptqVcey1so0drnBERUXTz+0RsWHRAtW3EGezlJooUFt1EbVDhrFCNp5jTtU0kZNHNnm7qWiSPByWz7wFEZW+NqW8fpN8+MwJZERFFty0/lcDT6FfE8wclI7OnPQIZERHAopuoTSpc6kV3RpzGRbfafG6Ac7qpy6l49ln49u5VNhgMyHnqKejMGi9gSEQU5cSAhHXfFaq2jTyzp7bJEFErLLqJ2qDIUaYaz0vQeNsNte3CAA4vpy7FuXIlat9+R7Ut7ebpsB53nMYZERFFv+2/lMFZ51XEs3onIqdfkvYJEVELFt1EbXCgoVQRkyU98uyc000UTqLDgZJ771VtswwdirQbb9Q4IyKi6CdJMtZ+vV+1beSZBRAEQeOMiOhQLLqJ2qBMZU63HLAjw67xXpehero5vJy6iPIn5iJQorzIJZjNyHlyLgSDIQJZERFFt91rK1Bf6VbEU3PjUXA8130hijQW3URtUOWuVMSkgB0ZCRoX3WpzunVGwJygbR5EncCxaBHqFyxQbcu4806Ye/fWOCMiougnyzLWfMVebqJoxqKbqA3qfFWKmBxIRHqCxos5qfV021IAvqBSjAvU1KD0wYdU22xjxyL5qis1zoiIKDbs31yN6uJGRTwx3Yo+IzIikBERHY5FN9FReAIeeCXli5nsT0CG5kV3rTLG7cIoxsmyjLKHHoJYrbyopIuPR87cJyDo+HJFRHS4YC/3PtW2EWcUQKfjRXmiaMB3MURHUelSDi0HAIOchDizxvNL1Xq6OZ+bYlzDZ5/B8d33qm2Z994LY06OxhkREcWGkh11KNvToIjHJ5sxYKzGO6wQUUgsuomOotxVrhq3GzVeuRxQn9PNlcsphvlLS1H22OOqbfGnnorECy/QNiEiohiy5ut9qvHhU3tAb+DbfKJowd9GoqOoVFlEDQBSLBoX3bKsvmUYi26KUbIkoeTeeyE1Kqdv6JOTkf3oI1wAiIgohPJ9DTiwVTntzBJvxOATOUKIKJqw6CY6igqXcrswAMi0ZWqbiNcBSH5lnHO6KUbVvvc+XCtWqrZlPfoIDKn82SYiCiXUvtzDTs2H0aTXOBsiOhIW3URHUdpYphrPTdB4rpTa0HKAc7opJnn37kXFM8+otiWefx7sU6dqnBERUeyoKXFiz3rlSDyTRY8hJ+dGICMiOhIW3URHUeRQFt2yaEWWXeO9sdUWUQM4vJxijhwIoOSeeyB7PIo2Q1YWMu+7LwJZERHFjrXfqPdyHz85D2abUeNsiOhoWHQTHUWxo1QRk/z2COzRrbJdGMDh5RRzqv/5OjwbNqq25TzxF+jtdo0zIiKKHQ1VbuxYpVzk1WDUYdgp+RHIiIiOhkU30RE0+Bqwx7FNEZcDSREoukP0dHN4OcUQz9atqHz5ZdW25CuvRNyECRpnREQUW9Z+WwhZkhXxwSfmwGY3RSAjIjoaFt1ER/Bzyc+QZFERDzh7I0ProjvUnG4OL6cYIfl8KLl7NuBXLgho6tkTGXfdGYGsiIhih7Pei60/lyjiOp2A4VN7RCAjImoLFt1ER7D0wFLVuNg4MAI93Sy6KbZVvfACvDt3Kht0OuQ8ORc6q1X7pIiIYsj67w9ACih7uQeMy0JCiiUCGRFRW7DoJgpBlEQsK16miEu+FMCfgdS4KBheLugBc6K2eRB1gGvNGlS//oZqW+qNN8A6fLi2CRERxRiP04/NS4uVDQIwYlqB9gkRUZux6CYKYVPVJtR6lYuXBRoHIjXeAr1O0DYhteHl1mRAx19jim6S04mSe+YAsrJ3xjxoENJvvjkCWRERxZaNPxYh4FVOees7IgNJmbYIZEREbcV360QhLC1SH1oeaByo/XxuQL2nm0PLKQaUP/1X+A8cUMQFoxE5Tz4JwcSFf4iIjsTnCWDjD8q/owAw4gz2chNFOxbdRCEsKVqiiMmSCaKrN3KSIjD3VG3LMG4XRlGucelS1H34oWpb+swZsAzor3FGRESx57efSuB1BRTxguNTkZ6fEIGMiKg9WHQTqShtLMWO2h2KeMDZF5ANGN87AsWuWk83twujKCbW1aH0vvtV26wjRiDluus0zoiIKPYE/CLWf1+o2jbyzJ7aJkNEHcKim0jFT8U/qcZFxyAAwOQB6VqmE5wLqzanm8PLKYqVPfY4ApWVirhgsyHnybkQ9PoIZEVEFFu2rSiDq96niOf0S0J2Hy6mShQLWHQTqVAbWg4AAecA9EixoVdanLYJ+V1AwKOMs+imKNXw1Vdo+PJL1bbMu++GqQf3kyUiOhpJlLD2m/2qbSPP5FxuoljBopvoMO6AG7+U/qKIi+48yAE7pgxIhyBovHJ5yD26Oaeboo+/ogJlDz+i2hZ30klIuuxSjTMiIopNO1dXwFGtvOie3iMB+YN44Z0oVrDoJjrMr6W/wit6FfFA4wAAwOQBGVqnpD60HOCcboo6siyj9IEHINbXK9p0iYnIfvxx7S9aERHFIFmSsebr0L3c/FtKFDtYdBMdJvRWYYNgMugwLloWUQPY001Rp+7jj+Fcov47lPXgAzBmRuCiFRFRDNq7sQq1pU5FPDnLht7DNF5bhoiOCYtuokPIsqw6n1sKJEDy5GB871RYTRFY/Cnk8HL2dFP08BUVoWLuk6ptCWeegcSzz9Y4IyKi2CTLMtZ8tU+1beQZBRB07OUmiiUsuokOsaN2B8pd5Yp4cGi5TvtVy5uFKro5vJyihCyKKLnnHkgul6JNn56GrAcfjEBWRESxqWhbLSr2OxTxhFQL+o7OjEBGRHQsWHQTHSLUquUHtwqL0NDYUHO6ObycokTNv96Ge/Ua1bacxx+HITlZ44yIiGJXqF7uEaf3gF7Pt+9EsYa/tUSHUCu6ZUmPgLMveqZGYKuwZqpzugXAmqR1JkQK3p07Ufncc6ptSZdcgviTT9Y4IyKi2FW6ux7FO+oUcavdhIETsrVPiIiOGYtuoiY1nhpsqtykiIuu3oBsjlwvN6A+vNyaBOgiML+c6BCyz4fi2bMh+/2KNmNeHjJmz45AVkREsWvt1/tU48NPy4fByNd9oljEopuoybLiZZAhK+KBxoEAgJMjNZ8bUO/p5nxuigJV8+bBu2WrskEQkPPkXOjjIzQ6hIgoBlUVObBvk/I132wz4PhJuRHIiIjCgUU3UZMlB9TncwcaB8Js0GF8JLYKa6Y2p5vzuSnC3Bs3ouofr6m2pVx3HWyjRmmcERFRbFsbYl/uIVPyYLIYNM6GiMKFRTcRAL/ox88lPyviojcDsj8V4/ukwhLJIV2uWmWM24VRBEkeD0pm3wOIoqLN3K8v0mfOiEBWRESxq67chV1rKhRxg1mPYVPyI5AREYULi24iAGsr1qLR36iIi01Dyyf3j+DQckB9eDl7uimCKp59Fr69e5UNBgOyn3wSOrNZ+6SIiGLYum/3Q1bOcsPxJ+XAEm/UPiEiChsW3UQAlhYtVY0HHE1FdyQXUfN7AL9TGbdyCyaKDOfKlah9+x3VtrSbp8N63HEaZ0REFNscNR5sW1mmiOsMAoaf1iMCGRFROLHoJoJ60S2LFojuAvRKi0PPSG0VBhxhj24OLyftiQ4HSu69V7XNMnQo0m68UeOMiIhi3/rvCyGJym7uQeOzEZfEkUNEsY5FN3V7++r3YV/DPkU80DgAgB4nR3xoeaiim8PLSXvlT8xFoKRUERfMZuQ8OReCgQv9EBG1h9vhw5afShRxQQBOOL0gAhkRUbix6KZuL+TQ8qb53FMGRnBoOaA+nxvglmGkOceiRahfsEC1LePOO2Hu3VvjjIiIYt+GHw4g4JcU8X6jM5GYbo1ARkQUbiy6qdtbWqwytFwWEHD2h8Wow9heES5uQw4vZ083aSdQXY3SBx5UbbONHYvkq67UOCMiotjndQewaXGxatuIaezlJuoqWHRTt9boa8SasjWKuOguAMQ4jO8d4a3CgNA93ZzTTRqRZRllDz8MsUZ5AUgXH4+cuU9A0PHlhIiovTYvKYLPHVDEew1LQ2pufAQyIqLOwHdJ1K39XPIzArLyxU6MlqHlgPoe3QB7ukkzDZ99Bsd336u2Zd53H4w5ORpnREQU+/w+ERsWHVBtG3lGT22TIaJOxaKburUlRUtU44GW/bmjoOgONbycW4aRBvylpSh77HHVtvhTT0XiBedrnBERUdewdXkp3A6/Ip43MBmZvewRyIiIOguLbuq2JFnCsuJlyrgvCZI3E73T4tAj1RaBzA6jNrzcbAf0Ru1zoW7FV1iI4ll3QmpsVLTpU1KQ/egjEAQhApkREcU2MSBh3bf7VdtGntlT22SIqNNxbxfqtjZXbUaNR9mLHGgcBEDA5AFR0MsNqG8Zxvnc1In8FRWoevVV1H30MRBQTr8AgKxHHoYhlVMciIg6YsevZWis9Srimb3syO2fpH1CRNSpWHRTt3XUoeUDIrw/dzO1nm5uF0adQKyvR/U/X0fNO+9A9nhCHpd4/vmwT52qYWZERF2HJMlY+02hatvIM3tyBBFRF8Sim7ottf25ZckI0dUbVqMeYyK9VVgztTndXESNwkhyu1Hzzr9R/c9/QmpoOOKxhqwsZN53r0aZERF1PXvWVaKu3KWIp+bGo+cQvr4TdUUsuqlbKnOWYVvNNkU84OwLyEZM6BMFW4U14/By6iSy34+6jz9G1SuvIlBZedTj9ampyHvpJejtXOCHiKgjZFnGmq/3qbaNPKOAvdxEXRSLbuqW1Hq5AUBsHAQgioaWi37Aq9LzyJ5uOgayJKFh4VeofOEF+AvVhzi2YjAg+dJLkTb9TzCkR8nvBhFRDCr8rQZVB5SLUyamW9FnZJSsJUNEYceim7qln4p+Uo0HGgcAQPQsouYOsUc353RTB8iyDOfSpah47nl4tylHeigIAuznnoP0226DKT+/8xMkIuriQvVyj5hWAJ2OvdxEXRWLbup2PAEPVpauVMRFdy7kQCL6pMchPyUKtgoD1BdRAzi8nNrNtXYtKp59Fu7Va9p0fPzkyUi/43ZYBgzo5MyIiLqHkp21KN1Vr4jHJZkxYGxWBDIiIq2w6KZu59eyX+ERlSszR10vN6A+nxtg0U1t5tm+HZXPPY/GxYvbdLx15Ehk3DkLthEjOjcxIqJuZs1X6vtynzC1B/RGncbZEJGWWHRTtxNqPncg2uZzA6F7ujm8nI7Cd+AAKl94EQ1ffAHI8lGPNw8YgIxZdyBu0iQu5ENEFGYV+xtQuEV5Id0Sb8TgE3MikBERaYlFN3UrsiyrFt1SIB6SJze6tgoD1LcLA7iQGoUUqKlB1Usvo/Y//wECgaMeb8zPR/rMmbCfdSYEHXtaiIg6w9qv1Xu5h52SD6M5SnZLIaJOw6KbupWddTtR6ixVxMXGAQB0mNg3FWZDFL34cU43tYN3zx4UXvd/CJSXH/VYfXoa0m++GUkXXwzBZNIgOyKi7qmm1Ind65XbMhotegyZnBuBjIhIayy6qVs52tDyk6NpPjcQek43h5fTYQJVVThww41HLbh1djtS//hHpFx1JXS2KFkwkIioC1v3zX5AZZbPkJPzYLYZtU+IiDTHopu6lSUHlihisqxHwNkPADC5fxTN5wbUi25jHGC0aJ8LRS3J5cKBP02Hv7g45DGCxYKUP/wBqX+8HvrERA2zIyLqvhqq3Nj+q/JiqN6ow7BTuRUjUXfBopu6jVpPLTZUblDERWcvQDKjb0Z89GwV1kxtTjfnc9Mh5EAAxbPuhGfzZvUDDAYk/e5ipE2/GcbMKBvJQUTUxa3/rhCypOzmHjwxBzY7p/YQdRcsuqnbWFa8DLLK+K5A40AAUdjLDaj3dNuStc+DopIsyyj7y19CbgdmGTYUuU8/DVNBgbaJERERnPVebFmuXEdGpxMwfCp7uYm6Exbd1G0cbT73lIFR2AuotpAae7q7LTkQgGfLFrjXb4B7wwa4168POaTcVFCA/HnzYEjmRRoiokjYsOgAxICkiPcfmwl7qjUCGRFRpET1/jBz587F6NGjkZCQgIyMDFxwwQXYvn17q2M8Hg9uueUWpKamIj4+HhdffDHK27ByL3UvfsmP5cXLFXHRmw7ZnwqbSY9RPaOwOFEbXs5F1Lol1+rV2HXaVOy79DKUP/EEGr78MmTBrU9JQf7811hwExFFiMfpx+YlKn+jBWDENI4+Imqvl19+GT179oTFYsHYsWPx66+/hjx2/vz5OOmkk5CcnIzk5GScdtppRzxeC1FddC9ZsgS33HILVq5cie+++w5+vx+nn346nE5nyzF33HEHPv/8c3z00UdYsmQJSkpKcNFFF0Uwa4pG6yvWw+F3KOJi09DyCX3SomurMACQRMBdp4xzu7Bux7t3Lw7c9CcEysqOeqxgsSD/1Vdg6tFDg8yIiEjNpsVF8HtFRbzPCRlIzoqLQEZEsevDDz/ErFmz8NBDD2Ht2rUYNmwYpk2bhoqKCtXjFy9ejN///vf48ccfsWLFCuTn5+P0009H8REWnO1sUT28/Ouvv251/6233kJGRgbWrFmDSZMmob6+Hq+//jree+89nHLKKQCAN998E4MGDcLKlSsxbty4SKRNUUht1XLg4HzuKQOjcD63uw6qe4xweHm3IrlcKJ4xE9IhFxtDEgTkPvNXWIcN6/zEiIhIlc8TwIYfDqi2jTyDvdxE7fXss8/ihhtuwHXXXQcAmDdvHr788ku88cYbuOeeexTHv/vuu63u//Of/8Qnn3yCRYsW4eqrr9Yk58NFdU/34err6wEAKSnBnr41a9bA7/fjtNNOazlm4MCB6NGjB1asWBGRHCk6LS1WzueWRQtEV08AwORo258bUJ/PDXB4eTciyzJKH3wI3p07j36wwYDsxx5FwiF/D4mISBvFO2rx6+d7sH1lKX77qQReZ0BxTI/jUpHeIyEC2RHFLp/PhzVr1rSq93Q6HU477bQ213sulwt+v7+lhoyEqO7pPpQkSbj99tsxceJEHH/88QCAsrIymEwmJCUltTo2MzMTZUcYhun1euH1elvuOxzBYceBQAB+vz/8yVNEFTmKUFJfAjPMreJ+52CY9Tr0SYtDRpwh+v7vG6sAncp+3JYUINpypU5R++F/UPvdd4DZrGzU6WDu0wfW44+HZcgQ2MaNgzEjPfp+jomIurh13xVi9cJ9rWKCyjvs4afn8m80EYI1FxCswRoaGlriZrMZ5sPe81RVVUEURWRmZraKZ2ZmYtu2bW16vtmzZyMnJ6dV4a61mCm6b7nlFmzevBnLli075nPNnTsXjzzyiCK+YsUK2GxRtk8zhcUDSQ8og0kAeogA6rFw4UKNM2qjYa8pY/sA7IvSfCm8EuKBR5V/q1StXtW5uRARUUi5U49+zNpty4G21QhEXZrL5QIADB48uFX8oYcewsMPPxzW53ryySfxwQcfYPHixbBYVDqzNBITRfett96KL774AkuXLkVeXl5LPCsrCz6fD3V1da16u8vLy5GVlRXyfHPmzMGsWbNa7hcXF2Pw4MEYP348cnNzO+VroMiZ8cMMrCprXZDIsgDn7j9Dlmx4/epRGNs7CudJb/gAWHiXMv5/XwOZx2ufD2kmUFOD/Vf9AQGVBUJ0CQko+Pc7MPFvFRFRxO1eV4Ef3j56JX3mTccjbyCnhxEBaFnQbMuWLa1qr8N7uQEgLS0Ner1esTvV0eo9AHjmmWfw5JNP4vvvv8fQoUPDkHnHRXXRLcsybrvtNixYsACLFy9Gr169WrWPHDkSRqMRixYtwsUXXwwA2L59OwoLCzF+/PiQ5z186ELzsAaDwQCj0dgJXwlFitPvxMqKlQig9dwq0V0Ajz8OcSY9xvTJgNEQhcsbeGsAyaOMx6cB/DntsiSfDyV/vhvygQNQW08/7/nnENezp9ZpERGRirJdjZADwhGPSe+RgJ7HZ0AQjnwcUXdhMARL0ISEBNjt9iMeazKZMHLkSCxatAgXXHABgOC040WLFuHWW28N+binn34af/nLX/DNN99g1KhRYcu9o6K66L7lllvw3nvv4X//+x8SEhJa5mknJibCarUiMTER119/PWbNmoWUlBTY7XbcdtttGD9+PFcuJwDAipIVCEjKxUyaVy2f2DcNpmgsuIHQC6lxy7AuS5YklMyeDVeIvSRTp/8JCVOmaJwVERGFUry99qjHjDyjgAU30TGYNWsWrrnmGowaNQpjxozB888/D6fT2bKa+dVXX43c3FzMnTsXAPDUU0/hwQcfxHvvvYeePXu21JDx8fGIj4+PyNcQ1UX3q6++CgCYPHlyq/ibb76Ja6+9FgDw3HPPQafT4eKLL4bX68W0adPwyiuvaJwpRaslRUfeKiwqVy1v5qpRxgwWwMh1B7oiWZZR/pcn4Pjqa9X2uIkTkX6EK7pERKQtZ70XdeWuIx6TnGVD7+FRuC0pUQy57LLLUFlZiQcffBBlZWUYPnw4vv7665bF1QoLC6HTHexEe/XVV+Hz+fC73/2u1Xk6Y854W0V10S3LKnsUH8ZiseDll1/Gyy+/rEFGFEskWcLSIuVWYZI/EZI3OAdk8oAofiFUK7qtKQCvlndJ1f94DbWH7SvZzJCTjZxn/gpBrzbgnIiIIqF4x9F7ucee3xuCjq/bRMfq1ltvDTmcfPHixa3u79u3r/MTaqeoLrqJjsVvVb+hxqMsXAONgwAIGJCZgJwkq/aJtZVbpei2ReGCb3TMaj/6CJXPP6/apouPR/4rr8CQnKxtUkREdETF2+tCtsUnmzFiWgH6nBDFI+qISDMsuqnLWlqs7OUGgICjeWh5FPdyA+pzum0svLoaxw8/oOyhh1XbBJMJea+8DMvAgdomRURER6XW0x2fbMbVT0wAAM7jJqIWLLqpy1pyQDmfW5aMEF19AAAnR33RzZ7urkwOBFDz1luofOFFQJKUB+h0yHnmr4gbM0b75IiI6Igaa72or3Ar4rkDkllsE5ECi27qksqd5dhas1URF519ANmIeLMBowqieBVwSQLcKnPFrFGcM7WZe/NvKH3gAXi3Kn9Gm2U9+CDsp5+uYVZERNQWsiRj5f92q7bl9ueINCJSYtFNXdJPxT+pxoPzuYGJfVOjd6swAPDWA7KojLOnO6ZJLhcqX3gRNW+/rd673STttluRfPllGmZGRERtIcsyln+8C9tXlqm25/ZP0jYhIooJLLqpS4rprcIA9aHlAPfojmGNy5aj7KGH4C8uPuJxyVf8Hmk336xRVkRE1B7bVpRhww8HVNuy+yTCnhbFC7QSUcSw6KYuxyt68UvpL4q46MmGHEgEEAuLqIUoujm8POaIdXUof/Ip1H/66ZEPFASkXHMNMv58F+cDEhFFIVmS8evne1TbDGY9Trqsv8YZEVGsYNFNXc6qslVwB5SLmzT3cg/MSkB2YpRfiVbbLgzg8PIYIssyHN98i7LHHoNYrbIS/SFMffsg+9HHYBtxgkbZERFRexXvqEVjrVcR1xkEnPWnIUjvkRCBrIgoFrDopi5HbdVyAAg4gvO5o37VckB9uzCAW4bFCH9FBcofewyO774/4nGC0YjUP92EtBtugGAyaZQdERF1xPZf1OdxT75iIPIHcSQaEYXGopu6FFmWsbRIuT+3FIiD5MkDAEyJ9vncwBHmdLOnO5rJsoz6/y5A+ZNPQnI4jnisdeRIZD/6CMx9+miUHRERdZTfJ2L3ukpF3JpgRP+xmRHIiIhiCYtu6lJ21e1CibNEERcbBwDQIcFswMiCGOgtDtXTzTndUUv2+VD22OOo++ijIx6ni4tDxp/vQtKll0LQRfEK+kRE1GLfhir4PcpdRfqOyoRez7/lRHRkLLqpS1Hr5QYO3SosDcZYeHFUm9OtMwJmzheLRoHaWhTPmAnXqlVHPC7+5JOR9cjDMGZlaZQZERGFQ6ih5QPG8u85ER0di27qUtSKblnWIeDsByAGVi1vpja83JYCcFXrqOPdtQsHpt8M/wH1LWQAQJ+cjMz77oP97LO4MjkRUQyRJRnrvi9E4W/KEWhJmTZkFPBiOBEdHYtu6jLqPHVYX7leERddvQDJAiAG9uduplp0cz53tGlcuhTFs+6E1NgY8hj7Oecg8945MKRwagARUSxx1Hjw47+34cAW9XVWBozN5IVUImoTFt3UZSwrWQZJlhTxQ7cKy0q0aJ1Wx6gNL+d87oiSZRmyzwfJ5YLscqHhm29R8cwzgKT8mQMAwWZDzty5sE87XeNMiYjoWMiyjC3LSrD8k12q87gBAALQfwyHlhNR27Dopi4j5Hzupq3CYqaXG1BfSI3bhWlGlmXUf/IJaj/8DwLl5ZBcLkhuNyCGePN1GEN2NvJffQWWgQM7OVMiIgonWZbxw9tbsW2F+hzuZsedlAt7mlWjrIgo1rHopi4hIAWwrHiZIi550yD70wAAU2JlPrcsc3h5BEluN0rvfwANX37Zocdbhw9H3ksvwpCWFubMiIios21ZVnLEglsQgJFn9cTos3tpmBURxToW3dQlrK9YD4dPuS9y89DyBLMBI2JhqzAA8DoAya+Mc3h5p/MVFaPottvg3bq1Q49PPP88ZD36KHRmc5gzIyKizhbwi1j15b6Q7XFJZkz9v8HI7R8j7yeIKGqw6KYuIfRWYcGi+8R+MbJVGKA+nxtgT3cnc65cieLb74BYV9f+BwsC0mfdgdQ//pGL6hARxajffiqBs86r2jZwXBYmXtIPljijxlkRUVfAopu6hCVFSxQxWTRDdPUEAEyJ9fncQHDLMAo7WZZR+/bbKH/6r22es30ond2OnLlPIOHUUzshOyIi0oLfK2LN1/tV2069ZhAGjs/WOCMi6kpYdFPMO+A4gD31exTxgLM/mn/ET46V+dwA4KpVj7OnO+wkjwdlDz2E+v99FvIYnd2OhFNOgc5mg85mhWCzQWe1QWezQZ+chLgxY6BPStIuaSIiCrtNi4vgbvAp4hk97RgwjquUE9GxYdFNMe9oQ8sHZduRaY+RrcKA0MPLOae7XcRGJ7w7d0BqdEL2eiC5PZA8bsgeb/DW7UHj4sXwbNkS8hzmfv2Q9/JLMPXooWHmRESkJb9XxLpvC1Xbxp7Xi9OGiOiYseimmKdWdMuyALFxAIAYWrW8GYeXd5gsinD+/DPqFyyA4/tFkH3KXou2Spg6FTlPzoUuLi6MGRIRUbTZ+nMpPE7lAqbZfRORP4ivvUR07Fh0U0xz+p1YVbZKEZfc+ZDFeAAxtj83oL5dGMCi+wi8e/agfsEC1P/vMwQqKo7tZIKA9JkzkHrTTezdICLq4iRJxoZFIXq5z+3N1wEiCgsW3RTTVpashF9le62WrcIsBozokaRxVsdIradb0AHmRO1ziWJiQwMaFn6F+gUL4N6wISzn1MXHI+eZvyJh8uSwnI+IiKLb3vWVaKjyKOJZve3IHcCtwYgoPFh0U0xbWnzk+dyT+qXDECtbhTVTm9NtTQF0MfZ1dBLvzp2oenUeHN9/f0zDxw9n6t0beS+9BHPvXmE7JxERRbf136v3cg8/jWt5EFH4sOimmCXJkup8bslvh+QNbu0RU6uWN1Pr6ebQcgBA/RdfomTOHMCvHN3QUbr4eNjPPBMZs++GPj4+bOclIqLotG9TFbatKMPuterTkexpFvQaHoPvH4goarHoppi1tXorqtxVinigcRCA4Bysyf1j8EVTbcuwbr5dmCzLqHnjDVT89Zk2P8aQkYHE88+HbdRICFYrdFYrBLMZOqsVOosFgsUSvDUaOzFzIiKKJjtXl+Pbf/52xGOGndoDOh3nchNR+LDoppi1pGiJarx5aPlxOXZkxNJWYc3Uerq78XZhsiiifO6TqP33v496rGAyIeG005B44YWImzAegl6vQYZERBQrVi/cd8R2s82AQROytUmGiLoNFt0Us1S3CpMMEJ19AACTY3FoOaA+p7ubDi+XPB6U/PluOL777ojHWYYNRdKFF8J+5pnQJ3LBOSIiUqqvdKOmxHnEY46blAujmRdsiSi8WHRTTKp0VeK3auXwMNHVB5BNAGJwqzAA8LmAgHIV1e5YdAdqa1F0y61wr10b8pikSy5ByrXXwNynj4aZERFRLNq/WTkl7VApOXEYOa1Ao2yIqDth0U0x6afin1TjAccgAIDdYsAJ+UkaZhQmakPLgW43vNxXVIwDN9wA39696gcIAjLvuw8pV12pbWJERBSz9m9Sf43NHZCMXkPT0H9sJkxWvjUmovDjXxaKSUsOHHk+90n9Y3CrMEB9aDnQrRZS82zZgsKbboJYqd4jIZjNyPnr07CffrrGmRERUazyeQIo2qFcqDSzlx0X3HFCBDIiou6ERTfFHJ/ow4rSFYq46MmCHEgCEKOrlgOhe7q7yfDyxp+WoXjmTEgul2q7LjER+a++AtuIERpnRkREsaxoWy2kgKyI9xzSfS5qE1HkxGBXIHV3q8tWwx1wK+LNvdxAjO7PDQCu7tvTXfffBTgwfXrIgtuYk4Oe77/HgpuIiNpt/yb10VMFQ9I0zoSIuiP2dFPMCb1VWHA+9/G5dmQkxOBWYUDooruLzukWHQ44vv0O9Z9/DtfKlSGPMw8ehPx582DMiMHF8YiIKKJkWca+zcqRZHFJZqTlxUcgIyLqblh0U0yRZVm16JYCNkjufADA5P4xXJh1gzndss+HxmXLUP/Z52j84QfIPt8Rj4+bOBG5f/879PFxGmVIRERdSdWBRrjqla81BUNSIQhCBDIiou6GRTfFlD31e1DcWKyIi40D0DxbYsrAGB1aDoTo6RYAa5LWmYSVLMtwr1uH+s8+g+OrryHW17fpcYkXXIDsxx6FYDR2coZERNRV7VpboRrvyaHlRKQRFt0UU442tDzRasTw/GQtUwovtYXUrEmATq95KuHg3bMH9Z99hobPv4C/WHmx5EhSp/8J6TNmsBeCiIg6bN/GKqz7tlAR1xt1yBsYw+8XiCimsOimmLK0aKkiJss6BJz9AAAn9UuDXhfDRZra8PIYm88tiyIc336L6jfehGfTpnY/XrDZkDnnHiRfckknZEdERN1F2d56fDN/M2RJuWp53oBkGE2xeUGbiGIPi26KGfXeeqyvWK+Ii66egGQFAEwZEMPzuQH1nu4Y2S5MDgTQ8NVXqHp1Hnx79rT78ebBg5B4zrlIPPccGNJjeIoAERFFXH2lC1++vBEBv6TafsLpPTTOiIi6MxbdFDOWFy+HKIuK+KFbhU2K1f25m7lqlbEoX0RN9vtR//kXqP7HP+Dbv79djzXkZLcU2uZ+/TopQyIi6k7EgIRv5v8GT6NftX3Mub2Q259Dy4lIOyy6KWYcbT73kNxEpCeYtUwp/FTndEdnT7fs86Hu009R/dp8+IuK2vw4nd0O+xlnIPG8c2EdMQKCTteJWRIRUXfz6+d7UFnoUG0bfFIORp3VU9uEiKjbY9FNMSEgBbCseJkiLvlSIfuCq49OGRDjvdx+D+B3KuNRNrxc8npR98knqJ7/TwRKS9v0GMFoRPyUKUg871zETZoEncnUyVkSEVF3Ub63AbVlTljijBADEtaqLJwGAD2HpuHky/tzgU4i0hyLbooJGys3osHXoIgHh5YHXzxPjvX53CH36I6OolvyeFD3n/+g+p+vI1Chvv3K4Yz5+Ui9/v9gP+ss6O32Ts6QiIi6E0mSseT97djyU8lRj03OsuH064+DTs/RVUSkPRbdFBNCDi13BOdzJ9mMGJ6fpGFGnUB1j25EfE635HKh9oMPUf3GGxCrqtr0GFPPnkib/ifYzz4bgoF/ZoiIKLwkUcL3b23FzlXlRz1WZxAw9frjYDRztXIiigy+G6aYoLpVmGiC6OoFAJjULz22twoDQvd0R2hOt+zzofaDD1D16jyItSoLvKkw9e2DtOnTYT/jDAh6vrkhIqLwk0QJ37+5BTtXt23U1fgL+iA9P6GTsyIiCo1FN0W94sZi7KrbpYgHnP3R/CM8OdbncwPqi6gBmg8vlyUJDV99hcrn/w7/gQNteox54ECkTZ+OhKmncWE0IiIKO4/TjwNba1C2px7F2+tQXdzYpsflD0rGsFPyOzk7IqIjY9FNUU+tlxvoYluFAVExvNy5ciUq/voMPL/91qbjLccdh7Rbbkb8lClcmIaIiDrF9l/KsPjf20LuuR2KPc2CU68ZDCHWR8IRUcxj0U1RL9R8brFxAABgWF4i0uJjfKswIHTRrcHwcs/2Haj42zNwLv2pTcdbhw1D2i03I+6kk1hsExFRp6kqasQP/9oKSZKPeJzBpMO48/vAWeeFs8GL+GQLTpjaA5Y4o0aZEhGFxqKboprL78Kvpb8q4qI7H7IYnJ8V86uWN4vA6uX+0lJU/v0F1P/vf4B85Dc0AGAdNRLpN98M2/jxLLaJiKhTSZKMH99pQ8Ft1uPcW4cip1+yRpkREbUPi26KaitLV8Iv+RXxQ4eWd4n53ID6nG6zHdCH/yq92NCA6tdeQ83b70D2+Y56vGXwYGTcdSfiJkwIey5ERERqNv5wABX7HUc8xppgxBk3Hs+Cm4iiGotuimpHm8+dbDNiWF6Shhl1IrXh5WHu5ZZ8PtS++x6q5s2DVF9/1OONublIv+MO2M86kwukERGRZuor3fjlf3tU26wJRmT1TkROvyQMnpgDk5VvZ4kouvGvFEUtWZZVi27Jb4fkyQEQXEAt5rcKAwCvA6jaroyHaT63LElo+OKL4IrkJSVHPV6flIS06X9C0u9/D53JFJYciIiI2kKWZSx+V33htKRMGy67fzQMRm5LSUSxg0U3Ra2tNVtR6a5UxIO93MFCu0sMLfc2Au9eAtQVKtvC0NPduHw5Kv72N3i3bD3qsYLZjJRrrkHqDX+EPoF7mhIRkbZkScavX+xF0bZa1fYpVw1gwU1EMYdFN0WtUKuWNw8tFwRgUr8YL7p9TuC9y4DCFertWUM7fOpAVRVKH3gQjT/+ePSDdTokXngB0m+7DcasrA4/JxERUXtIkgxd04g1nyeAH/61FbvXKS+4A8Dxk3I5d5uIYhKLbopaSw8oh5bLkgGisy8AYGheElJjeaswvxt4/3Jg/zL1dnsuMP7WDp268adlKJkzB2JV1VGPjT/5ZKTfOQuW/v079FxERBRdGqrc2LepCs46H+KTzUjJiUNKThys8ZGfLuRu9GHPukrsXluB0t31EP0SElItSMq0wVHtQW2ZS/Vx8clmjL+wj8bZEhGFB4tuikpV7ipsrt6siIuu3oAcfNMwuX8M93L7PcAHVwB71ReKQ3wWcM3nQFxqu04r+XyofPY51Lz11lGPtQwZgow/34W4MWPa9RxERBR9ZEnG/t+qsXlpMfZvrgZUdtmy2U1IyYlDcqYNoiTD7w7A5xHhcwfg8wQgy0BiurWlSE/NiUdSpg16Q+iFNGVJRsmuOhRtr0VjjQfOeh9c9V4463zwuQMwWvWwxBlhiTNCpxNQtrcB8mFbgDVUedBQ5Tni13fyFQO4YBoRxSz+9aKo9FPRT6rxQOOgls+nDIzR/bkDXuA/fwB2/6DeHpcBXPsFkNq+K/revXtRcudd8GzZcsTjjD16IOOO25Fwxhnca5uIKMZ5Gv3Y8nMJfltafNTC1dXgg6vBF3K+NADUlDixd8PBUVKCTkBKtg05fZOQ3S8JOf2SEJdoRkO1G9tXlmHbitIjPq/XGYDXGUA93O3/4pqef9Ll/dFzSFqHHk9EFA1YdFNUCr1V2AAAQEqcCUNzE7VMKTwCPuCja4Gd36q329KCPdxp/dp8SlmWUb/gU5Q9/jhkl/qwPADQJycj7eabkXzZpRC4IjkRUUxz1Hiw6ou92LGqHKLKKt/hIksyqoudqC52YtOSYgBAfIoZjbVe1d70cLLEGTHthuOQNzC822cSEWmNRTdFHZ/ow88lPyvioicTsj/4wjupX1rLwisxQ/QDH18HbF+o3m5NCRbcGQPbfkqHA2UPPYyGhSHO2SR+yhRkP/EXGJK5AA0RkVZqSpzYubocNrsJBUNSYU+1HvM5Rb+E9YsKsXrhPgR8nVdsH0ljjbfTnyM1Nx5nTR8Ce9qxf8+IiCKNRTdFndXlq+EKKHtsm1ctB2JwaLkYAD75I7DtC/V2SxJw9f+AzMFtPqVr3TqU3PVn+IuLQx4jmEzImH03kq+4gkPJiYg0IokSfvl8L9Z+vb8lpvtYwLAp+Rh5ZgHMNmOHzlv4WzV++s9O1JWHHtUUS9J7JCA1Lx4NlW7UlrvgbvBBpxMw6MQcTLy4L4xmbg1GRF0Di26KOqHmc4tN87kFATgplrYKk0RgwU3Alk/V2y2JwYI7u23bg8miiOr581H54kuAKIY8ztS3D3L/9jdYBgzoQNJERNQRznovvnv9NxTvqGsVlwIy1n1XiK0rSjHmnF4YfFIO9PrQC5QdqqHajeUf7cKe9epbaR0uPtmM407KQb/RWXA7fKgpcaK6pLHp1gl3gw96gw4mqx4miwEmqwEmix5+n4TaUif83tCvLUeiN+oQl2RGXKIJcYlmmG0G+NwBeJx+eJwB+NwBxCWZUXB8KvqMSEdiuq3V4/0+EXq9AF0bvy9ERLGCRTdFBb/kx29Vv2F1+Wos3KscKi0HbBDd+QCAYXlJSImLkTnJkgh8ejOw+WP1drMd+MMCIGd4m07nLytDyd2z4fr11yMel3T5ZcicPRs6K4flERFppWRnLb75529w1ftCHuNp9GPpBzuwaXERJlzUFwVDUlVHIkmSjJoSJ/asr8S6b/Yj0IZ523kDkzHk5Dz0HJraUrgmpluR1bv1GiiyJEMIMUVLlmU4ajyoKXGiptSJykIHSnbWhfyaBJ2AguNTMWhCNgqGpLb5QoIao4k920TUNbHopojwi378Vv0bVpWtwqqyVVhfuR7uQOiVTQPO/gCCL8ZTBsTI0HJJAj6bAWz8QL3dFA9c9QmQO7JNp3N8/z1K77sfYn19yGN0iYnIfvwx2KdO7UjGREQxSZZluOp9qK9yo6HKjYZKd9M2VG64G/2ITzaj17A09BuVCWtC+C/ayrKMdd8WYuX/9ii2wwqltsyFL1/ZiLyByZj4u76w2c0o39eA8j31KNtbj4p9jjb3OA8cn4UR0wqQnBXXpuNDFdwAIAgC7KlW2FOtLSuGy7KMhio3infUoXRnHSoKHTCa9ehzQgb6j81EXKK5Tc9LRNRdsegmTfhFPzZXb8bqstVtKrIPd+hWYZMHxMDQckkCvrwDWP9v9XZjHHDlx0D+0ffIljwelD/5JOo++PCIx9lGj0bOX5+GMSurIxkTEUU1v08MFtRVnqaiOvhR31RcH2kF77pyF4q21WLZR7vQ47gUDBibhV5D02AIQ8+q1+XH929txb6NVUc/WEXRtlp8+PiqDj02vUcCJl3eX9GTHW6CICAx3YbEdBsGT8zp1OciIuqKWHRTp2guslt6sivWwyMeef/QUGTRjEBjfwBAapwJQ6J9qzBZBr76M7DmLfV2gxW48j9AwfijnsqzfQdK7roT3p27Qh+k1yP91luQeuONEPQcmkdE0U2WZQR8EtyNPnidAbgbfcE5v42HfDj9cDfdNt8Px0rdsiRj/6Zq7N9UDaNFjz4jMjBgbBZy+yUdsfc3lMpCB75+bdMR96lOSLEgOduGwt9qjiX1Vsw2A8Zd0AeDT8yJvZ08iIi6IRbdFBY+0YfNVU1FdvkqbKjY0OEi+1CyrIO3/BxACs5NPrl/enS/wZBl4Ot7gFX/VG83WIArPgR6nniU08iofe89VDz1NGRf6LmBxpwc5DzzDGwjTjiWrImoC2kuan2eAPweET5PcAErn0eE3xO89TXd+t2H3W9udwcgBiRACPZyCgKAptuD9w9+LghCS9EqCMHhy8FpygIEXbBdEuWWIloMtL2AlmUJslQPWXJAEKwQ9Glh2Y3B7xGx7edSbPu5FPHJZvQfk4n+Y7OQmhMf8vvq94hNi4L5UbqrHisW7D7i11IwJBWnXTsYljgjDmypwfJPdqK62NnxpAVg8MQcjLugN6zxMbK2CRERseimjvGJPmyq2oRVZauwumw1NlSGp8gGAKPOiAxTP+w5kAV/wwmQfQeHk58czUPLZRn49n7gl3nq7XozcPl7QO+Tj3iaQG0tSu+7H40//HDE4+xnnYmshx+G3m7vaMZEFAN8nkBwGHWFG/WVbrjqfU1FsrJQ9nuDt3LbphVHHVlyQxIrIYtVkMVKSGIVZLEaQODgQUI89KaB0JsGQWcIz2tCY60Xa78pxNpvCpGWH4/0/ISW4trjDK6+7XX6IYlt+8YKAjD2/N4YcXpBy8WI/MEpuHTgGGz7uRQrP9sDd0PoC6pqcvsnYfxFfZHZk3/ziYhiDYtuahOf6MPGyo1YXb4aq8tWY33lenhFb1jObdQZMTR9KEZnjcbozNEYmj4UN/xrA7ZVtZ4fpxOASdG6VZgsA98/DKx4Sb1dbwIu+zfQ99SQpxAbnXAuXYLyJ59CoKIi5HGCzYas++5D4kUXcu9toi7C4/SjvtKN+koX6iuCC4HVV7pRV+lud3EWC2Q5AFmsgSxWtRTZklgFyG3oBZYbIXpXQ/SuhqBLhd48CHrTQAi61sWo3qCDPc0Cg0mPykJHm3OrOtCIqgON7f2SWlgTjDj9+uOQNzBF0abTCRh8Yg76jsrA2m/2Y/33B1TnopssemT0tCOrdyIye9mR2cseUz3bkiSibNcOVBXuR48hw5GUybVGiKh7Y9FNqryiF5sqN2FV+cGe7HAW2cPShwWL7KzRGJI2BBaDpaXd7RPxy17l3Lfh+UlIjtatwn78C7D8efU2nRG49G2g/+mKJt+BA2hcvASNixfD9euvkP3+Iz6NZfBg5PztGZh79QpD0kSkFVmW4WrwtRTTLR8VLtRXuuF1BY5+khgky17IYn1weLhY09RzXQlZqgVw7N3xslSNgHsZAu5lsGf0QcGQCeg/7kSk5achLtHU0stcX+nGjl/LsOPXctSVu1TybL4IUAlJqgVkf1N+MiBLACTIkAFIwYuskJraBQg6OwR9EgRdMrJ698BZ00chPuXI2zWaLAaMO78PjjspFxt+OICaEicSks3I7J2IrF6JSM6yQQz4sfH7r/DD6wvhqKpEcm4ecgcMRt6g45A78DjEJyuLei0E/H44qipgtFgRl5SsuPhbsmMbFr3+Kir27W6JDTl1GqZcfQOMFsvhpyMi6hYEWY7VQWjhU1RUhPz8fBw4cAB5eXmRTicivKI32JNdtrplTrZPCk/viklnwrCMYRidORqjskYpiuzD/bCtHP/31mpFfNbU/phxar+w5BRWi58CFj+h3ibogUv/BQw6FwAgBwJwr1+PxsWL4Vi8GL5du9UfpyLluuuQfsft0Jmi9MIDUTcnSzIa67ytiumGpt7q+ko3Am3c/imWyLIIWWpomnPdAFmsO/i5VAfI4blY2x56gwG9ThiFQSdORu8RY2A45G+mJEnYv7EQm5ZswIHfdsDnKgsOZZdqEI6LAABgMJmRlJWN5OwcJGflIDk7F6n5PZDZqy90bVjsUgz4sfnH77Hyvx+gsaY65HFJmdnIHXgccgYMgtFsht/jgc/jhs/tht/rgc/tgslqQ96g49HrhJHQ6UI/d+nO7di+YilqSophiYtHfGoaElJSkZCaDqs9EbUlRSjbvRNlu3eicv9eSGLwIlFydi76jhmPvqPGISkzCz+9/zY2//it6nMkZ+fgrFvvQlbf/misrcHOX5ajaMtmCDodBk48GX1GjeXoLaJuojvWXiy60T3/45uL7ObVxTdWbuy0Into+lCY9W3fw/OBTzfjnZX7FfHPbp2IoXlJYckxbH76G7DoUfU2QQ/87nWIuVPQ+NMyNC5ZgsaffoJ0hH221ehTU5Hz5FzEn3RSGBImCs3vE1tWj3Y3+ppug/f9PhE6nQCdXmi61QU/1wcX0NI33R4ab3Vs02OFprher2s6Xjh4Xn3rY1uO1wlR82ZcFCU4qj0He6wrmoaEN+0L3Z4FwqKBIAAmqwFGix4miwGmplujxQCDSQdZkuH3OeB11sDnqobPVQOfuwY+dy387hr4vfUIV7HaGcy2OPQbOwEmixWVhftQuX8vPI1tH2oeTiarDfnHDUXB0OEoGHICkrNzWv1cS6KILT/9iJWfvI/6ivKwPndSVjZGnnUBjjv51Fa9zaW7tmPFR+9h7/o1x/4kgoCjLSag0+uR0bM3yvbsUhyb1bc/Tvr9tcgbfBxKtm/FrlUrUV18AEazGRN+dwXSevQ89hyJKCp0x9qLRTe6x3+8J+BpmZMd7iLbrDdjWPowjMoahdGZozEkfcgRi2xZllHn8qO4zo3Seg9K6twoqXOjuOl2S2kDPIfNcUuLN+HXe0+LrpXLl/8d+O5BRViWAZ/DiMaUK+HYVg332nXBfbs7IO6kk5Az9wkY0tKONVuKQh6nHztXlaNkZx187gDiksyISzYjPsmM+BQL4pPMsCWaYLEZ272dkRiQDimafS3Fc8tWTIfHG/0IHGGf40hTLdCbCnpBf2jRr7wo0OrYVgX+YUX+IRcGms8nCAIcNZ6W4eCOag9kKfIvm0azvlWhbGwumK0GmMx6GK0GGEyAXi9Cp/ND0ImA4Icg+wDZD0nyQZZ8CPg98Hs8LT2jwd5SD/weF5x1daivLEfAq31vNQBAEJCclY20/J5I61EAe1oG9m1ch92rf0HAF6GcwighLR0FQ05Az2EnQAoEsOKTD1BbWtypz2mJT8CwqWcif/BQrFn4KfauU44qizST1Qqf290qptMbcOHsB9Fz2AgAQNGWzVj/7ZeQJBEDJ0xCv7ETo+bCHBEdXXeovQ7Hohtd8z++ucheVX6wJ9svHXm+cFuZ9WYMTx8eLLKb5mSb9AeH73n8IsqaiulgId1UWNe7mwpsD9z+9g2zvGhELp69dHhY8g+LFS8D39zbclcSAVeFGY0lZjSWWOB3HttyCYacbKT+8Y9IvvxyCDrdsWbbYaJfQuUBB5x1XljijUjJiQv7Yj6SKKGm1IWK/Q1wVAd7CiVJhiTKkEUZknjwfsutKMNo1iM1Nw7p+QlI75EAa8LR85JlGbVlLpTsrEPxjlqU7a6Hx+mH0WKA2XqwaDFbDcHipSlmMDV/6GBsujUY9RD0AgJeEX6fiIBPRMAnwe8Nfm40G5CYYUVSpg2J6VboDbqWr7dwSw22rSjF3o1VkAJH/xMs6ARYE4yw2U2w2U1Iy09A35EZSMuLb/VGs77SjU1LirB7TQUaa2O/KOnOdHoB9jQrEtOtiEsCTGYXIDRADjRADDQi4AsWyz63uiZg9wAAHDxJREFUGz6Pu2Vosd/jDhbNbjcC/thZgM2SYEd6j55I79ETaU23qXk9VOcA+9wu7Fq1Elt++hGFmzZAlqP3YhGFj9FixeWPPIX9G9dh6btvtmrLGTAYp1x3EzJ79YlQdkTUHl2x9joaFt3oGv/xnoAHGyo3tAwX31S1KbxFdsZwjM4cjZEZI5Fl7Y8qh9TSQ314UV3VGP43ei/8/gScNywn7OftkF9eA776MwJuHRpLg0V2Y5kZcuAYimNBgHXoUMRPmYz4yZNhHjAgIlftnfVelO2pR9nuepTtqUdFoUNRFFoTjEjJjgt+5MQhuem2LcW4JMmoK3ehcn8DKvY7ULG/AVUHGsPSwxqfbEZ6j2AB3lyI2xJNqCl1omRHHYp31KFkZy3cjvD8XrSHIAAJaVYkpVtRVdQIV5hWo07OsqH/mEyk5sZjy/JS7NtUFc0jfekwBqMOiRlWxCfpYI7zQG9oBKR6BLx1cDuq0VBZgfrKMnidx7Cvc5TRGwxIyeuB9PwCpBX0arlVW5CrLZx1tdi2fCm2LluM8j07w5qroNNBp9cHb3U66HTBzw+N+71eeBwNYX1eNal5PeB2NMBVX9fpzxUuBrMZSZnZqCrcF75zmsyhRzkIAoZMmYpR516MlJzcsD0nEYVfV6i92otFN2LzP94dcLcU2avLVoe1yDbpzOiVcBwyTcchTuoPnzMXZfUBlNZ7UFrngU/UtlchwWLAsrtPQaLNqOnzHk6WZXg+novGD19GY4kFnppj6/HVxcUh7qSTED/5ZMRPmgRDirYr0UqihOpiJ8r21KO0qch2VHd8r3VrQrAnPCUrWISn5MTBEm9CdVEjKpqK7MpCB/waLialN+pUt+Mh0orJokdCmhG2eA+MJicEnQOivw4+dy2cdVVoqCiHW4OiTUsmqw2JmVlIysiCPSMTSRlZSMzMQmJGJhIzsqA3dM7GKTUlRdi6bDG2LluM+vKyNj1Gp9cjNTc/eAGgR0+kF/RCekEv2BKT2nwRwNPYiNqyYtSVlqCmtAR1ZSWoLS1GbWkJfG7lSuntkV7QCxMuvQp9Ro4BANSVlaB42xYUbfsNxdt+Q11ZacjHCoKu3aMADGYzBAjwe9VfCxJS05HVpx/Se/ZC1YFC7F23Gn6PW3Fc/7ETcfLV1yM+ORUr//shVv73A8gdnGbVET2Hj8QJ085Bz+EjjriAHBFFRizWXseKRTdi4z/eHXBjfcX6ln2yN1ZtREAKzxYzOphg9PeGr7EXnPUFEN15iJbd5HQC8NTFQ3HJqPxOOb8sihAbGiDW1ECsqUGgphZibS3E2qbPa2og1tYiUFuLQNE+iA7lm4v2MBb0QMLkKYifMhm2ESMgaLgSucfpD/ZiN32U73N0ydWUibRmiRdgS/DBbHNBr3cCcgP83lp4HNVorKmEs6420imGlU6vhz0to1UhHfzIRGJmFixx8RGdXyvLMkp3bsfWZT9i+88/tVzUsCUmtRTVzQV2Sm4e9IbOuaAryzJc9XWoLNyHws0bsH/jOlTsbduOFSm5+ZhwyZXoP3bCEacYOetqUVtWAr3eAKPFApPVCqPFCpPFAkHQYdeqFVj9xQKU7tx+xOczWW0Ycdb5GHnW+TDHxcHndsFRVQlHTTVc9XWw2u3I7NUXcUnJrR4X8PlQ+NsG7Fq1EpX79sCWmIQTzji3Ze51s5IdW7Ho9Xkt24jlDBiMAeMmoveIMdi1eiV+WfCfTlngLiEtHcdPnorjTj4F9vTMkD+XsixD9Pvh87ghS1K7LroQUfvFQu0Vbiy6EZ3/8S6/62BPdnmwJztcRbYsGSG6ekJ09UbA1RuSOxfRUGTbLQbkJFmbPizIS7bhnKHZyEu2tfkcks8XLJprahCoqYFYWxf8vLYGYnNBXVODQNOtWF/f4UXO2sRggG3kSMRPnoz4ySeHdX9tUZTgcwfgdQVabr2uAHye1jGP04+qAw7Ulh1bjwt1rrgkM9wOHyRRmz/J5jgDrPEmWOKMsMQbYY1vvjW1ut/8udFigNxqbr3UMr9eEmXIkgxRlA4e0/IhtZqL33ysWjx4bqnV/H1ZVHlOqfX5ZcWcf5Xjmh4vKx4fvH+kxdFkWYI13gtrvDvYWy04IPrr4XPXwFlXBWddzVFXbY4FeoMBRqsNJosFRrMFZlsc7OkZwYI6s6nHOiML8ampMdN7KEkiPI5gMWdLTIpsMgBcDfUtBfj+jevhqK5s1Z6UmY3xl1yBgRMnhfV7XLx9K9Z8uQC7fl3ZqvfbZLU2FdsXwBIfH7bnUyPLMhzVVTDb4mC2tX5d97qcWPPlp9i+YhkEQUDeoOPRd9RYrPpiAQo3rQ/L8+sNBsQlp8Kelo6UnDwkZ+egsbYGJTu2onLf3lZrIMQlJWPIqdNwwhnnwmZPDMvzE9FB0Vh7dTYW3Yi+//hv9n2DZz6/G3JABISDUzRl4bBboE3tkmSE5M5HwF2AgKcnRE82AANkCE3HCYc8TjjkfM2fCyHuBx/b8gPU1C5DCE5iPYRRLyAr0YKcRCtymwrr7CQLcpKC97MTLUiwtO5tkGUZktMFsbbmkEK5uRdavaCWGhvb9b3uDPqkJMSfPAnxkycjbuJE6O12xTFiQILfI8LnCcDXfOsOwO8V4XMH4HOL8Lr98LkC8LqDHy2fN9129V5qQUDT9lIqq0sLApz13mMuUFNz45CWn4CAT2r5P/A1f7/dAQR8nTscMj7ZjAHjsjBwXDaSMm2QJRnuRj8aaz1orPXCWeeFy+GDu8EHV4MPbocPVUWNR81LpxfQ54R0pObFwxJ3sJBuLqDNNgN0+sgt0NdRkihC9PsR8Puabv0Q/b6W2+ZYc3vzx8HjWz+u5XOfr+VxAV/TOX1+iAE//F4PXPW1mg6NbQtB0DX1alpgshzs3TRarU33D4lbm9osrduaH9/82M7q8SV1siyjtrQYhZs2oKGqApm9+6Hv6HGdNvweAOrKy/Dbku9RU1yErL79cfyUqbDGJ3Ta8x0rr8uFDx+6G5Uq88INRhMGTZqCrUt/7LRFAw0mMwadeDIGnTQFeQOPi+jCpkRdSbTVXlpg0Y3o+49fVfwbds34L/SIQ6tVkeSDZXJLXD60TG4KtIrJLY8F0PrxTU2HHyvIhz0HAEE+7HyQDzkOh8VUHn9ofgAgCGhdwh+iKSCIAUAMQJAlCLIMARIEWQJkqSkmQYAMQRabYvIh8VDHShBkMfj1HHJc8wcOeZ7DPwAJsmBAwGCBqLcgYLAgoA9+LuT1hL7fYAgFfSAnpcHvleDziPAfWlQ333eLMbGXryXOiKzedmT1SURaXgKcdV7UlDhRU+ZETYkTzrpjXx3bZjcho6cdGQUJLYugWeKMwX2Zj7JFlhiQUFPiROWB4FzxykIHqouOvChbal48cvslIbd/MrL7JR518TdRlBDwNq1K3rQ6ecAnIuAP3kqiHFzN3HxwZXOjWQ+9UQdXgw915a7gR0Xwtr7SDaNJj8xedgwcn43cAcnt3gbP5wlg38Yq7FhVjgO/1UA6pIfWmmDEcZNycfykXMQlht62r71kWQ4WrE2FaMDnO3h7aGEb8B8sWg8vbFtiB48/eP/QojjQdHvoY4Nt0Vb4diZLgh2J6RktPc3B20wkpmciIS0dRrOFw1+pW3DUVOH9+//calSAJcGOC+9+ADn9B6G+ohwrPnkf25Yvgejv3IUymy9Q5R83FKPPuxgZPXu3tFXs24Pibb8hOSsH+ccP69SLJ0SxLtpqLy2w6Eb0/cdXONxYMPMrBExJkU6FugsBSMmOQ1bvRGT1TkR2n0QkZliP+Kbe6w6gtjRYgNeUNn0coRi3xBmRUZCAjJ52pPdIQEaBHXFJprAWDpIoobbchapCByoLG+Fy+GCzm5DTLwk5/ZJgthnQUFmByv17Ubl/L6oK98HjcsJgMsFotsBoNrfcGpo+tybYkZrXA6l5+TCaldsXHap5DmdtSTF8HjfEgB9iIAApEAjeisHbgzF/y/1gAetDwOdDwOdFwOeDIAhIL+iF/uNOREavPorvVXVxOdYsXIr6iiokZabguJOGI6N3bxiM6j2WYiAAr8sJT6Oj6aMRHmfjwfvOxmCs5X7wWK+zEZLYtUdWaM1ktTXNh86EPf2w27QMxfBbou7MWVeLpe++icrCfcgo6I3xv/s9EjMyWx3jaqjHpkXfYMN3XymG7XcKQcDACZOQ3W8Ati1bgtJdB+fN29MzMGD8SUjJyYPeZILBaITeaITBaILe0Px58FZvbG43Be8bDLygRl1etNVeWugyRffLL7+Mv/71rygrK8OwYcPw4osvYsyYMW16bLT9x8uyjPnXL4CfRTd1UHDOnh+Q/ZBlP4IjDPQQBD0APYwWE7J6JyOrTwqyeycis5cd5nauDi/LMvweN7xuF3wuF7wuF3wuJ5z1jagtq0V9eR28bi+sCWbY0+IRl2iF3mQMvuFoftNhMDS96QjGdAYDZEmCFAhAkkRIAbHpNtA011eEJAYgiWLwK9LrodMboDMEbw+/L/r9qDqwv1WR7XV1cPslQUBSZhbS8guQ1qMn0vILYIlLQE3JAVQXFaK66ACqigo7bfugxIxM9B93InoOG4nyPTuxa9VKlOzcpphLrNMbkNajAInpmfC6GuFubIS3qbD2uY9tIUBqO6PZ0lRIt+6pbi6sLXGdO39WK7IkA01z5WWx6fOADFmUgKaYLEpAIDhvXtAhuEJm82iWQ24hBPekR9MUEuVxhzy2CxYlsiRDrPMiUOVGoNIFf5U7+Hm1B7JPhCHNClOBHeYedpgKEqA/wkgdyRNAoMYD2S/BkGyGLiG8Fzg7Sg5IEBt8EBu8EOu8EBt8kCUZOrMeOosBgkUPXZwRhiQLdPFGCDoBkssP794GePfUIVDnhc5igCHFAkOKBfokM3Q2A3RWA6DXQazxwFfpRNX2PSjcvQmbty6GO3D0Bdr0ggEJxhQkGtNgNSQgIPnhlVzwiW7IkAEIMOkssBriYNQdvPjqCjSg1LUHXim8a6a0FOjGQwt0ZcGuekzz5wYjDKbWj9EZjC2FffC12BD8MAZffw1Nty2v003tXXVYvegPwFfvhLfeCX+DGwGHBwGHB6LTB8kdgKAToLebYbTbYE6Ogzk1AZbkeOhspqOOxqMj60jt1d5a76OPPsIDDzyAffv2oV+/fnjqqadw1llnhetLaLcuUXR/+OGHuPrqqzFv3jyMHTsWzz//PD766CNs374dGRkZR318tBXdAPD9zW/BoDei+b9HxiG3cvD20JZDj2v1CLmpvTkqH9outwwAb/14tWObbuVDnvNIx6mdUyXv5nO2zupg3sFp5rqmEedC07+mzwWh9S0AQNcyXP3QuIBDziEcelzz/UPOLQgtj2o+BofcC85ZR8vXeOigf8hC8Gtonv8uN8+Zl1vmv8uycMj8+aa43Hy/+fkk6OCHThYhCCJ0kCDIAeggBT8XROggQ4fgcHh98+cCEHxfKkAHPXSCDjohuBiPKAcgySIkWYQoi5DkACRIkHWAoAdkfXAONXQCBIMOMARvBYMOgl5AwOuH6PZB9Pohef2QfBJ0gg56waD6oRMM0Ak6iHIg+CH5EZD9EOUAApIfYvPnsh+iFIAo+yHJIvQ6IwyCEXrBCIPOBINghKEpZtAZoRdMMOiCFwgCki/4Ifvgl3wIyP6WmF8OPodeMMKoM8EomGDQmYOf68wwCCYYdSboBH3L90bttvl71fx5MO+m758stntb7OD3zAiDYGj6eoIfgNz0vfA3fR3B74/chmcQIMDQ8jUGvz86hHehq9a/T4f+3h38PWz1e3pIu9C0zsPR21v/7h3xmJbfU4Q+x2HPebR2odXvflMRCCG4vgSkpv9vGZIcXG9DbzLCYDHBYDHDaLXAaLPCZLPBFGeD0WqGoNcFf5/0QtPvli5YOOp1B3/X9E1Fpk7XdNt0v6X9kGOb2iAITcXtIQXuIZ/LAbl1e6CpAA5IB9sP+Vz5+EOPl5uKZ+mwojr4ecT2hW8qwFsK8kO/R03fN+hwSEHfvjfIgkEHwaSDYNRDZ9a3fC6YdBBMTTGjHoJRpzJHSkn2S5A9AUheEZJXbPlc9oqQPCIkpw+Bag/QjnUq9KkWmHvYYcyNh+wJIFDtQaA6WKRLztbDrAWTHoZ0KwxpTR/JZsheEaLTD8kVgOT0Q3L6IQck6GxG6OKM0McHb3XxxuBrwmEkVwCiwwep0QexwQfJ6Ydg1EFvDxb5ersJglEXvHBQ4YK/0g2x1tP2nxm9AH2CCWK995h+zgJ2CT7BA71TB2PABEEGvJIHPtENQRBg0cfBqOv4dBxJFlHnq4BHdMGsaz1C7ND3Pq3eYcnyIbGmI1tizY9TPwatziQf9j5R5b7K44LPJeHQ92AH78sHz9+cgxDct17Q6yA0/11qtWe9AMHQtKe9XgdBaPqAAB10TX97ddBBaGo79G+7ruVvb6t/TY9p+nYBTfkEbw55Bys3fX3ywe9bMPz/7d1daBT3HsbxZ1+ySatVSHNOgtEYBPU0fUmoJjGIxmA0aBX0KhcFoxdeqbSEXCiUWqHN0lBBfCnFG0VQfEG0IucmbCuxJCJGoqCNR8Fg4Rw3J7QkukJydmfOxbZ7mppTdyc7OzPZ7weC2dn/zP5mk2fXX2b2P8nlPklKSP54QAEjoKAZVFAFKvAVWv65m6ahCY0r7vuPEv6EjKAhs1Ay/aYMIyHTMJIHEBLJ7w0jIcP49TXXSCQn7wyYMoNm8jWkwJd8XSkKKlAUlL8opODrBQoUhZIHEgIBBYJB+f0B+YPJAwsBf/Lf5MGIROoMutQZdYlfD1jE40ok4vpbU6Pe+OtfLO2vHTLtvTLt9Xp7e7V69WqFw2Ft2rRJZ86c0Zdffqnbt2/rnXfesWOXXmlGNN319fWqra3V0aNHJUmGYWjBggXas2eP9u7d+8r13dh0/6Pj73o96N7JTQAAAAC4n69ljsqbqp0uIyXT3ivTXq+1tVWxWExXr15NLVuxYoVqamr0zTffZG9HMuD580UmJibU39+v5ubm1DK/36/m5mb19fU5WNn0+NL50zkAAAAA/Akvz8tipdfr6+ubNF6SWlpaHO0NPT+14sjIiBKJhEpLJ0+oUVpaqsHBwSnXGR8f1/j4/yZ7Gh0dlZT8q0s8np1rYU/XP1/8W4UBrqsMAAAAwDrjXyElhoqdLiPl6dOnkpI92JzfXVq3sLBQhYWTT/u30us9ffp0yvG/Pa4TPN90WxEOh3XgwIGXljc0NDhQDQAAAADklz9+vnr//v367LPPnCnGZp5vuktKShQIBBSNRictj0ajKisrm3Kdffv2qb29PXU7Ho/rxx9/1IIFC+R34QyNa9as0bVr15wuIyVX9djxONPdptX1M10vk/GvGvvs2TNVVVXp/v37euON/JsngPy4Z3tuy0864/I5P27LjpS/+XFbdtIZm8/ZkdyXH69mJxvbJD/uYxiGnjx5oqqqKgV/d037Px7llqz1emVlZRmNzwXPN92hUEjLli1TJBLRli1bJCV/kJFIRLt3755ynalOXVi5cqXdpVoWCoVcM8GblLt67Hic6W7T6vqZrpfJ+FeNHRtLXsKqvLx80ik8+YL8uGd7bstPOuPyOT9uy46Uv/lxW3bSGZvP2ZHclx+vZicb2yQ/7lRRUZHWOCu9XkNDgyKRiD7++OPUsu7ubkfPavZ80y1J7e3tamtr0/Lly1VXV6dDhw4pFotpx44dTpeWFbt27XK6hElyVY8djzPdbVpdP9P1Mhnvtt8Pt3Hb8+PV/GRje27Lj9t+N9zGjc9PvubHbdmxsu1847bnx6vZycY2yY/3varX27Ztm8rLyxUOhyVJH330kRobG3Xw4EF98MEHOnv2rG7duqXjx487tg8z4pJhknT06NHUBdNramp0+PBh1dfXO10W4LixsTHNnTv3pckqALwa+QGsITuAdeTnZX/W661Zs0aVlZU6efJkavyFCxf0ySefaGhoSIsXL1ZXV5c2btzoUPUzqOkGMLXx8XGFw2Ht27dvys/KAPj/yA9gDdkBrCM/Mw9NNwAAAAAANnHfVN0AAAAAAMwQNN0AAAAAANiEphsAAAAAAJvQdAMAAAAAYBOabiDPvXjxQgsXLlRHR4fTpQCeUllZqffee081NTVqampyuhzAUx4/fqympiZVVVXp3XffVSwWc7okwPUePHigmpqa1Ndrr72my5cvO10W0hB0ugAAzvriiy+0YsUKp8sAPKm3t1ezZ892ugzAc7Zv367PP/9cq1at0s8//8xlkYA0LF26VAMDA5Kk58+fq7KyUuvWrXO2KKSFI91AHnv48KEGBwe1YcMGp0sBAOSJe/fuqaCgQKtWrZIkFRcXKxjkOBCQiStXrmjt2rWaNWuW06UgDTTdgEf19PRo8+bNmjdvnnw+35SnFx07dkyVlZUqKipSfX29bt68Oen+jo4OhcPhHFUMuEc28uPz+dTY2Kja2lqdPn06R5UDzptufh4+fKjZs2dr8+bNev/999XZ2ZnD6gHnZOO95zfnz59Xa2urzRUjW2i6AY+KxWKqrq7WsWPHprz/3Llzam9v1/79+3X79m1VV1erpaVFw8PDkqRvv/1WS5Ys0ZIlS3JZNuAK082PJP3www/q7+/XlStX1NnZqbt37+aqfMBR081PPB7X9evX9fXXX6uvr0/d3d3q7u7O5S4AjsjGe48kjY2Nqbe3Vxs3bsxF2cgGE4DnSTIvXbo0aVldXZ25a9eu1O1EImHOmzfPDIfDpmma5t69e8358+ebCxcuNN98801zzpw55oEDB3JZNuAKVvLzRx0dHeaJEydsrBJwJyv56e3tNdevX5+6v6ury+zq6spJvYBbTOe959SpU+aHH36YizKRJRzpBmagiYkJ9ff3q7m5ObXM7/erublZfX19kqRwOKyffvpJQ0ND+uqrr7Rz5059+umnTpUMuEY6+YnFYnr27Jmk5GQ23333nd5++21H6gXcJJ381NbWanh4WL/88osMw1BPT4/eeustp0oGXCGd7PyGU8u9h1krgBloZGREiURCpaWlk5aXlpZqcHDQoaoAb0gnP9FoVFu3bpUkJRIJ7dy5U7W1tTmvFXCbdPITDAbV2dmp1atXyzRNrV+/Xps2bXKiXMA10v2/2+joqG7evKmLFy/mukRMA003AG3fvt3pEgBPWbRoke7cueN0GYBnbdiwgStnABbMnTtX0WjU6TKQIU4vB2agkpISBQKBl16Uo9GoysrKHKoK8AbyA1hHfgBryM7MRtMNzEChUEjLli1TJBJJLTMMQ5FIRA0NDQ5WBrgf+QGsIz+ANWRnZuP0csCjnj9/rkePHqVuP378WAMDAyouLlZFRYXa29vV1tam5cuXq66uTocOHVIsFtOOHTscrBpwB/IDWEd+AGvITh5zevp0ANZ8//33pqSXvtra2lJjjhw5YlZUVJihUMisq6szb9y44VzBgIuQH8A68gNYQ3byl880TTO3bT4AAAAAAPmBz3QDAAAAAGATmm4AAAAAAGxC0w0AAAAAgE1ougEAAAAAsAlNNwAAAAAANqHpBgAAAADAJjTdAAAAAADYhKYbAAAAAACb0HQDAAAAAGATmm4AAAAAAGxC0w0AAAAAgE1ougEAAAAAsAlNNwAAAAAANvkvmQ00ewZ+D5gAAAAASUVORK5CYII=", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "base_dir = \"/your/checkpoints/directory\" # replace with your directory\n", + "extract_checkpoints_and_plot_results(base_dir, calculate_accuracy)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "latent", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.19" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/validation.json b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/validation.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c924c935fd487c69e3cd508048d61fc55adaad --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/validation.json @@ -0,0 +1,76 @@ +{ + "passed": true, + "steps": 2, + "batch_size": 1024, + "author_loss": [ + 10.958324432373047, + 10.982955932617188 + ], + "embedding_update_norm": 0.00027920061256736517, + "all_checkpoint_parameters_finite": true, + "fresh_process_reload": { + "passed": true, + "step": 2, + "queries": 56, + "raw_generation_exact_match": true, + "metrics": { + "ID Triples": { + "total": 8, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + }, + "OOD Triples": { + "total": 8, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + }, + "Train-II": { + "total": 8, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + }, + "Test-II": { + "total": 8, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + }, + "Test-IO": { + "total": 8, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + }, + "Test-OI": { + "total": 8, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + }, + "Test-OO": { + "total": 8, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + } + } + }, + "physical_gpu1_compute": { + "passed": true, + "physical_gpu": 1, + "torch": "2.6.0+cu126", + "gpu": "NVIDIA L20X", + "loss": 63.067955017089844, + "backward_finite": true + } +} diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/contract-tests.log b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/contract-tests.log new file mode 100644 index 0000000000000000000000000000000000000000..2d5f7ed6cbd34fa074db4b2892bb65f19b235fd8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/contract-tests.log @@ -0,0 +1,2 @@ +...... [100%] +6 passed in 2.40s diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/execution-lock.json b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/execution-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..7a31a0a792d333aeca707879ff327829e377065b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/execution-lock.json @@ -0,0 +1,3 @@ +{ + "config_sha256": "f7faf264e54f1c29457bc43a3f61102df691abbdb0fb47e01ade3c1c116e14a1" +} diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/frozen-config.json b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/frozen-config.json new file mode 100644 index 0000000000000000000000000000000000000000..5b5ad4816fadc84699b15c85b3915af2d1b03ab1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/frozen-config.json @@ -0,0 +1,237 @@ +{ + "batch": "implicit-reasoning-paper-reproduction-v2", + "module": "paper_reproduction", + "gpus": [ + 0, + 1 + ], + "runtime": { + "docker_context": "lm-memory", + "docker_host": "unix:///run/docker-lm-memory/docker.sock", + "image": "sha256:24c345d3a3690bf481a4be1832078c1ad4cfd3637073237ab259a145cf95aa6c", + "python": "/opt/conda/bin/python", + "cpus": 4, + "memory": "16g", + "env": { + "PYTHONHASHSEED": "0", + "HF_HUB_OFFLINE": "1", + "TRANSFORMERS_OFFLINE": "1" + } + }, + "additional_sources": [ + "tests/test_paper_reproduction.py" + ], + "specs": [ + { + "name": "only_ii-seed42", + "arm": "only_ii", + "seed": 42, + "max_steps": 1000000, + "save_steps": 50000, + "save_step_dense": 40000, + "save_step_dense_interval": 2000, + "log_steps": 100, + "dataset": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reproduction-v1/only_ii", + "data_file": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reproduction-v1/data-audit.json", + "data_files": { + "train.json": "6f48e0bece52062f0fa9d5aae4a76438638b1607a8eae8408ee3e7bace422c4b", + "valid.json": "d631cd092cfc5f57a5e51a2f2bb7091935b892dedfddfb33e23e1d6bfb1ccb0d", + "test.json": "3d8d526e3efddc2000d876a21eebc60979541868149343ce4df15c46bf243d6c", + "vocab.json": "51f3a0975cf006a0d050600701eb7efc44158b42b68abb0ab85a6647a366620b" + }, + "tokenizer": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2", + "reference_model": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2", + "world_sha256": "554a9a479f6e528bef1ff5c7586f4a67f6683dd039e401d8087ccdcdd1086b14", + "paper": "Ye et al., NeurIPS 2025", + "original_experiment": "Section 2.3 / Figure 3", + "data_seed": 42, + "paper_data_commit": "d024e6bf353d167a8a140204bfa26b342ab1e824", + "author_training_commit": "734ca654ec7a71dd6737d640407fac14491d538c", + "tracking_group": "implicit-reasoning-paper-reproduction-v2", + "data_file_sha256": "27a20c44f495841a60f54f594f63708692e5c3217344d54509983bc1bb02665c", + "data_sha256": "27a20c44f495841a60f54f594f63708692e5c3217344d54509983bc1bb02665c" + }, + { + "name": "ii_plus_id-seed42", + "arm": "ii_plus_id", + "seed": 42, + "max_steps": 1000000, + "save_steps": 50000, + "save_step_dense": 40000, + "save_step_dense_interval": 2000, + "log_steps": 100, + "dataset": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reproduction-v1/ii_plus_id", + "data_file": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reproduction-v1/data-audit.json", + "data_files": { + "train.json": "fe63e765e4f9b37c033094939006f58f7c70fe40561af70c8df5a6b7790fe751", + "valid.json": "d631cd092cfc5f57a5e51a2f2bb7091935b892dedfddfb33e23e1d6bfb1ccb0d", + "test.json": "3d8d526e3efddc2000d876a21eebc60979541868149343ce4df15c46bf243d6c", + "vocab.json": "51f3a0975cf006a0d050600701eb7efc44158b42b68abb0ab85a6647a366620b" + }, + "tokenizer": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2", + "reference_model": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2", + "world_sha256": "554a9a479f6e528bef1ff5c7586f4a67f6683dd039e401d8087ccdcdd1086b14", + "paper": "Ye et al., NeurIPS 2025", + "original_experiment": "Section 2.3 / Figure 3", + "data_seed": 42, + "paper_data_commit": "d024e6bf353d167a8a140204bfa26b342ab1e824", + "author_training_commit": "734ca654ec7a71dd6737d640407fac14491d538c", + "tracking_group": "implicit-reasoning-paper-reproduction-v2", + "data_file_sha256": "27a20c44f495841a60f54f594f63708692e5c3217344d54509983bc1bb02665c", + "data_sha256": "27a20c44f495841a60f54f594f63708692e5c3217344d54509983bc1bb02665c" + } + ], + "retry_of": "implicit-reasoning-paper-reproduction-v1", + "retry_reason": "Both first attempts stopped at pre-training full-pool decoding of the unassigned padding vocabulary class 52463. Keep logits, architecture, training, data and seeds; make an unmapped generated id printable as an incorrect output.", + "frozen_utc": "2026-10-07T20:47:39.620604+00:00", + "repository": "/ossfs/workspace/llm-memory-editability", + "source_root": "/ossfs/workspace/llm-memory-editability/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source", + "results_root": "/ossfs/workspace/llm-memory-editability/results/implicit-reasoning-paper-reproduction-v2", + "source": { + "configs/experiment-tracking-defaults.json": "41d4b73b9d2f57f71fe51dd8500275f2c9fb3476ec24a9eeee3a8deadb5ecaa2", + "configs/implicit-reasoning-paper-reproduction-v2.json": "745ab22ba49cc704134e67c521bf62f0d45a33c6aa63e559a6599a3286572dbe", + "scripts/execute_learning_use.py": "45e37897d5b1902c33347bb11db0f8b7cc43855c955baa1b3a5f3617a71590ac", + "scripts/run_memory_interface_next.py": "f80f1cfdd3fa0a2685489c4101c234387745e66e46427208b523886eefe96bb3", + "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/loop_kv_learning.py": "4ccd5d0d7adda50daf33a88268b64a28cb6ef36c7db960543045012024888b96", + "src/llm_memory_editability/loop_kv_learning_train.py": "040ca2afd2981ce1e61a9eec571a4e0f1bd5a7f3d22bdc05d24fb22e6419e537", + "src/llm_memory_editability/loop_learning.py": "502153b1aaac4f988103aacc8f3106dc57b0a4d6495115628335c95fc46c64be", + "src/llm_memory_editability/loop_learning_diagnostics.py": "c84e3a584006a8f171dc71d1141a36acca787cb9cd92cbaadd6328ea736f9860", + "src/llm_memory_editability/loop_learning_train.py": "c64a212ac7af73f69e3900092f44ae066b97005964150814adf6457682635afb", + "src/llm_memory_editability/low_rank.py": "e1ddb5714d492311a43af2d5fd3dd5f578d8144db0b3d860ca71e3b603d018e1", + "src/llm_memory_editability/memory_reuse.py": "e95814cd98de22adc54e458f0b5933f2c3f13a0640c0c71a841780a9b1b52e57", + "src/llm_memory_editability/moe_sequential.py": "0ad900ecc7b9da153d74d6f201597399c6de572e149a8e6243852623006bc144", + "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/paper_reproduction.py": "d20e82379e1e5c15d9ca5d052d945061316530e7c40c50b4432e45af7e4caaf0", + "src/llm_memory_editability/parametric_architecture.py": "b444fe7ed463a4167124bce1506caf6710206e05014377bb6cb3092d93100cfb", + "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": "207bd54a0bee05da823d8f90a56f1b508b1958ccd49c361e89146b5847eddc0e", + "src/llm_memory_editability/sequential_replay.py": "205704803c73a4dfce06b577e7fd42f17c959980db7895dc883b680301cfc33d", + "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_paper_reproduction.py": "c35631e9781d78f32a3dfe31e6e22c05479ed665301de61330b768002984a397" + }, + "input_files": { + "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reproduction-v1/data-audit.json": "27a20c44f495841a60f54f594f63708692e5c3217344d54509983bc1bb02665c", + "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2/config.json": "0daed7749b4f02b8f76240d5444551d7b08712dab4d0adb8239c56ba823bb7b4", + "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2/merges.txt": "1ce1664773c50f3e0cc8842619a93edc4624525b728b188a9e0be33b7726adc5", + "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2/model.safetensors": "248dfc3911869ec493c76e65bf2fcf7f615828b0254c12b473182f0f81d3a707", + "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2/tokenizer_config.json": "5e04eb606e3a1583530a42e36c2a6b6615c86f34fe77e44d9ddeb43ff940931f", + "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2/vocab.json": "196139668be63f3b5d6574427317ae82f612a97c5d1cdaf36ed2256dbf636783" + }, + "git_commit": "f298768b6843c8e53a0009b3adc0291eda5fea2c" +} diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/fullpool-smoke.log b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/fullpool-smoke.log new file mode 100644 index 0000000000000000000000000000000000000000..007d4d7bafb931e01645f31e0ca87a54edecb9a3 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/fullpool-smoke.log @@ -0,0 +1,349 @@ +/opt/paper-upstream/transformers/src/transformers/utils/generic.py:441: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead. + _torch_pytree._register_pytree_node( +/opt/paper-upstream/transformers/src/transformers/utils/generic.py:309: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead. + _torch_pytree._register_pytree_node( +numpy version: 1.23.5 +torch version: 2.6.0+cu126 +transformers version: 4.37.0.dev0 +local gpu count: 1 +setting device complete. device: cuda +...initing weights... +### general model args: +LanguageModelingArgs(adafactor_beta1=None, adafactor_clip_threshold=1.0, adafactor_decay_rate=-0.8, adafactor_eps=(1e-30, 0.001), adafactor_relative_step=True, adafactor_scale_parameter=True, adafactor_warmup_init=True, adam_betas=(0.9, 0.999), adam_epsilon=1e-08, best_model_dir='outputs/best_model', cache_dir='/ossfs/workspace/llm-memory-editability/results/implicit-reasoning-paper-validation-v2/runs/author-fullpool-smoke/cache', config={}, cosine_schedule_num_cycles=0.5, custom_layer_parameters=[], custom_parameter_groups=[], dataloader_num_workers=0, do_lower_case=False, dynamic_quantize=False, early_stopping_consider_epochs=False, early_stopping_delta=0, early_stopping_metric='eval_loss', early_stopping_metric_minimize=True, early_stopping_patience=3, encoding=None, eval_batch_size=512, evaluate_during_training=True, evaluate_during_training_silent=True, evaluate_during_training_steps=2000, evaluate_during_training_verbose=False, evaluate_each_epoch=True, fp16=True, gradient_accumulation_steps=1, learning_rate=0.0001, local_rank=-1, logging_steps=50, loss_type=None, loss_args={}, manual_seed=42, max_grad_norm=1.0, max_seq_length=10, model_name='/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2', model_type='gpt2', multiprocessing_chunksize=-1, n_gpu=1, no_cache=True, no_save=False, not_saved_args=[], num_train_epochs=20, optimizer='AdamW', output_dir='/ossfs/workspace/llm-memory-editability/results/implicit-reasoning-paper-validation-v2/runs/author-fullpool-smoke/model-output', overwrite_output_dir=False, polynomial_decay_schedule_lr_end=1e-07, polynomial_decay_schedule_power=1.0, process_count=190, quantized_model=False, reprocess_input_data=True, save_best_model=False, save_eval_checkpoints=False, save_model_every_epoch=False, save_optimizer_and_scheduler=True, save_steps=2, scheduler='constant_schedule_with_warmup', silent=True, skip_special_tokens=True, tensorboard_dir='/ossfs/workspace/llm-memory-editability/results/implicit-reasoning-paper-validation-v2/runs/author-fullpool-smoke/tensorboard', thread_count=None, tokenizer_name=None, tokenizer_type=None, train_batch_size=1024, train_custom_parameters_only=False, use_cached_eval_features=False, use_early_stopping=False, use_hf_datasets=False, use_multiprocessing=False, use_multiprocessing_for_evaluation=True, wandb_kwargs={}, wandb_project=None, warmup_ratio=0.06, warmup_steps=2000, weight_decay=0.1, model_class='LanguageModelingModel', block_size=10, config_name=None, dataset_class=None, dataset_type='None', discriminator_config={}, discriminator_loss_weight=50.0, generator_config={}, max_steps=2, min_frequency=2, mlm=False, mlm_probability=0.15, sliding_window=False, special_tokens=['', '', '', '', ''], stride=0.8, tie_generator_and_discriminator_embeddings=True, vocab_size=None, clean_text=True, handle_chinese_chars=True, special_tokens_list=[], strip_accents=True) +### ddp args: +{'local_rank': -1, 'rank': -1, 'gpu': None, 'world_size': -1, 'dist_url': 'env://', 'dist_backend': 'nccl'} +lm config: +GPT2Config { + "_name_or_path": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2", + "activation_function": "gelu_new", + "architectures": [ + "GPT2LMHeadModel" + ], + "attn_pdrop": 0.1, + "bos_token_id": 50256, + "embd_pdrop": 0.1, + "eos_token_id": 50256, + "initializer_range": 0.02, + "layer_norm_epsilon": 1e-05, + "model_type": "gpt2", + "n_ctx": 1024, + "n_embd": 768, + "n_head": 12, + "n_inner": null, + "n_layer": 8, + "n_positions": 1024, + "no_ln": false, + "no_mlp": false, + "reorder_and_upcast_attn": false, + "resid_pdrop": 0.1, + "scale_attn_by_inverse_layer_idx": false, + "scale_attn_weights": true, + "share_mlp": false, + "summary_activation": null, + "summary_first_dropout": 0.1, + "summary_proj_to_labels": true, + "summary_type": "cls_index", + "summary_use_proj": true, + "task_specific_params": { + "text-generation": { + "do_sample": true, + "max_length": 50 + } + }, + "transformers_version": "4.37.0.dev0", + "use_cache": true, + "vocab_size": 52464 +} + +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +/opt/paper-upstream/transformers/src/transformers/generation/utils.py:2645: UserWarning: Specified kernel cache directory could not be created! This disables kernel caching. Specified directory is /root/.cache/torch/kernels. This warning will appear only once per process. (Triggered internally at /pytorch/aten/src/ATen/native/cuda/jit_utils.cpp:1442.) + next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0) +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +{"step": 0, "examples": 0, "metrics": {"ID Triples": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "OOD Triples": {"total": 2000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "Test-II": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "Test-IO": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "Test-OI": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "Test-OO": {"total": 1986, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "Train-II": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}}} +lm tokenizer: + bos: <|endoftext|> 50256 + eos: <|endoftext|> 50256 + pad: <|endoftext|> 50256 +lm.transformer.wte.weight torch.Size([52464, 768]) +lm.transformer.wpe.weight torch.Size([1024, 768]) +lm.transformer.h.0.ln_1.weight torch.Size([768]) +lm.transformer.h.0.ln_1.bias torch.Size([768]) +lm.transformer.h.0.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.0.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.0.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.0.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.0.ln_2.weight torch.Size([768]) +lm.transformer.h.0.ln_2.bias torch.Size([768]) +lm.transformer.h.0.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.0.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.0.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.0.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.1.ln_1.weight torch.Size([768]) +lm.transformer.h.1.ln_1.bias torch.Size([768]) +lm.transformer.h.1.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.1.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.1.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.1.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.1.ln_2.weight torch.Size([768]) +lm.transformer.h.1.ln_2.bias torch.Size([768]) +lm.transformer.h.1.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.1.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.1.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.1.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.2.ln_1.weight torch.Size([768]) +lm.transformer.h.2.ln_1.bias torch.Size([768]) +lm.transformer.h.2.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.2.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.2.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.2.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.2.ln_2.weight torch.Size([768]) +lm.transformer.h.2.ln_2.bias torch.Size([768]) +lm.transformer.h.2.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.2.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.2.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.2.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.3.ln_1.weight torch.Size([768]) +lm.transformer.h.3.ln_1.bias torch.Size([768]) +lm.transformer.h.3.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.3.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.3.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.3.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.3.ln_2.weight torch.Size([768]) +lm.transformer.h.3.ln_2.bias torch.Size([768]) +lm.transformer.h.3.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.3.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.3.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.3.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.4.ln_1.weight torch.Size([768]) +lm.transformer.h.4.ln_1.bias torch.Size([768]) +lm.transformer.h.4.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.4.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.4.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.4.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.4.ln_2.weight torch.Size([768]) +lm.transformer.h.4.ln_2.bias torch.Size([768]) +lm.transformer.h.4.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.4.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.4.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.4.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.5.ln_1.weight torch.Size([768]) +lm.transformer.h.5.ln_1.bias torch.Size([768]) +lm.transformer.h.5.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.5.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.5.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.5.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.5.ln_2.weight torch.Size([768]) +lm.transformer.h.5.ln_2.bias torch.Size([768]) +lm.transformer.h.5.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.5.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.5.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.5.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.6.ln_1.weight torch.Size([768]) +lm.transformer.h.6.ln_1.bias torch.Size([768]) +lm.transformer.h.6.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.6.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.6.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.6.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.6.ln_2.weight torch.Size([768]) +lm.transformer.h.6.ln_2.bias torch.Size([768]) +lm.transformer.h.6.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.6.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.6.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.6.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.7.ln_1.weight torch.Size([768]) +lm.transformer.h.7.ln_1.bias torch.Size([768]) +lm.transformer.h.7.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.7.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.7.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.7.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.7.ln_2.weight torch.Size([768]) +lm.transformer.h.7.ln_2.bias torch.Size([768]) +lm.transformer.h.7.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.7.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.7.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.7.mlp.c_proj.bias torch.Size([768]) +lm.transformer.ln_f.weight torch.Size([768]) +lm.transformer.ln_f.bias torch.Size([768]) +# params: +40292352|786432|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|total number of optimized params: 97783296 +****************begin training. Total # of steps: 2 warmup steps: 2000 epochs: 1 +/opt/paper-upstream/simpletransformers/simpletransformers/seq2seq/seq2seq_model.py:756: FutureWarning: `torch.cuda.amp.GradScaler(args...)` is deprecated. Please use `torch.amp.GradScaler('cuda', args...)` instead. + scaler = amp.GradScaler() +/opt/paper-upstream/simpletransformers/simpletransformers/seq2seq/seq2seq_model.py:799: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead. + with amp.autocast(): +{"step": 1, "examples": 1024, "loss": 10.958324432373047, "learning_rate": 5.0000000000000004e-08} +/opt/paper-upstream/simpletransformers/simpletransformers/seq2seq/seq2seq_model.py:1019: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead. + with amp.autocast(): +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +{"step": 2, "examples": 2048, "metrics": {"ID Triples": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "OOD Triples": {"total": 2000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "Test-II": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "Test-IO": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "Test-OI": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "Test-OO": {"total": 1986, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "Train-II": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}}, "loss": 10.982955932617188, "learning_rate": 1.0000000000000001e-07} +/opt/paper-upstream/transformers/src/transformers/utils/generic.py:441: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead. + _torch_pytree._register_pytree_node( +/opt/paper-upstream/transformers/src/transformers/utils/generic.py:309: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead. + _torch_pytree._register_pytree_node( +numpy version: 1.23.5 +torch version: 2.6.0+cu126 +transformers version: 4.37.0.dev0 +local gpu count: 1 +setting device complete. device: cuda +Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained. +### general model args: +LanguageModelingArgs(adafactor_beta1=None, adafactor_clip_threshold=1.0, adafactor_decay_rate=-0.8, adafactor_eps=[1e-30, 0.001], adafactor_relative_step=True, adafactor_scale_parameter=True, adafactor_warmup_init=True, adam_betas=[0.9, 0.999], adam_epsilon=1e-08, best_model_dir='outputs/best_model', cache_dir='/ossfs/workspace/llm-memory-editability/results/implicit-reasoning-paper-validation-v2/runs/author-fullpool-smoke/cache', config={}, cosine_schedule_num_cycles=0.5, custom_layer_parameters=[], custom_parameter_groups=[], dataloader_num_workers=0, do_lower_case=False, dynamic_quantize=False, early_stopping_consider_epochs=False, early_stopping_delta=0, early_stopping_metric='eval_loss', early_stopping_metric_minimize=True, early_stopping_patience=3, encoding=None, eval_batch_size=512, evaluate_during_training=True, evaluate_during_training_silent=True, evaluate_during_training_steps=2000, evaluate_during_training_verbose=False, evaluate_each_epoch=True, fp16=True, gradient_accumulation_steps=1, learning_rate=0.0001, local_rank=-1, logging_steps=50, loss_type=None, loss_args={}, manual_seed=42, max_grad_norm=1.0, max_seq_length=10, model_name='/ossfs/workspace/llm-memory-editability/results/implicit-reasoning-paper-validation-v2/runs/author-fullpool-smoke/model-output/checkpoint-2', model_type='gpt2', multiprocessing_chunksize=-1, n_gpu=1, no_cache=True, no_save=False, not_saved_args=[], num_train_epochs=20, optimizer='AdamW', output_dir='/ossfs/workspace/llm-memory-editability/results/implicit-reasoning-paper-validation-v2/runs/author-fullpool-smoke/model-output', overwrite_output_dir=False, polynomial_decay_schedule_lr_end=1e-07, polynomial_decay_schedule_power=1.0, process_count=190, quantized_model=False, reprocess_input_data=True, save_best_model=False, save_eval_checkpoints=False, save_model_every_epoch=False, save_optimizer_and_scheduler=True, save_steps=2, scheduler='constant_schedule_with_warmup', silent=True, skip_special_tokens=True, tensorboard_dir='/ossfs/workspace/llm-memory-editability/results/implicit-reasoning-paper-validation-v2/runs/author-fullpool-smoke/tensorboard', thread_count=None, tokenizer_name=None, tokenizer_type=None, train_batch_size=1024, train_custom_parameters_only=False, use_cached_eval_features=False, use_early_stopping=False, use_hf_datasets=False, use_multiprocessing=False, use_multiprocessing_for_evaluation=True, wandb_kwargs={}, wandb_project=None, warmup_ratio=0.06, warmup_steps=2000, weight_decay=0.1, model_class='LanguageModelingModel', block_size=10, config_name=None, dataset_class=None, dataset_type='None', discriminator_config={}, discriminator_loss_weight=50.0, generator_config={}, max_steps=2, min_frequency=2, mlm=False, mlm_probability=0.15, sliding_window=False, special_tokens=['', '', '', '', ''], stride=0.8, tie_generator_and_discriminator_embeddings=True, vocab_size=None, clean_text=True, handle_chinese_chars=True, special_tokens_list=[], strip_accents=True) +### ddp args: +{'local_rank': -1, 'rank': -1, 'gpu': None, 'world_size': -1, 'dist_url': 'env://', 'dist_backend': 'nccl'} +lm config: +GPT2Config { + "_name_or_path": "/ossfs/workspace/llm-memory-editability/results/implicit-reasoning-paper-validation-v2/runs/author-fullpool-smoke/model-output/checkpoint-2", + "activation_function": "gelu_new", + "architectures": [ + "GPT2LMHeadModel" + ], + "attn_pdrop": 0.1, + "bos_token_id": 50256, + "embd_pdrop": 0.1, + "eos_token_id": 50256, + "initializer_range": 0.02, + "layer_norm_epsilon": 1e-05, + "model_type": "gpt2", + "n_ctx": 1024, + "n_embd": 768, + "n_head": 12, + "n_inner": null, + "n_layer": 8, + "n_positions": 1024, + "no_ln": false, + "no_mlp": false, + "reorder_and_upcast_attn": false, + "resid_pdrop": 0.1, + "scale_attn_by_inverse_layer_idx": false, + "scale_attn_weights": true, + "share_mlp": false, + "summary_activation": null, + "summary_first_dropout": 0.1, + "summary_proj_to_labels": true, + "summary_type": "cls_index", + "summary_use_proj": true, + "task_specific_params": { + "text-generation": { + "do_sample": true, + "max_length": 50 + } + }, + "torch_dtype": "float32", + "transformers_version": "4.37.0.dev0", + "use_cache": true, + "vocab_size": 52464 +} + +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +/opt/paper-upstream/transformers/src/transformers/generation/utils.py:2645: UserWarning: Specified kernel cache directory could not be created! This disables kernel caching. Specified directory is /root/.cache/torch/kernels. This warning will appear only once per process. (Triggered internally at /pytorch/aten/src/ATen/native/cuda/jit_utils.cpp:1442.) + next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0) +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.pdf b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.pdf new file mode 100644 index 0000000000000000000000000000000000000000..4b182b3d578cad1f398fc0630d620c0c2567792d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c2c7ae4d335e8bcf6e6b2fd5a1795eaedbd038375b025d7aeed2a7f4c8d1bb8 +size 587752 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.txt b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.txt new file mode 100644 index 0000000000000000000000000000000000000000..0f325321de61b0e7792aee483afee48d4957034e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.txt @@ -0,0 +1,1482 @@ +Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing , pages 15686–15702 +December 6-10, 2023 ©2023 Association for Computational Linguistics +MQUAKE: Assessing Knowledge Editing in +Language Models via Multi-Hop Questions +Zexuan Zhong†∗, Zhengxuan Wu‡∗, +Christopher D. Manning‡, Christopher Potts‡ and Danqi Chen† +†Princeton University ‡Stanford University +{zzhong,danqic}@cs.princeton.edu {wuzhengx,manning,cgpotts}@stanford.edu +Abstract +The information stored in large language mod- +els (LLMs) falls out of date quickly, and re- +training from scratch is often not an option. +This has recently given rise to a range of tech- +niques for injecting new facts through updating +model weights. Current evaluation paradigms +are extremely limited, mainly validating the +recall of edited facts, but changing one fact +should cause rippling changes to the model’s +related beliefs. If we edit the UK Prime Min- +ister to now be Rishi Sunak , then we should +get a different answer to Who is married to +the British Prime Minister? In this work, we +present a benchmark, MQUAKE (Multi-hop +Question Answering for Knowledge Editing), +comprising multi-hop questions that assess +whether edited models correctly answer ques- +tions where the answer should change as an +entailed consequence of edited facts. While we +find that current knowledge-editing approaches +can recall edited facts accurately, they fail catas- +trophically on the constructed multi-hop ques- +tions. We thus propose a simple memory-based +approach, MeLLo, which stores all edited facts +externally while prompting the language model +iteratively to generate answers that are consis- +tent with the edited facts. While MQUAKE re- +mains challenging, we show that MeLLo scales +well with LLMs (up to 175B) and outperforms +previous model editors by a large margin.1 +1 Introduction +As large language models (LLMs) are deployed +widely, the need to keep their knowledge correct +and up-to-date without massive retraining costs +becomes increasingly important (Sinitsin et al., +2020). Prior work has proposed knowledge editing +methods to incrementally inject a set of new facts +into a language model (Zhu et al., 2021; De Cao +et al., 2021; Meng et al., 2022a,b; Mitchell et al., +*Equal contribution. +1Our datasets and code are publicly available at https: +//github.com/princeton-nlp/MQuAKE. +New Fact: The current British Prime Minister is Rishi Sunak. +Who is the current British +Prime Minister? +Who is married to the +British Prime Minister? +Recall +Edited Fact +Boris Johnson Rishi Sunak +Carrie Johnson Carrie Johnson +Model +Before Edit +Model +After Edit +Our +Question +Who is currently the head +of the British government? +Recall +Related Fact +Boris Johnson Rishi Sunak +Figure 1: An example of our benchmark MQUAKE . +Existing knowledge-editing methods often perform well +at answering paraphrased questions of the edited fact +but fail on multi-hop questions that are entailed conse- +quences of the edited fact. +2022a,b), but it is not yet clear whether these meth- +ods provide a viable solution of updating and main- +taining deployed LLMs. +To evaluate these methods, existing benchmarks +often focus on measuring whether the edited model +can recall the newly injected facts and whether un- +related knowledge remains unchanged post-editing. +However, a vital unaddressed question is whether +the edited model can handle questions where the an- +swer should change as an entailed consequence of +edited facts. For example (see Figure 1), if we up- +date the British Prime Minister from Boris Johnson +to Rishi Sunak within a model, the answer to Who +is married to the British Prime Minister? should +also change as a consequence of this edit. +Therefore, we propose MQUAKE (Multi-hop +Question Answering for Knowledge Editing), a +new benchmark for a more complete evaluation +of knowledge-editing methods. Each example in +MQUAKE consists of a multi-hop question (in- +cluding{2, 3, 4}-hop questions) which corresponds +to a chain of facts. When we edit one or a few facts +in a chain, the edited model needs to propagate +the change to entailed consequences of the edited +facts. MQUAKE includes a dataset MQUAKE- CF +15686 +based on counterfactual edits, and another dataset +MQUAKE- T of temporal knowledge updates to +evaluate model editors on real-world changes. +We evaluate state-of-the-art knowledge-editing +methods on MQUAKE , testing from editing facts +mentioned in one question to editing facts men- +tioned in a large set of questions. The latter setting +evaluates approaches that are designed to handle +many edits, such as MEMIT (Meng et al., 2022b). +Surprisingly, existing knowledge-editing methods +often perform well on answering questions that are +paraphrases of the edited fact but fail drastically +on questions where the answer should change as +a consequence of an edited fact. For example, a +GPT-J model edited by ROME (Meng et al., 2022a) +can only answer 7.6% of multi-hop questions in +MQUAKE- CF, even though it could answer43.4% +of the questions before editing. +Towards faithful knowledge editing, we propose +a simple but effective method, MeLLo, that sig- +nificantly outperforms existing model editors even +with a large number of edits. Instead of updating +model weights, MeLLo stores edits in an explicit +memory inspired by memory-based editing meth- +ods (Mitchell et al., 2022b) and prompts the lan- +guage model iteratively to interact with the edited +facts. Specifically, it decomposes a multi-hop ques- +tion into sub-questions successively, generates ten- +tative answers, and checks whether it is consistent +with edited facts before returning the final answer. +Such a method does not require any additional train- +ing, and can be easily scaled up to large LMs such +as GPT-3 (Brown et al., 2020; Ouyang et al., 2022) +unlike methods requiring weight updates. We hope +that both our benchmark and proposed method +provide additional insights into building faithful +knowledge-editing methods. +2 Problem Definition +This section introduces our setting and argues that +a model edit is only truly successful if the edited +model also returns new correct answers for ques- +tions that change as a consequence of the edits. +2.1 Querying Factual Knowledge in LLMs +We represent a fact as a triple (s, r, o), consist- +ing of a subject ( s), a relation ( r), and an object +(o), and manually construct a natural language +prompt template tr(⋅) for each type of relation +r as a way of querying knowledge from a lan- +guage model (Petroni et al., 2019). This template +takes a subject s as input and generates a ques- +tion or a cloze-style statement tr(s). For instance, +given the subject United Kingdom and the relation +head of government, we can form a cloze sentence +The Prime Minister of the United Kingdom is __ . +We consider an autoregressive language model +f ∶ X → Y, which takes a piece of text x∈ X as in- +put and predicts y ∈ Y, the continuation ofx. Given +a fact triple (s, r, o), we can query the language +model to recall the fact by feeding the prompttr(s) +as input and matching the output f(tr(s)) with +the object o. While prior work has studied how +to prompt to extract more knowledge (Jiang et al., +2020; Shin et al., 2020; Zhong et al., 2021), we sim- +ply use manually-written templates, as enhancing +knowledge retrieval is not our focus. +2.2 Knowledge Editing +The knowledge stored in a language model can +be incorrect or become outdated over time. One +possible solution is to edit the knowledge on the +fly without retraining. A fact edit is defined as a +pair of fact triples that share the same subject and +relation e= ((s, r, o),(s, r, o∗)), which represents +the associated object is updated from o to o∗. For +simplicity, we abbreviate the notation for an edit as +e= (s, r, o → o∗) throughout the paper. +Given a collection of fact edits E = {e1, e2, . . .} +and a language model f, knowledge editing in- +volves learning a function K ∶ F × E → F that +yields an edited language model f∗ ∶ X → Y, +K(f, E) = f∗. For the methods we assess in Sec- +tion 4, K modifies the weights of f in an attempt to +incorporate E. Our proposed alternative, MeLLo, +is much more lightweight: it keeps f frozen and +instead uses E as an external knowledge store to +guide generation (Section 5). +In previous work (De Cao et al., 2021; Mitchell +et al., 2022a,c; Meng et al., 2022a,b), the evaluation +focuses on assessing whether the edited model re- +calls the updated knowledge and whether unrelated +knowledge remains unchanged post-editing. To +evaluate whether a “single-hop” edit e= (s, r, o → +o∗) is successful with an edited model f∗(⋅), exist- +ing paradigms assess whether f∗(tr(s)) is equal +to o∗ (or assigns o∗ a high probability). Addition- +ally, they check correctness by varying tr(s) while +keeping semantic equivalence (Meng et al., 2022b). +2.3 Evaluation of Multi-hop Questions +By only evaluating single-hop questions, exist- +ing methods were tested for recalling edited facts. +15687 +It remains unknown whether an edited model +can handle a question where the answer should +change as an entailed consequence of an edited +fact. We propose to evaluate edited models with +multi-hop questions by considering a chain of +facts C = ⟨(s1, r1, o1), . . . ,(sn, rn, on)⟩, where +the object of ith fact also serves as the subject +of the next fact in the chain, i.e., oi = si+1. We +denote R = [r1, . . . , rn] as the relation set and +S = [s1, . . . , sn] as the subject set. We then use C +to construct a multi-hop question that asks about +the head entity s1, with the answer being the tail +entity on. Similar to a single-hop question, we +generate a question as tR(S). For example, with +a chain consisting of two facts ( United Kingdom, +head of government, Boris Johnson), (Boris John- +son, spouse, Carrie Johnson), one can write a 2- +hop question Who is married to the British Prime +Minister? Once one or more facts in the chain are +edited, e.g., (United Kingdom, head of government, +Boris Johnson → Rishi Sunak), the language model +has to leverage the updated knowledge to answer +the question, which we posit as a crucial indicator +of a model faithfully updating the fact. +3 MQ UAKE: Multi-hop Question +Answering for Knowledge Editing +We construct the benchmark MQUAKE (Multi- +hop Question Answering for Knowledge Editing), +which contains two datasets. The first, MQUAKE- +CF, is designed as a diagnostic dataset for the evalu- +ation of knowledge editing methods on counterfac- +tual edits. The second, MQUAKE- T, comprises +temporal-based knowledge updates and is intended +to assess the effectiveness of knowledge editing +methods in updating outdated information with cur- +rent, real facts. We first present the data construc- +tion process for MQUAKE- CF and MQUAKE- T. +Then, we present the data statistics and evaluation +settings, followed by evaluation metrics in the end. +3.1 Data Construction of MQ UAKE- CF +Sampling chains of facts Our dataset is con- +structed based on Wikidata (Vrande ˇci´c and +Krötzsch, 2014), a knowledge base consisting of +fact triples associated with millions of entities. We +first sample chains of facts from Wikidata. We man- +ually select 37 common relations and consider a +subgraph that solely comprises these relations and +the top 20% of common entities based on hyperlink +counts in Wikipedia articles. 2 We collect chains +that contain N = 2, 3, 4 triples from the Wikidata +subgraph. We also adopt heuristics rules to ensure +that the sampled fact triples are coherent and lead +to natural questions (see Appendix A.1 for details). +Filtering unrecallable facts As answering multi- +hop questions requires the model to leverage each +single-hop fact, we filter out any chain of facts +which contain at least one fact that cannot be re- +called by GPT-J (Wang and Komatsuzaki, 2021), +which we will mainly evaluate on. To recall single- +hop facts, we curate a question template for each +relation type following prior work (Petroni et al., +2019; Meng et al., 2022a), and query the model +using in-context learning with 8 demonstration ex- +amples (see Appendix A.2 for more details). +Generating multi-hop questions Given C = +⟨(s1, r1, o1), . . . ,(sn, rn, on)⟩, we aim to write a +set of questions Q about the head entity s1 with the +gold answer a being the tail entity oN. We leverage +ChatGPT (gpt-3.5-turbo) to automatically gen- +erate questions given a chain of facts C, because +(1) this provides us more diverse question formats +of good quality; (2) it is challenging to manually +write question templates for all the different types. +We prompt ChatGPT to generate three questions +for each sampled chain of facts. We include the +prompt we used and examples of generated multi- +hop questions in Appendix A.3. +Sampling counterfactual edits So far, we +have collected ⟨Q, a,C⟩ (questions, answer, fact +triples) for each instance in the dataset. Next, +we sample counterfactual edits E and col- +lect the corresponding fact triples C∗ and an- +swer a∗. Given a chain of n factual triples C = +⟨(s1, r1, o1), . . . ,(sn, rn, on)⟩, we randomly sam- +ple t ∈ {1, . . . , N} counterfactual edits in C. For +a triple (s, r, o), we sample a counterfactual ob- +ject o∗ from all possible objects that are related to +relation r. We replace (s, r, o) with (s, r, o∗) in +the chain and update other facts accordingly. We +make sure that, after injecting counterfactual ed- +its, the new chain still exists so that we are able +to find an updated answer a∗. We only keep the +sampled edits if the corresponding updated answer +a∗ is not identical to the original one a. We use the +same filtering process as Appendix A.2 to make +2We focus on common entities as LMs can recall facts +about common entities more reliably (Mallen et al., 2023). +15688 +E (W ALL-E, creator, Andrew Stanton→ James Watt) +(University of Glasgow, headquarters location, +Glasgow → Beijing) +Q In which city is the headquarters of the employer of +W ALL-E’s creator located? +What is the location of the headquarters of the company +that employed the creator of W ALL-E? +Where is the headquarters of the company that employed +the creator of W ALL-E situated? +a Emeryville +a∗ Beijing +C (W ALL-E, creator, Andrew Stanton) +(Andrew Stanton, employer, Pixar) +(Pixar, headquarters location, Emeryville) +C∗ +::::::::::(W ALL-E,:::::::creator, ::::::James :::::Watt) +(James Watt, employer, University of Glasgow) +::::::::::(University::of:::::::::Glasgow,::::::::::::headquarters ::::::::location,::::::::Beijing) +Table 1: An instance in the MQUAKE- CF dataset, +which consists of an edit set E, a set of three multi-hop +questions Q, the desirable answer pre- and post-editing +a, a∗, and the chain of facts pre- and post-editing C, C∗. +The edited facts are marked as ::(s,::r, :::o∗). +#Edits 2-hop 3-hop 4-hop Total +MQUAKE- CF +1 2,454 855 446 3,755 +2 2,425 853 467 3,745 +3 - 827 455 1,282 +4 - - 436 436 +All 4,879 2,535 1,804 9,218 +MQUAKE- T 1 (All) 1,421 445 2 1,868 +Table 2: Data statistics of MQUAKE. +sure GPT-J can recall all unedited single-hop facts +in the chains. +3.2 Data Construction of MQ UAKE- T +Following a similar procedure to building +MQUAKE- CF, we construct the other segment: +MQUAKE- T, focusing on temporal-based, real- +world fact updates. We take two dumps of Wiki- +data: 2021-04 and 2023-04, and obtain the differ- +ences between the two versions. We find that most +changes in Wikidata come from schema changes, +i.e., ( Encyclopédie, instance of , encyclopedia → +written work) instead of actual fact updates. We +then manually select 6 relations where the changes +are most likely to align with real fact changes, e.g., +(United Kingdom, head of government, Boris John- +son → Rishi Sunak). Similarly, we sample chains of +facts and filter out unrecallable facts using GPT-J. +When we generate edits given a fact chain, instead +of sampling artificial counterfactual facts, we re- +quire that edits come from the diff set between the +two versions of Wikidata. Note that different from +MQUAKE- CF, each instance in MQUAKE- T re- +lates to only one edit, because all the edits are about +position changes (e.g., head of state) and involving +two in a question is not coherent. The goal of this +dataset is to evaluate how successfully edited lan- +guage models can answer questions which involve +authentic updates to real-world knowledge. +3.3 Dataset Summary +Dataset format As shown in Table 1, each in- +stance in the MQUAKE dataset is denoted by a tu- +ple d= ⟨E, Q, a, a∗, C, C∗⟩, where E is a set of edits +that we want to inject into the language model, Q +represents multi-hop questions we use to evaluate +editing methods (we provide three multi-hop ques- +tions), a and a∗ denote the correct answer before +and after edits, and C and C∗ correspondingly repre- +sent the factual triples associated with this question +before and after editing. A desirable knowledge +editing method will inject all the edits in E into the +model, and enable the model to internally use the +edits and answer the questions. +Data statistics Table 2 summarizes the statistics +of the MQUAKE- CF and MQUAKE- T datasets. +The MQUAKE- CF dataset consists of more than +9K N-hop questions (N ∈ {2, 3, 4}), each of which +associates with one or more edits. 3 We regard +it as a diagnostic dataset to study the ability of +edited models leveraging newly injected knowl- +edge through editing methods. The MQUAKE- T +dataset includes 1.8K instances, each of them asso- +ciates with one real-world fact change. +Number of edited facts We consider two eval- +uation scenarios: a) First, we perform knowl- +edge editing on only one instance d, which is as- +sociated with up to four edited facts. b) Then, +we split the dataset into groups of k instances +(k ∈ {1, 100, 1000, 3000} on MQUAKE- CF and +k ∈ {1, 100, 500, 1868} on MQUAKE- T), and con- +sider all instances in a group at the same time +and inject all the edited facts of these instances +into the model at once. This harder setting is par- +ticularly interesting for editing methods such as +MEMIT, which can handle large numbers of edits +effectively (Meng et al., 2022b). +3Throughout the paper, our experiments on MQUAKE- +CF are conducted on a randomly sampled subset of the full +dataset which includes 3000 instances (1000 instances for each +of {2,3,4}-hop questions) due to limited compute resources. +15689 +Base Model Method Edit-wise Instance-wise Multi-hop Multi-hop (CoT) +GPT-J +Base – 100.0 43.4 42.1 +FT 44.1 24.1 1.6 ↓41.8 1.9 ↓40.2 +MEND 72.8 59.6 9.2 ↓34.2 11.5 ↓30.6 +ROME 90.8 86.7 7.6 ↓35.8 18.1 ↓24.0 +MEMIT 97.4 94.0 8.1 ↓35.3 12.3 ↓29.8 +Vicuna-7B +Base – 61.0 30.0 36.6 +FT 20.2 7.8 0.7 ↓29.3 0.2 ↓36.4 +MEND 65.2 47.6 7.4 ↓22.6 8.4 ↓28.2 +ROME 99.8 89.6 8.4 ↓21.6 12.2 ↓24.4 +MEMIT 96.6 84.0 7.6 ↓22.4 9.0 ↓27.6 +Table 3: Performance results on MQUAKE- CF (maximally 4 edits) for different knowledge editing methods +using two base models, GPT-J and Vicuna-7B. We consider edits associated with each instance independently. +Chain-of-thought (CoT) is included as a more advanced variant of prompt. Base denotes the model before editing. +We include breakdown multi-hop (CoT) performance on MQUAKE- CF for {2,3,4}-hop questions and for questions +with {1,2,3,4} edits in Appendix G. +3.4 Evaluation Metrics +We use the following metrics to measure whether +the edits are made successfully. We include de- +tailed formal definitions in Appendix B. +• Edit-wise success rate measures how many +facts can be successfully recalled from the +edited language model. +• Instance-wise accuracy measures in how +many multi-hop instances, the model can re- +call all the individual single-hop facts. This is +a reference metric for multi-hop performance, +as the model must encode each individual fact +in order to answer the multi-hop question. We +measure instance-wise accuracy both before +and after editing the model. +• Multi-hop accuracy measures the accuracy +of the original and edited language models +on multi-hop questions. In our datasets, there +are three generated multi-hop questions for +each instance. If any of the three questions is +correctly answered by the model, we regard it +as accurate. This is the main metric that we +focus on to study models’ ability to use edited +knowledge consistently. +4 MQ UAKE Challenges Model Editors +4.1 Experimental Setup +Language models We use GPT-J (6B) and +Vicuna-7B (Chiang et al., 2023), which is a fine- +tuned model based on LLaMA-7B (Touvron et al., +2023) as the baseline models to evaluate knowl- +edge editing approaches. It is worth noting that +existing parameter-update methods require access +to a white-box language model and are very com- +putationally expensive to apply to large models. +In Section 5, we propose a lightweight approach, +which can be applied to large black-box language +models (Ouyang et al., 2022; Brown et al., 2020). +Knowledge editing approaches We evaluate the +following state-of-the-art knowledge editing ap- +proaches on our datasets (more details can be found +in Appendix C). +• Fine-tuning (FT) simply performs gradient +descent on the edits to update model parame- +ters. We follow Zhu et al. (2021) and fine-tune +one layer in the model with a norm constraint +on weight changes. +• MEND (Mitchell et al., 2022a) trains a hyper- +network to produce weight updates by trans- +forming the raw fine-tuning gradients given +an edited fact. +• ROME (Meng et al., 2022a) first localizes +the factual knowledge at a certain layer in the +Transformer architecture, and then updates the +feedforward network in that layer to insert the +new facts. +• MEMIT (Meng et al., 2022b) extends ROME +to edit a large set of facts. It updates feedfor- +ward networks in a range of layers to encode +all the facts. +Given an edited fact (s, r, o → o∗), we convert it +to a cloze statement tr(s) and apply knowledge +editing approaches with the objective of correctly +predicting the edited object o∗ given tr(s). We +15690 +Edit- Instance- Multi- Multi-hop +Method wise wise hop (CoT) +Base – 100.0 34.3 46.8 +FT 19.5 19.0 0.0 ↓34.3 0.2 ↓46.6 +MEND 99.0 98.5 16.0 ↓18.3 38.2 ↓8.6 +ROME 100.0 97.7 0.3 ↓34.0 11.3 ↓35.5 +MEMIT 100.0 98.9 0.3 ↓34.0 4.8 ↓42.0 +Table 4: Performance results on MQUAKE- T for differ- +ent knowledge editing methods using GPT-J as the base +model.We consider edits associated with each instance +independently. Base denotes the model before editing. +include the templates of cloze statement tr for each +relation type r in Appendix I. +Evaluation metrics As discussed in Section 3.4, +we report edit-wise success rate, instance-wise ac- +curacy, and multi-hop accuracy in our evaluation. +We query the model with either manually-written +prompt templates (for single-hop facts) or GPT- +generated questions (for multi-hop fact chains). We +adapt in-context learning and prompt the model +with demonstrations when calculating instance- +wise and multi-hop accuracy, in order to encourage +the language model to recall and output knowledge +in the desirable format (Brown et al., 2020). +We also consider chain-of-thought prompting +(Wei et al., 2022) with in-context demonstrations +to ensure the model’s reasoning ability is fully uti- +lized. See Appendix D for detailed prompts that +we used to query language models. We denote the +multi-hop accuracy with chain-of-thought prompt- +ing as multi-hop (CoT). +4.2 Results on MQ UAKE- CF +Table 3 shows the results on MQUAKE- CF when +considering each instance individually across dif- +ferent methods with GPT-J and Vicuna-7B as the +editing base models. As shown, all of the editing +methods perform better than our fine-tuning base- +line. In addition, they all gain traction on edit-wise +evaluation, with MEMIT and ROME achieving +higher than 90% accuracy with GPT-J and Vicuna- +7B. In other words, when injecting a small number +of edits, these techniques successfully inject the ed- +its into language models and have the edited model +recall them at inference time, which corroborates +previous findings (Zhu et al., 2021; De Cao et al., +2021; Meng et al., 2022a; Mitchell et al., 2022a,b). +Subsequently, a low edit-wise success rate entails +a worse instance-wise accuracy (e.g., 59.6% for +MEND vs. 94.0% for MEND), as instance-wise +correctness relies on recalling every fact from the +model correctly for multi-hop questions. +0 500 1000 1500 2000 2500 3000 +Number of Edited Instances +0 +10 +20 +30 +40Multi-hop Acc. (%) +FT +MEND +Base +MEMIT +ROME +(a) MQ UAKE- CF +0 250 500 750 1000 1250 1500 1750 +Number of Edited Instances +0 +10 +20 +30 +40Multi-hop Acc. (%) +FT +MEND +Base +MEMIT +ROME +(b) MQ UAKE- T +Figure 2: Multi-hop performance (CoT) of GPT-J +before and after editing on (a) MQUAKE- CF and +(b) MQUAKE- T across four different knowledge- +editing methods with k edited instances drawn for edit- +ing. k ∈ {1, 100, 1000, 3000} on MQUAKE- CF. k ∈ +{1, 100, 500, 1868} on MQ UAKE- T. +Surprisingly, the performance of edited models +fails catastrophically at answering multi-hop ques- +tions. Even with the strongest baseline approach, +MEMIT, multi-hop performance changes from +43.4% → 8.1% with GPT-J and 30.0% → 7.6% +with Vicuna-7B. Our results lead to a surprising +conclusion that, although these methods act faith- +fully when evaluating with single-hop questions, +all of them fail catastrophically at answering multi- +hop questions that rely on the edited facts. More im- +portantly, compared to the ability to answer multi- +hop questions prior to edits, model performance +drops significantly as well. Our findings suggest +that current knowledge-editing techniques, instead +of integrating new facts into the model as new inter- +nal knowledge, are ratherhard coding them into the +model by updating weights locally. We hope these +results can act as a call to the community to rethink +the faithfulness of knowledge-editing methods and +15691 +Tentative answer +Multi-hop question What is the capital city of the country of +citizenship of Ivanka Trump’s spouse? +Subquestion Who is Ivanka Trump’s spouse? +Tentative answer Ivanka Trump’s spouse is Jared Kushner +Retrieved fact David Cameron is married to Courtney Love +Answer Jared Kushner +Subquestion What is the country of citizenship of Jared Kushner? +The country of citizenship of Jared Kushner is United States +Jared Kushner is a citizen of Canada +Canada +…… …… +Final answer Ottawa +Retrieved fact +Answer +David Cameron is married to Courtney Love +Edited Fact Memory +The capital of the US is Seattle +The CEO of Apple is Carlos Slim +… +Our Approach: MeLLo +Query the memory with a subquestion +Retrieve an edited fact from the memory + Tentative answers generated by the model + Retrieved facts + Edited facts stored in the memory +Jared Kushner is a citizen of Canada +😐 not contradict +⚠ contradict! +Figure 3: The illustration of our proposed method MeLLo. MeLLo decompose a multi-hop question into subques- +tions iteratively. When a subquestion is generated, the base model generates a tentative answer to the subquestion. +Then, the subquestion is used to retrieve a most relevant fact from the edited fact memory. The model checks if the +retrieved fact contradicts the generated answer and updates the prediction accordingly. The concrete prompts used +in MeLLo are shown in Appedix F. +conduct deeper evaluations of edited models. +One hypothesis that these edited models cannot +answer our multi-hop questions faithfully is that +our prompt is not effective enough. Recent works +suggest that providing explanations as Chain-of- +thought (CoT) can greatly increase model perfor- +mance even for models at the scale of 6B models +(Wei et al., 2022). We further enhance our prompt +with explanations and reevaluate all methods. De- +tails about our CoT prompt template can be found +in Appendix D. As shown in Table 3, CoT helps +slightly across all settings yet still fails catastroph- +ically at answering multi-hop questions. This fur- +ther suggests that current knowledge-editing meth- +ods fail to update knowledge faithfully. +4.3 Results on MQ UAKE- T +We evaluate all methods on GPT-J with real-world +knowledge edit on MQUAKE .4 The evaluation +results are shown in Table 4. We find that in +this setting, all methods except fine-tuning achieve +near-perfect performance in terms of edit-wise and +instance-wise accuracy. However, on multi-hop +questions, the performance drops significantly com- +pared to the base model before editing. We find +that MEND works surprisingly well with CoT on +MQUAKE- T. We hypothesize that this may be +due to MEND being particularly effective in edit- +ing certain relations (e.g., head of state ). On the +4We exclude Vicuna-7B on MQUAKE- T as it is trained +more recently, and is likely to be contaminated with the new +knowledge in our temporal questions. +other hand, our results show that the edited model +with CoT can substantially boost multi-hop perfor- +mance. This suggests that explicit knowledge recall +greatly helps the edited models answer multi-hop +questions, while these models struggle to utilize +the edited knowledge internally. +4.4 Evaluation with Edits at Scale +We extend our evaluation and consider all the ed- +its from a randomly split group of k instances +at the same time ( k ∈ {1, 100, 1000, 3000} on +MQUAKE- CF and k ∈ {1, 100, 500, 1868} on +MQUAKE- T). The results are shown in Fig- +ure 2. We find that, on both MQUAKE- CF and +MQUAKE- T, the multi-hop performance of all +methods further drops when injecting more edits +into language models at the same time. +5 MeLLo: A Proposal for Editing Large +Language Models +In Section 4, our evaluation results show that ex- +isting knowledge-editing methods fail catastroph- +ically on multi-hop questions of MQUAKE . In +this section, we present a simple but effective alter- +native, MeLLo (Memory-based Editing for Large +Language Models). +5.1 Method +Figure 3 illustrates how MeLLo answers multi-hop +questions. Inspired by memory-based knowledge- +editing methods (Mitchell et al., 2022b), MeLLo +15692 +keeps the base language model frozen and main- +tains all the edits in an explicit memory. During in- +ference, MeLLo (1) decomposes a multi-hop ques- +tions into subquestions; (2) prompts the base lan- +guage model to provide tentative answers to sub- +questions; and (3) self-checks whether the tentative +answers contradict any edited facts in the mem- +ory. MeLLo can be applied easily to LLMs such as +GPT-3 (Ouyang et al., 2022; Brown et al., 2020). +Edited fact memory MeLLo stores all the edited +facts explicitly in memory. Specifically, all edited +facts are first converted into sentence statements +through manually-defined templates. Then, an off- +the-shelf retrieval model (we use the pretrained +Contriever model; Izacard et al. 2021) is used to +embed all the edit statements and save them in a +retrieval index. The index takes a query as input +and returns an edited fact that is the most relevant +(i.e., closest in the embedding space) to the query. +Step-by-step generation and self-checking To +answer multi-hop questions with LLMs, we fol- +low previous works and first prompt the model to +decompose the multi-hop questions into multiple +simple subquestions (Press et al., 2022; Zhou et al., +2023a). For example, in Figure 3, the first subques- +tion is Who is Ivanka Trump’s spouse? Second, +the model generates a tentative answer (e.g., Jared +Kushner) to the subquestion based on the (unedited) +knowledge stored in the model. Third, to assess +whether the generated answer conflicts with any +new knowledge edits, the subquestion is used as a +query to retrieve a most relevant editing statement +from the edited facts saved in memory. Fourth, +the model is prompted to self-check if the retrieved +fact contradicts the generated answer. If it does, the +model adjusts the intermediate answer to this sub- +question using the retrieved statement. Note that it +is possible that a subquestion does not relate to any +edited fact in memory as the corresponding fact is +not edited; in this case, the model is prompted to +keep the generated answer as the retrieved edit does +not cause a contradiction. Finally, the model either +generates the next subquestion of the multi-hop +question or outputs the final answer. +5.2 Evaluation Results +We apply MeLLo on GPT-J (Wang and Komat- +suzaki, 2021), Vicuna-7B (Chiang et al., 2023), +and text-davinci-003 (Ouyang et al., 2022; +Brown et al., 2020). Table 5 shows performance +of MeLLo on MQUAKE- CF and MQUAKE- T. +We find that with the same base model (i.e., +GPT-J), MeLLo outperforms MEMIT and MEND +significantly across all the settings while be- +ing more efficient and requiring no training. +When incorporating MeLLo with a stronger LLM +(text-davinci-003), MeLLo enlarges the perfor- +mance gap substantially. This suggests that MeLLo +works particularly well on strong base language +models which can easily follow the instructions in +our prompts. Along with its simplicity and efficacy, +we think MeLLo can serve as a strong knowledge- +editing baseline for future research. First, it does +not require access to white-box model weights, so +it is very extensible without any adaptation. Sec- +ond, our base language model remains intact, avoid- +ing the pitfall of overfitting to editing facts or de- +stroying existing capacities due to weight updates. +Third, we store edits in an explicit memory com- +ponent instead of injecting facts into model pa- +rameters, which provides greater controllability in +removing or adding knowledge on the fly. +We note that in order to answer multi-hop ques- +tions correctly after editing, the retriever we use in +MeLLo needs to retrieve all the associated edited +facts from the memory. In Appendix H, we investi- +gate how retrieval accuracy affects the performance +of MeLLo when using GPT-3 as the base model. +6 Related Work +Knowledge-editing methods Past work has in- +vestigated different approaches in editing LLMs +at scale by injecting new knowledge into static +model artifacts (Zhu et al., 2021; Sotoudeh and +Thakur, 2019; Dai et al., 2022a; Hase et al., 2023; +Zhou et al., 2023b; Dong et al., 2022; Huang et al., +2023). Some of these approaches include locating +and modifying model weights that are responsi- +ble for specific concepts (Meng et al., 2022a,b; +Dai et al., 2022b), and fast adaptation through a +small auxiliary editing network (Mitchell et al., +2022a; De Cao et al., 2021). Recent work edits +knowledge representations during decoding pro- +cedures of LLMs (Hernandez et al., 2023). Our +proposed approach MeLLo share a similar spirit +with SERAC (Mitchell et al., 2022b) where an ex- +plicit memory component is used to maintain all +the edited facts. Different from SERAC, which +trains additional models to incorporate the memory, +MeLLo directly uses the base model to self-check +whether the model generations need be adjusted. +This allows MeLLo to be easily applied to black- +15693 +MQUAKE- CF MQUAKE- T +# Edited instances 1 100 1000 3000 1 100 500 1868 +Base Model Method +GPT-J MEMIT 12.3 9.8 8.1 1.8 4.8 1.0 0.2 0.0 +GPT-J MEND 11.5 9.1 4.3 3.5 38.2 17.4 12.7 4.6 +GPT-J MeLLo 20.3 12.5 10.4 9.8 85.9 45.7 33.8 30.7 +Vicuna-7B MeLLo 20.3 11.9 11.0 10.2 84.4 56.3 52.6 51.3 +GPT-3 MeLLo 68.7 50.5 43.6 41.2 91.1 87.4 86.2 85.5 +Table 5: Performance results of MeLLo (ours) on MQUAKE- CF and MQUAKE- T with GPT-J, Vicuna-7B, +or GPT-3 (text-davinci-003) as the base language model. We consider a batch of k instances as once ( k ∈ +{1, 100, 1000, 3000} on MQUAKE- CF and k ∈ {1, 100, 500, 1868} on MQUAKE- T). We include the best results +with GPT-J from existing methods (MEMIT for MQUAKE- CF and MEND for MQ UAKE- T) for comparison. +box LMs without any extra training. +Knowledge-editing evaluation The evaluation +metrics for knowledge-editing techniques often in- +volve verifying the updated answers by querying +the edited facts or related facts (paraphrased or +logically-entailed facts), as well as verifying that ir- +relevant facts are not corrupted (Meng et al., 2022a; +Mitchell et al., 2022a; De Cao et al., 2021; Zhu +et al., 2021; Hase et al., 2023). More recent work +takes a step forward by evaluating LLMs’ abilities +to make inferences based on injected facts (Onoe +et al., 2023) (e.g., after learning iPhone is a smart- +phone, the model should also know iPhone can +browse the internet), or measuring the absence of +unintended side effects of model edits (Hoelscher- +Obermaier et al., 2023). Complementary with +existing evaluation tools, MQUAKE particularly +focuses on assessing whether edited models can an- +swer multi-hop questions where the answer should +change as an entailed consequence, showing that +existing approaches fail on those questions. +Prompting methods for multi-hop QA Since +the debut of effective base models such as GPT-3, +prompt-based methods combined with an optional +retrieval module have become a popular approach +in handling multi-step QA tasks (Press et al., 2022; +Yao et al., 2023; Khattab et al., 2022). Recent +work also seeks to combine external NLI mod- +ules to justify whether answers to prompt-based +queries are able to handle reasoning-based QA +questions (Mitchell et al., 2022c). Our method is +similar but more generic since we rely on the LLM +itself to perform NLI step-by-step before reaching +the final answer. +7 Conclusion +In this work, we present a benchmark MQUAKE +that assesses knowledge editing methods for lan- +guage models via multi-hop questions. We find +that although edited language models can effec- +tively recall edited facts, they fail on multi-hop +questions that are entailed consequences of the ed- +its. We propose a simple but effective alternative, +MeLLo, which significantly outperforms existing +knowledge editing methods. MeLLo does not re- +quire any additional training and can be applied +to large LMs such as GPT-3 (Brown et al., 2020). +We hope our work can facilitate future research on +developing faithful knowledge editing methods. +Limitations +The limitations of our work are as follows. +• We mainly evaluate existing knowledge edit- +ing methods on GPT-J (Wang and Komat- +suzaki, 2021) and Vicuna (Chiang et al., 2023). +The efficacy of these methods on other LLMs +remains less explored. Note that existing edit- +ing methods are very computationally expen- +sive. We leave the evaluation on other models +as future work. +• We demonstrate that MeLLo outperforms ex- +isting knowledge editing methods on models +with > 6B parameters. As MeLLo relies on +language models for question decomposition +and self-checking, future work may study how +MeLLo works with smaller models such as +GPT-2 (Radford et al., 2019). +• Our proposed memory-based approach, +MeLLo, while being very effective on the +MQUAKE benchmark, requires manually +15694 +defined prompts to drive language models +on new tasks. Although we believe MeLLo +is easy to instantiate on different tasks, we +acknowledge this limitation and leave the +evaluation on other tasks as future work. +• The multi-hop questions in MQUAKE are +automatically generated by ChatGPT, rather +than being crafted by humans. Although +MQUAKE- T already involves real knowl- +edge changes, we posit that the use of +human-authored questions could further align +MQUAKE with the realistic applications of +knowledge editing methods. +Acknowledgements +We thank Dan Friedman, Tianyu Gao, Eric +Mitchell, Mengzhou Xia, Howard Yen, Jiayi Geng +for providing valuable feedback. This research is +partially supported by an NSF CAREER award +(IIS-2239290), a Sloan Research Fellowship, and +Microsoft Azure credits through the “Accelerate +Foundation Models Academic Research” Initiative. +ZZ is supported by a JP Morgan Ph.D. Fellowship. +CM is a CIFAR Fellow. +References +Tom Brown, Benjamin Mann, Nick Ryder, Melanie +Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind +Neelakantan, Pranav Shyam, Girish Sastry, Amanda +Askell, et al. 2020. Language models are few-shot +learners. In Advances in Neural Information Process- +ing Systems (NeurIPS). +Wei-Lin Chiang, Zhuohan Li, Zi Lin, Ying Sheng, +Zhanghao Wu, Hao Zhang, Lianmin Zheng, Siyuan +Zhuang, Yonghao Zhuang, Joseph E. Gonzalez, Ion +Stoica, and Eric P. Xing. 2023. Vicuna: An open- +source chatbot impressing GPT-4 with 90%* Chat- +GPT quality. +Damai Dai, Li Dong, Yaru Hao, Zhifang Sui, Baobao +Chang, and Furu Wei. 2022a. Knowledge neurons in +pretrained transformers. In Association for Computa- +tional Linguistics (ACL). +Damai Dai, Li Dong, Yaru Hao, Zhifang Sui, Baobao +Chang, and Furu Wei. 2022b. Knowledge neurons in +pretrained transformers. In Association for Computa- +tional Linguistics (ACL). +Nicola De Cao, Wilker Aziz, and Ivan Titov. 2021. +Editing factual knowledge in language models. In +Empirical Methods in Natural Language Processing +(EMNLP). +Qingxiu Dong, Damai Dai, Yifan Song, Jingjing Xu, +Zhifang Sui, and Lei Li. 2022. Calibrating factual +knowledge in pretrained language models. In Find- +ings of Empirical Methods in Natural Language Pro- +cessing (EMNLP). +Peter Hase, Mona Diab, Asli Celikyilmaz, Xian Li, Zor- +nitsa Kozareva, Veselin Stoyanov, Mohit Bansal, and +Srinivasan Iyer. 2023. Do language models have +beliefs? Methods for detecting, updating, and visu- +alizing model beliefs. In European Chapter of the +Association for Computational Linguistics (EACL) . +Evan Hernandez, Belinda Z Li, and Jacob Andreas. +2023. Measuring and manipulating knowledge rep- +resentations in language models. arXiv preprint +arXiv:2304.00740. +Jason Hoelscher-Obermaier, Julia Persson, Esben Kran, +Ioannis Konstas, and Fazl Barez. 2023. Detect- +ing edit failures in large language models: An +improved specificity benchmark. arXiv preprint +arXiv:2305.17553. +Zeyu Huang, Yikang Shen, Xiaofeng Zhang, Jie Zhou, +Wenge Rong, and Zhang Xiong. 2023. Transformer- +patcher: One mistake worth one neuron. In Inter- +national Conference on Learning Representations +(ICLR). +Gautier Izacard, Mathilde Caron, Lucas Hosseini, Se- +bastian Riedel, Piotr Bojanowski, Armand Joulin, +and Edouard Grave. 2021. Towards unsupervised +dense information retrieval with contrastive learn- +ing. Transactions on Machine Learning Research +(TMLR). +Zhengbao Jiang, Frank F Xu, Jun Araki, and Graham +Neubig. 2020. How can we know what language +models know? In Transactions of the Association of +Computational Linguistics (TACL). +Omar Khattab, Keshav Santhanam, Xiang Lisa +Li, David Hall, Percy Liang, Christopher Potts, +and Matei Zaharia. 2022. Demonstrate-search- +predict: Composing retrieval and language mod- +els for knowledge-intensive NLP. arXiv preprint +arXiv:2212.14024. +Alex Mallen, Akari Asai, Victor Zhong, Rajarshi Das, +Hannaneh Hajishirzi, and Daniel Khashabi. 2023. +When not to trust language models: Investigating +effectiveness and limitations of parametric and non- +parametric memories. In Association for Computa- +tional Linguistics (ACL). +Kevin Meng, David Bau, Alex Andonian, and Yonatan +Belinkov. 2022a. Locating and editing factual asso- +ciations in GPT. In Advances in Neural Information +Processing Systems (NeurIPS). +Kevin Meng, Arnab Sen Sharma, Alex Andonian, +Yonatan Belinkov, and David Bau. 2022b. Mass- +editing memory in a transformer. In International +Conference on Learning Representations (ICLR) . +15695 +Eric Mitchell, Charles Lin, Antoine Bosselut, Chelsea +Finn, and Christopher D Manning. 2022a. Fast model +editing at scale. In International Conference on +Learning Representations (ICLR). +Eric Mitchell, Charles Lin, Antoine Bosselut, Christo- +pher D Manning, and Chelsea Finn. 2022b. Memory- +based model editing at scale. In International Con- +ference on Machine Learning (ICML) . +Eric Mitchell, Joseph J. Noh, Siyan Li, William S. Arm- +strong, Ananth Agarwal, Patrick Liu, Chelsea Finn, +and Christopher D. Manning. 2022c. Enhancing self- +consistency and performance of pretrained language +models with NLI. In Empirical Methods in Natural +Language Processing (EMNLP). +Yasumasa Onoe, Michael JQ Zhang, Shankar Padman- +abhan, Greg Durrett, and Eunsol Choi. 2023. Can +lms learn new entities from descriptions? Challenges +in propagating injected knowledge. In Association +for Computational Linguistics (ACL). +Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, Car- +roll L. Wainwright, Pamela Mishkin, Chong Zhang, +Sandhini Agarwal, Katarina Slama, Alex Ray, John +Schulman, Jacob Hilton, Fraser Kelton, Luke E. +Miller, Maddie Simens, Amanda Askell, Peter Welin- +der, Paul Francis Christiano, Jan Leike, and Ryan J. +Lowe. 2022. Training language models to follow +instructions with human feedback. In Advances in +Neural Information Processing Systems (NeurIPS) . +Fabio Petroni, Tim Rocktäschel, Patrick Lewis, An- +ton Bakhtin, Yuxiang Wu, Alexander H Miller, and +Sebastian Riedel. 2019. Language models as knowl- +edge bases? In Empirical Methods in Natural Lan- +guage Processing (EMNLP). +Ofir Press, Muru Zhang, Sewon Min, Ludwig Schmidt, +Noah A Smith, and Mike Lewis. 2022. Measuring +and narrowing the compositionality gap in language +models. arXiv preprint arXiv:2210.03350. +Alec Radford, Jeffrey Wu, Rewon Child, David Luan, +Dario Amodei, Ilya Sutskever, et al. 2019. Language +models are unsupervised multitask learners. OpenAI +blog. +Taylor Shin, Yasaman Razeghi, Robert L Logan IV , +Eric Wallace, and Sameer Singh. 2020. Autoprompt: +Eliciting knowledge from language models with auto- +matically generated prompts. In Empirical Methods +in Natural Language Processing (EMNLP) , pages +4222–4235. +Anton Sinitsin, Vsevolod Plokhotnyuk, Dmitry Pyrkin, +Sergei Popov, and Artem Babenko. 2020. Editable +neural networks. In International Conference on +Machine Learning (ICML). +Matthew Sotoudeh and Aditya V Thakur. 2019. Cor- +recting deep neural networks with small, generalizing +patches. In Workshop on Safety and Robustness in +Decision Making. +Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier +Martinet, Marie-Anne Lachaux, Timothée Lacroix, +Baptiste Rozière, Naman Goyal, Eric Hambro, +Faisal Azhar, et al. 2023. LLaMA: Open and ef- +ficient foundation language models. arXiv preprint +arXiv:2302.13971. +Denny Vrandeˇci´c and Markus Krötzsch. 2014. Wiki- +data: a free collaborative knowledgebase. Communi- +cations of the ACM, 57(10):78–85. +Ben Wang and Aran Komatsuzaki. 2021. GPT-J- +6B: A 6 Billion Parameter Autoregressive Lan- +guage Model. https://github.com/kingoflolz/ +mesh-transformer-jax. +Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten +Bosma, Ed Chi, Quoc Le, and Denny Zhou. 2022. +Chain of thought prompting elicits reasoning in large +language models. In Advances in Neural Information +Processing Systems (NeurIPS). +Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak +Shafran, Karthik Narasimhan, and Yuan Cao. 2023. +ReAct: Synergizing reasoning and acting in language +models. In International Conference on Learning +Representations (ICLR). +Zexuan Zhong, Dan Friedman, and Danqi Chen. 2021. +Factual probing is [MASK]: Learning vs. learning to +recall. In North American Chapter of the Association +for Computational Linguistics (NAACL). +Denny Zhou, Nathanael Schärli, Le Hou, Jason Wei, +Nathan Scales, Xuezhi Wang, Dale Schuurmans, +Olivier Bousquet, Quoc Le, and Ed Chi. 2023a. +Least-to-most prompting enables complex reasoning +in large language models. In International Confer- +ence on Learning Representations (ICLR) . +Wenxuan Zhou, Sheng Zhang, Hoifung Poon, and +Muhao Chen. 2023b. Context-faithful prompt- +ing for large language models. arXiv preprint +arXiv:2303.11315. +Chen Zhu, Ankit Singh Rawat, Manzil Zaheer, Srinadh +Bhojanapalli, Daliang Li, Felix Yu, and Sanjiv Kumar. +2021. Modifying memories in transformer models. +In International Conference on Machine Learning +(ICML). +15696 +A Details of Dataset Construction +A.1 Sampling Fact Chains from Wikidata +We collect chains of facts that containN = {2, 3, 4} +triples from Wikidata. We adopt heuristic rules to +ensure that the sampled fact triples are coherent +and lead to natural questions. Specifically, we ap- +ply the following constraints when sampling fact +chains from Wikidata. (1) The sampled chain does +not involve a circle; (2) The sampled chain does +not contain two triples that share the same relation +type; (3) The triples with the object being a country +can only appear in the last two hops of the chain; +(4) The sampled chain contains up to three object +types; (5) All triples with a person or location ob- +ject are consecutive in the chain; (6) The subject +entity associated with the relation headquarters +location (P159) must be a company or an organi- +zation; (7) In all triples with the relation capital +(P36), the subject has to be a country. To use these +heuristic rules, we manually label the object types +for each relation we consider. For example, the +relation head of state (P35) corresponds to a person +as the object. +A.2 Filtering Unrecallable Facts with GPT-J +We filter out any chain of facts which contain at +least one fact that cannot be recalled by GPT-J. For +each relation type, we manually define a question +template as well as 8 demonstration examples for +in-context-learning. We use in-context-learning to +ensure the model can capture the answer format +from the context. Table 6 shows an example of the +prompt we use to recall facts of the relation devel- +oper (P178). We include the question templates of +all relations on MQ UAKE in Appendix I. +A.3 Generating Questions using ChatGPT +Given a chain of facts, we prompt ChatGPT +(gpt-3.5-turbo) to automatically generate multi- +hop questions. The prompt we used is shown in +Table 7. +In Table 8, we show some randomly selected +examples of the questions generated by ChatGPT +on MQUAKE- CF. We select 3 instances from +2, 3, 4−hop questions, each of which contains three +generated questions. As shown, ChatGPT success- +fully transforms the chain of triples into grammati- +cally correct questions. Although these multi-hop +questions are synthetic, they are logically consis- +tent with the flow of the triple chains. We believe +these generated questions are of sufficient qual- +ity for assessing the efficacy of knowledge-editing +methods. +B Evaluation Metrics +We evaluate the editing results based on three evalu- +ation metrics: edit-wise success rate, instance-wise +accuracy, and multi-hop accuracy. Suppose we +have edited a language model and obtain the edited +model f∗(⋅). +Edit-wise success rate measures how many +edited facts can be recalled by the edited language +model. Given an edit e= (s, r, o → o∗), the editing +success is defined as 1 [f∗(tr(s))= o∗]. We take +the averaged value of the all edits in the dataset and +refer it as the edit-wise success rate metric. +Instance-wise accuracy measures how many in- +stances are there where all the associated facts +can be recalled by the language model (either +the original or edited one). Given an instance +d= ⟨E, Q, a, a∗, C, C∗⟩, the instance-wise accuracy +before editing is defined as +1 +⎡⎢⎢⎢⎢⎣ +⋀ +(s,r,o)∈C +[f(tr(s))= o] +⎤⎥⎥⎥⎥⎦ +, +and the instance-wise accuracy post editing is de- +fined as +1 +⎡⎢⎢⎢⎢⎣ +⋀ +(s,r,o)∈C∗ +[f∗(tr(s))= o∗] +⎤⎥⎥⎥⎥⎦ +. +We report the averaged instance-wise accuracy in +our evaluation. +Multi-hop accuracy measures the accuracy on +multi-hop questions. We regard an instance be- +ing predicted correctly if any of the multi-hop +questions are answered correctly by the language +model. Given an instance d = ⟨E, Q, a, a∗, C, C∗⟩, +the multi-hop accuracy before editing is defined as +1 +⎡⎢⎢⎢⎣ +⋁ +q∈Q +[f(q)= a] +⎤⎥⎥⎥⎦ +, +and the multi-hop accuracy post editing is defined +as +1 +⎡⎢⎢⎢⎣ +⋁ +q∈Q +[f∗(q)= a∗] +⎤⎥⎥⎥⎦ +. +We report the averaged multi-hop accuracy in our +evaluation. +15697 +(In-context-learning examples) +Q: Who is the developer of Telegram? A: Telegram FZ-LLC +Q: Who is the developer of Microsoft Windows? A: Microsoft +Q: Who is the developer of PlayStation 2? A: Sony Interactive Entertainment +Q: Who is the developer of iTunes? A: Apple Inc. +Q: Who is the developer of SR-71 Blackbird? A: Kelly Johnson +Q: Who is the developer of Moblin? A: Linux Foundation +Q: Who is the developer of Xbox 360? A: Microsoft +Q: Who is the developer of Kinsey scale? A: Alfred Kinsey +(Query during inference) +Q: Who is the developer of SteamOS? A: Valve Corporation +Table 6: An example of the prompt we used to recall single-hop factf with relation developer (P178) from language +models. We use in-context-learning with 8 demonstration examples to ensure the model can output the answer in a +desirable format. +System: +You are a powerful multi-hop question generator. Users will provide a chain of Wikidata triples, +and you will help write questions to ask the tail entity from the head entity. You shouldn’t +include bridge entities in generated questions. The questions should only include the head entity. +[12 in-context demonstrations abbreviated ] +User: +Given Wikidata triples (Daredevil/Bullseye: The Target, author, x1), (x1, country of citizenship, +x2), (x2, continent, x3), write a question to ask x3. Don’t mention x1, x2, ... Write three +possible questions in natural English. +System: +1. What continent is the country of citizenship of the author of Daredevil/Bullseye: The Target +located in? +2. From which continent does the author of Daredevil/Bullseye: The Target’s country of citizenship +belong? +3. What continent is the author’s country of citizenship, who wrote Daredevil/Bullseye: The Target, +situated in? +Table 7: An example of using ChatGPT (gpt-3.5-turbo) to generate questions from Wikidata triples. We manually +write 12 demonstrations as the prompt when querying ChatGPT. +C Implementation Details for Knowledge +Editing Methods +C.1 Fine-tuning +Our fine-tuning baseline (FT) performs gradient +descent on the edits to update model parameters. +We fine-tune layer 21 of GPT-J and layer 31 of +Vicuna-7B. We follow Zhu et al. (2021) and use a +norm constraint on weight changes with a coeffi- +cient 5 × 10−5 in our implementation. +C.2 MEND +We use the GPT-J MEND editor trained by Meng +et al. (2022a). For Vicuna-7B, we train our own +MEND editor model on the Wikitext generation +editing dataset (Mitchell et al., 2022a) with the +different hyperparameters. During inference, we +set the learning rate scale to be 1.0. +C.3 ROME +For GPT-J, we use the default hyperparameters of +ROME and the pre-computed covariance statistics +released by Meng et al. (2022a). For Vicuna-7B, +we run ROME to update model weights at layer +9 with the default hyperparameters. We compute +the covariance statistics for Vicuna-7B on Wikitext +using a sample size of 100,000. +C.4 MEMIT +For GPT-J, we use the default hyperparameters of +MEMIT and the pre-computed covariance statistics +released by Meng et al. (2022b). For Vicuana-7B, +we update model weights at layers {5, 6, 7, 8, 9} +with the default hyperparameters. Similarly, we +compute the covariance statistics for Vicuna-7B on +Wikitext using a sample size of 100,000. +15698 +Examples of 2-hop questions +C (Jacques Necker, employer, University of Geneva) (University of Geneva, headquarters location, Geneva) +Q What is the location of the headquarters of the employer of Jacques Necker? +Where is the employer of Jacques Necker headquartered? +In which city is the head office located for the company that employed Jacques Necker? +C (Percival Lowell, educated at, Harvard University) (Harvard University, headquarters location, Cambridge) +Q What is the location of the headquarters of the institution where Percival Lowell was educated? +In which city is the institution located where Percival Lowell received his education? +Where is the headquarters of the educational institution attended by Percival Lowell located? +C (Gordon Moore, country of citizenship, United States of America) (United States of America, capital, Washington, D.C.) +Q What is the capital of the country where Gordon Moore holds citizenship? +Which is the capital city of the country to which Gordon Moore belongs? +In which city is the seat of the government of the country where Gordon Moore is a citizen? +Examples of 3-hop questions +C (Kim Kardashian, spouse, Kanye West) (Kanye West, genre, hip hop music) +(hip hop music, country of origin, United States of America) +Q What is the country of origin of the genre associated with the spouse of Kim Kardashian? +From which country does the genre of the partner of Kim Kardashian hail? +Which country is the genre of the partner of Kim Kardashian associated with originally from? +C (Nicholas of Tolentino, religion or worldview, Catholic Church) (Catholic Church, founded by, Jesus Christ) +(Jesus Christ, place of birth, Bethlehem) +Q Where was the founder of Nicholas of Tolentino’s religion born? +In which city was the founder of the religion that Nicholas of Tolentino adhered to born? +What is the birthplace of the founder of the religion that Nicholas of Tolentino followed? +C (Boston, head of government, Marty Walsh) (Marty Walsh, educated at, Boston College) +(Boston College, headquarters location, Chestnut Hill) +Q In what city is the headquarters of the institution where the head of government of Boston was educated located? +Where is the location of the headquarters of the educational institution where the head of government of Boston +received their education? +What is the city where the headquarters of the institution where the head of government of Boston was educated +at located? +Examples of 4-hop questions +C (Xbox Live, developer, Microsoft) (Microsoft, chief executive officer, Satya Nadella) +(Satya Nadella, place of birth, Hyderabad) (Hyderabad, continent, Asia) +Q Which continent is home to the birthplace of the CEO of Xbox Live developer? +Where was the CEO of the developer of Xbox Live born in which continent? +In what continent was the CEO of Xbox Live’s developer born? +C (Winnie the Pooh, creator, A. A. Milne) (A. A. Milne, child, Christopher Robin Milne) +(Christopher Robin Milne, country of citizenship, United Kingdom) (United Kingdom, official language, English) +Q What is the official language of the country where the child of Winnie the Pooh’s creator holds citizenship? +Which language is officially spoken in the country where the child of the creator of Winnie the Pooh is a citizen? +What is the officiated language of the country where the child of Winnie the Pooh’s creator is a citizen of? +C (watchOS, developer, Apple Inc.) (Apple Inc., chief executive officer, Tim Cook) +(Tim Cook, country of citizenship, United States of America) (United States of America, capital, Washington, D.C.) +Q What is the capital of the country where the CEO of the developer of watchOS holds citizenship? +In which city does the CEO of the company that developed watchOS hold citizenship? +Which city is the capital of the home country of the CEO of the developer of watchOS? +Table 8: Qualitative examples of the generated multi-hop questions on MQUAKE- CF. Given a chain of facts, we +query ChatGPT (gpt-3.5-turbo) to generate multi-hop questions with the prompt shown in Table 7. +D Chain-of-thought Prompting for +Multi-hop Questions +We use chain-of-thought (CoT) prompting (Wei +et al., 2022) to maximize model performance. Ta- +ble 9 shows one simplified example of our prompt +with CoT. +E Extended Golden Labels for +MQUAKE- T +Our MQUAKE- T contains limited test cases. To +better assess the model’s original performance on +multi-hop questions, we extend the possible golden +labels for each multi-hop question. Specifically, +we allow outdated answers given smaller language +15699 +Question: What is the capital of the country where Plainfield Town Hall is located? +Thoughts: Plainfield Town Hall is located in the country of the United States of America. The +capital of United States is Washington, D.C. +Answer: Washington, D.C. +Question: In which country is the company that created Nissan 200SX located? +Thoughts: Nissan 200SX was created by Nissan. Nissan is located in the country of Japan. +Answer: Japan +[3 in-context demonstrations abbreviated ] +Question: Who has ownership of the developer of the Chevrolet Corvette (C4)? +Thoughts: The developer of Chevrolet Corvette (C4) is Chevrolet. Chevrolet is owned by General +Motors. +Answer: Model Generated Answer Goes Here +Table 9: The template of the prompt we used for asking multi-hop questions using chain-of-thoughts. +Please answer the following question faithfully using the knowledge you have from Wikipedia. +Provide 10 possible answers to the question, using all the Wikipedia data you know. Rank them from +the most current to the most outdated. +Input: What is the name of the current head of the United States of America government? +Output: +Joe Biden +Donald Trump +Barack Obama +George W. Bush +Bill Clinton +George H. W. Bush +Ronald Reagan +Jimmy Carter +Gerald Ford +Richard Nixon +Input: What is the name of the current head of the New York City government? +Output: Model Generated Answer Goes Here +Table 10: The template of the prompt we used for extending golden labels for MQUAKE- T. The prompt contains +one demonstration for better aligning model behaviors. +models tend to be less calibrated. To extend the +golden labels, we use GPT-3 (text-davinci-003) +to query outdated answers. See the prompt we used +in Table 10. +F Prompts used in MeLLo +The prompt we used in MeLLo is shown in Ta- +ble 11. We first prompt the language model to de- +compose subquestions. Then the language model +generates a tentative question to the subquestion +(marked in green text); then we use the generated +subquestion to retrieve the most relevant edited fact +(marked in light blue text) and append it to the +prompt. The model self-checks if the retrieved fact +contradicts the generated answer. The prompting +procedure goes iteratively until the model generates +the final answer. +G Breakdown Results on MQ UAKE- CF +Table 12 and Table 13 present the breakdown re- +sults on MQUAKE- CF when using GPT-J as the +base model. We find that, in all editing methods +(1) the performance on 2-hop questions is much +higher than 3-hop and 4-hop questions; (2) the +performance is worse when there are more edits +asssociated with the edited instances. +H Impact of Retrieval Performance +In MeLLo, in order to answer multi-hop questions +correctly after editing, the retrieval model needs to +retrieve all the associated edited facts (each ques- +tion is associated with 1-4 edited facts) from the +memory. Here we investigate how retrieval accu- +racy affects the performance of MeLLo when using +GPT-3 as the base model. We compute the retrieval +accuracy (i.e., how many instances where all the as- +15700 +[4 in-context demonstrations abbreviated ] +Question: What is the capital city of the country of citizenship of Ivanka Trump’s spouse? +Subquestion: Who is Ivanka Trump’s spouse? +Generated answer: Ivanka Trump’s spouse is Jared Kushner. +Retrieved fact: David Cameron is married to Samantha Cameron. +Retrieved fact does not contradict to generated answer, so the intermediate answer is: Jared +Kushner +Subquestion: What is the country of citizenship of Jared Kushner? +Generated answer: The country of citizenship of Jared Kushner is United States. +Retrieved fact: Jared Kushner is a citizen of Canada. +Retrieved fact contradicts to generated answer, so the intermediate answer is: Canada +Subquestion: What is the capital city of Canada? +Generated answer: The capital city of Canada is Ottawa. +Retrieved fact: The capital city of United States is Seattle. +Retrieved fact does not contradict to generated answer, so the intermediate answer is: Ottawa +Final answer: Ottawa +Table 11: A step-by-step illustration of MeLLo solving one simplified example. Green parts are generated by the +language model, and blue parts are facts retrieved by the retriever. +2-hop 3-hop 4-hop All +Base 47.5 27.1 45.3 42.1 +FT 3.7 1.4 0.5 1.9 +MEND 13.9 11.3 9.5 11.5 +ROME 33.8 9.1 11.4 18.1 +MEMIT 22.5 6.0 8.4 12.3 +Table 12: Breakdown multi-hop performance (CoT) on +MQUAKE- CF for {2,3,4}-hop questions. We use GPT- +J as the base model in this experiment +# Edits = 1 2 3 4 All +Base 34.0 43.0 40.4 51.7 42.1 +FT 4.2 0.7 0.3 0.0 1.9 +MEND 16.0 11.0 7.3 4.4 11.5 +ROME 23.8 20.9 9.0 2.6 18.1 +MEMIT 20.5 9.8 5.5 2.6 12.3 +Table 13: Breakdown multi-hop performance (CoT) on +MQUAKE- CF for questions with {1,2,3,4} edits. We +use GPT-J as the base model in this experiment. +# Instances (k =) 1 100 1000 3000 +Retrieval acc. 93.6 67.7 59.4 58.7 +MeLLo (on GPT-3) 68.7 50.5 43.6 41.2 +Table 14: How retrieval accuracy affects the multi-hop +performance of MeLLo on MQUAKE- CF. We consider +a group of k instances at the same time. Retrieval acc.: +how many instances where all the associated edited facts +are correctly retrieved from the memory. +sociated edited facts are correctly retrieved from the +memory) when applying MeLLo on MQUAKE- +CF with GPT-3 by considering different numbers +of edited instances at the same time. As Table 14 +shows, the performance of MeLLo decreases if the +retrieval accuracy is lower (as a result of consider- +ing more instances at the same time). Among those +questions where all associated facts are success- +fully retrieved from memory, MeLLo can answer +73.1% of them correctly. This indicates that re- +trieval performance can significantly impact the +model performance. When we consider more ir- +relevant knowledge edits in the memory, retrieval +can be more challenging, and we expect that using +more advanced retrieval techniques can improve +the performance. +I Question/Cloze Statement Templates +used in MQ UAKE +Table 15 shows the question templates and +the cloze-style statement templates we use in +MQUAKE. We use the question templates to query +single-hop facts when we use GPT-J for filtering +and use the cloze-style statement templates to con- +vert an edited fact to a natural language statement. +15701 +Relation Question template Cloze-style statement template +P30 Which continent is [S] located in? [S] is located in the continent of +P36 What is the capital of [S]? The capital of [S] is +P35 What is the name of the current head of state in [S]? The name of the current head of state in [S] is +P6 What is the name of the current head of the [S] government? The name of the current head of the [S] government is +P20 Which city did [S] die in? [S] died in the city of +P26 Who is [S] married to? [S] is married to +P140 Which religion is [S] affiliated with? [S] is affiliated with the religion of +P1412 What language does [S] speak? [S] speaks the language of +P19 Which city was [S] born in? [S] was born in the city of +P69 Which university was [S] educated at? The univeristy where [S] was educated is +P40 Who is [S]’s child? [S]’s child is +P27 What is the country of citizenship of [S]? [S] is a citizen of +P175 Who performed [S]? [S] was performed by +P108 Who is the employer of [S]? [S] is employed by +P112 Who founded [S]? [S] was founded by +P50 Who is the author of [S]? The author of [S] is +P170 Who was [S] created by? [S] was created by +P407 Which language was [S] written in? [S] was written in the language of +P37 What is the official language of [S]? The official language of [S] is +P740 Where was [S] founded? [S] was founded in the city of +P495 Which country was [S] created in? [S] was created in the country of +P106 What kind of work does [S] do? [S] works in the field of +P136 What type of music does [S] play? The type of music that [S] plays is +P364 What is the original language of [S]? The original language of [S] is +P937 Which city did [S] work in? [S] worked in the city of +P800 What is [S] famous for? [S] is famous for +P641 Which sport is [S] associated with? [S] is associated with the sport of +P413 What position does [S] play? [S] plays the position of +P286 Who is the head coach of [S]? The head coach of [S] is +P159 Which city is the headquarter of [S] located in? The headquarters of [S] is located in the city of +P178 Who is the developer of [S]? [S] was developed by +P488 Who is the chairperson of [S]? The chairperson of [S] is +P169 Who is the chief executive officer of [S]? The chief executive officer of [S] is +P449 Who is the original broadcaster of [S]? The origianl broadcaster of [S] is +P176 Which company is [S] produced by? The company that produced [S] is +P1037 Who is the director of [S]? The director of [S] is +P1308 Who is the [S]? The [S] is +Table 15: Question templates and cloze-style statement templates that are used in MQUAKE . “[S]” represents a +placeholder for the subject entity of the fact. We use the question templates to query single-hop facts when we use +GPT-J for filtering and use the cloze-style statement templates to convert an edited fact to a statement. +15702 \ No newline at end of file diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.pdf b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.pdf new file mode 100644 index 0000000000000000000000000000000000000000..b644a83f9865399d0cb1366ab4b2b0878308f5d4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:131344c1b52cacb5d062ffd261b455a1a1cc0d9f2b70555de429455eb23be15c +size 1648738 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.txt b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.txt new file mode 100644 index 0000000000000000000000000000000000000000..77cc83636192e901985726d45f4086c91e9e50a1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.txt @@ -0,0 +1,1400 @@ +Evaluating the Ripple Effects of Knowledge Editing in Language Models +Roi Cohen1 Eden Biran1 Ori Yoran1 Amir Globerson1,2 Mor Geva1,2,∗ +1Blavatnik School of Computer Science, Tel Aviv University, Israel 2Google Research, Israel +{roi1, edenbiran, oriy }@mail.tau.ac.il, {gamir, morgeva }@tauex.tau.ac.il +Abstract +Modern language models capture a large body +of factual knowledge. However, some facts +can be incorrectly induced or become obso- +lete over time, resulting in factually incorrect +generations. This has led to the development +of various editing methods that allow updat- +ing facts encoded by the model. Evaluation of +these methods has primarily focused on testing +whether an individual fact has been success- +fully injected, and if similar predictions for +other subjects have not changed. Here we +argue that such evaluation is limited, since in- +jecting one fact (e.g., ‘ ‘ J a c kD e p pi st h es o no f +Johnny Depp’’ ) introduces a ‘‘ripple effect’’ +in the form of additional facts that the model +needs to update (e.g., ‘‘Jack Depp is the sib- +ling of Lily-Rose Depp’’ ). To address this, we +propose novel evaluation criteria that consider +the implications of an edit on related facts. +Using these criteria, we then construct R IPPLE- +EDITS, a diagnostic benchmark of 5K factual +edits, capturing various types of ripple effects. +We evaluate prominent editing methods on +RIPPLEEDITS, showing that they fail to introduce +consistent changes in the model’s knowledge. +In addition, we find that a simple in-context +editing baseline obtains the best scores on our +benchmark, suggesting a promising research +direction for model editing. 1 +1 Introduction +Modern language models (LMs) capture a large +volume of factual knowledge in their parame- +ters, which can be effectively utilized in down- +stream tasks (Petroni et al., 2019; Roberts et al., +2020; Shin et al., 2020; Razniewski et al., 2021; +Heinzerling and Inui, 2021; Kadavath et al., 2022; +Cohen et al., 2023). However, factual beliefs cap- +tured by the model may be incorrect or become +∗Work done at Google DeepMind. +1We release R IPPLEEDITS and our code at https:// +github.com/edenbiran/RippleEdits. +outdated over time, potentially affecting the mod- +el’s performance on downstream tasks, its reli- +ability, and its usability (Dhingra et al., 2022; +Lazaridou et al., 2021; Jang et al., 2022). +This limitation has prompted research on +knowledge editing (KE) methods, which modify +LMs to fix their factual errors (we provide a for- +mal definition in §2). Knowledge editing work +has focused on applying factual updates to LMs. +Given an entity-relation-object triplet (e,r,o ) rep- +resenting a fact (e.g., ‘‘Lionel Messi plays for the +Inter Miami team’’ ), recent work proposed vari- +ous methods (Mitchell et al., 2022; Meng et al., +2022, 2023; Hernandez et al., 2023b; Si et al., +2023) to inject this fact into the parameters of a +given LM, while ‘‘overriding’’ beliefs the model +might have on e and r (e.g., that Messi plays for +Paris Saint-Germain). +A key question with KE is how to evaluate +the success of such editing operations. The most +basic ‘‘sanity-check’’ is that the model correctly +completes (e,r, ?), as well as other paraphrases +of this task, with o. However, this is not enough +as an evaluation, since one needs to check that +the model did not distort other facts. Indeed, +the standard evaluation protocol (Mitchell et al., +2022; Meng et al., 2022, 2023) for KE focuses on +these two aspects of correctly completing various +paraphrases of the new fact, as well as ensuring +that other unrelated facts have not been changed. +In this work, we argue that to evaluate model +edits, one should go beyond the single fact that was +edited and check that other facts that are logically +derived from the edit were also changed accord- +ingly. For example, ifz is the mother ofe, then the +children of z are the siblings of e. Consequently, +once we modify the belief of a certain model that +z → z′is the mother of e, then we should also +ensure that the model’s belief regarding the sib- +lings of e is also correct. Figure 1 illustrates an- +other example, where editing the Team for which +Lionel Messiplays modifies other related facts, +such as his country of residence, while other facts +283 +Transactions of the Association for Computational Linguistics, vol. 12, pp. 283–298, 2024. https://doi.org/10.1162/tacl a 00643 +Action Editor: Jing Jiang. Submission batch: 8/2023; Revision batch: 11/2023; Published 3/2024. +c© 2024 Association for Computational Linguistics. Distributed under a CC-BY 4.0 license. +Figure 1: Illustration of the evaluation scope of +RIPPLEEDITS, compared to existing knowledge editing +benchmarks. For a given factual edit, we consider the +‘‘ripple effect’’ of the edit on the model’s knowledge. +should be retained. We refer to such changes that +are implied by a factual edit as ripple effects. +To account for ripple effects in the evaluation of +factual edits, we propose six concrete evaluation +criteria (see §3, Figure 2), for testing which facts +other than the edit itself should be modified or +retained post-editing. Our tests evaluate how well +the model integrates the edit with the rest of its +knowledge, through queries that involve logical +reasoning, complex composition of facts with the +edit as an intermediate step, subject aliasing, and +specificity across relations. +Building upon these criteria, we create +RIPPLEEDITS, a new benchmark for comprehensive +evaluation of KE of LMs (see §4). R IPPLEEDITS +includes 5K entries, each consisting of a factual +edit, along with a set of test queries that check if +the edit was successful in terms of its ripple effect. +Moreover, R IPPLEEDITS contains meta-data for +each edit, including information about the time- +stamp of the edit (i.e., recent versus old), and the +popularity of the entities (i.e., head versus tail). +We use R IPPLEEDITS to evaluate three popular +editing methods on five recent strong LMs (see +§5). We find that, even though current KE methods +are effective in modifying a particular fact, they +often fail to capture the ripple effects entailed +by that fact, and demonstrate poor performance +on most of our evaluation criteria. Moreover, +analyzing how editing performance varies across +model sizes and entity frequencies, we find that +(a) larger models handle ripple effects better, and +(b) editing frequent entities results in more logical +reasoning errors. +Last, we consider a simple in-context editing +baseline for KE that leverages the casual atten- +tion mechanism rather than explicit parametric +updates. While this method achieves the best re- +sults on our benchmark, outperforming current +parametric KE methods, there is still ample room +for improvement that calls for future research. +To conclude, our work makes multiple contri- +butions: (a) it highlights key limitations of KE +evaluation, specifically regarding ripple effects +and introduces comprehensive evaluation crite- +ria to mitigate those limitations, (b) it proposes +RIPPLEEDITS, a benchmark inspired by these cri- +teria, (c) it evaluates current methods for KE +and shows that they do not perform well on this +task, while demonstrating that in-context edit- +ing is a promising direction for KE. We release +RIPPLEEDITS and our code to facilitate future work +on KE. +2 Problem Setting +We consider editing of factual knowledge, where +facts are expressed as triplets (e,r,o ) of a sub- +ject entity e (e.g., Lionel Messi ), a relation r +(e.g., Team), and an object o (e.g., Inter Mi- +ami). We distinguish between two edit types, +based on the knowledge encoded in the model +before the edit: (a) modification of a fact that is al- +ready encoded in the model (e,r,o ) → (e,r,o ∗), +that is, updating the object o → o∗ for a given +subject e and relation r, and (b) injection of a +new fact (e,r,o ∗) that is not captured by the +model. Moreover, we note that for one-to-one +relations like Date of birth , where there is +a single object for a given subject, an injection +edit can be viewed as populating an empty object +(e,r, ∅) → (e,r,o ∗). In contrast, for one-to-many +relations, such as Sibling and Occupation, +an injection edit augments the set of objects (e,r, +284 +Figure 2: An illustration of our evaluation criteria, for an edit that simulates adding a sibling to the subject entity +Prince, shown at the top of each graph with a bold arrow and an edit sign over the Sibling relation. For +each criterion, the tested subject and target object are circles with dashed blue line and solid green line , respec- +tively, and other nodes in dotted orange line .F o r Logical Generalization (A), the additional fact that needs to +be inserted to the knowledge graph (KG) is presented with an edit sign next to the relation. We show the same +node in different colors for completeness, as the tested subject is also the object in the edit that needs to be in- +serted. For Compositionality I, II (B, C), the model needs to hop over the edit to arrive at the target. In Subject +Aliasing (D) we verify the edit also propagates to paraphrases of the input. In Preservation (E), we verify that +other targets of the edited subject-relation are preserved. In Relation Specificity, we verify other relations for the +subject are not modified. +{o1,..,o n}) → (e,r, {o1,..,o n,o∗}). Whether an +edit is viewed as a modification or injection, de- +pends on whether that information was captured +in the model before the edit. Moreover, evaluat- +ing if a specific fact (before or after an edit) is +encoded by a model is typically done by testing +if the model predicts the object for various input +queries that represent the subject and relation (see +more details in §3.2). +3 Ripple Effects of Factual Edits +We focus on evaluating the downstream effect of a +given edit, i.e., given an edit (e,r,o ) → (e,r,o ′), +we expect certain facts related to the edit to change +as well. Consider, for example, the edit shown in +Figure 1. Changing the team for which Messi plays +might also affect the league he plays in and his +country of residence. Formally, for a given model, +assume a knowledge-graph K := {(ei,r i,o i)}N +i=1 +of N factual triplets, representing the model’s +knowledge, and let δ :( e,r,o ) → (e,r,o ′) be an +edit request for K.W ed e f i n et h eripple effect of +δ on K, as the set of triplets R(δ) that the model +implicitly needs to inject, modify, or delete from +K to reflect the world state after the edit. +Notably, different edits can cause ripple effects +of varying magnitudes. For example, changing the +country of Rome from Italy to France, will entail +many follow-up changes, such as the country +in which the Colosseum is located, the language +spoken in Rome, and so forth. In contrast, updating +the siblings of Prince (Figure 2) is both more +realistic and should result in a more local effect. +We refer to the number of facts affected by a +single editδ (i.e.,|R(δ)|) as its severity. In general, +editing popular entities that appeared frequently +during training is likely to introduce more changes, +and thus, editing their properties has a higher +severity. +3.1 Evaluation Criteria +We wish to evaluate how well models capture the +ripple effects of factual edits. However, given that +ripple effects can potentially span a large number +of implied edits, we focus on evaluating modified +facts that are within a 2-hop distance from the +285 +subject or object of the edit. Concretely, for an +edit δ :( e,r,o ) → (e,r,o ∗), we evaluate the +ripple effect R(δ), via the following evaluation +criteria (examples are shown in Figure 2): +1. Logical Generalization (LG): Relations in a +knowledge graph satisfy certain logical con- +straints. For example, the relation Sibling +is symmetric and therefore if (e, Sib- +ling,o ) is true then (o, Sibling,e ) is +also true, and vice versa (Figure 2A). Like- +wise, the relation Location is transitive so +(e, Location,o ) ∧ (o, Location,z ) ⇒ +(e, Location,z ). We wish to check that +such logical implications about the subject e, +the original object o, and the new object o∗, +hold after editing. We focus and elaborate +on specific constraints in §4. +2. Compositionality I (CI):A s δ alters one +edge in a knowledge graph, we can check +the composition of this edge with other +edges. Namely, we test if the model can +compose the edited fact with other facts +about the target object. Let (o,r′,z ) and +(o∗,r′,z∗) be two facts of the same relation +about o and o∗, respectively. Also, denote +by r′′= r ◦r′the complex relation express- +ing the composition of r and r′(e.g., r′′= +Profession of sibling for r = +Sibling and r′= Profession). Then, +after the edit δ, we expect the following +change (e,r′′,z ) → (e,r′′,z∗). For example +(Figure 2B), the professions of the siblings +of Prince can be modified once a new +sibling is injected. +3. Compositionality II (CII):W et e s ti ft h e +model can compose the edited fact with facts +about a different subject e′⁄= e. Formally, +let (e′,r′,e ) be a fact about e′with e as its +object, and denote byr′′= r′◦r the complex +relation expressing the composition of r′and +r (see an example in criterion 2). After the +edit δ, the following change is expected for +the subject e′: (e′,r′′,o ) → (e′,r′′,o∗).F o r +instance (Figure 2C), changing the siblings +of Prince also modifies the siblings of +the founder of Paisley Park Records +(i.e., r′′is a complex relation expressing +‘‘siblings of the founder’’). +4. Subject Aliasing (SA): We test that editing +a fact about e induces the same edit to other +entities e′that are aliases of e, namely, (e′, +r,o ) → (e′,r,o ∗). For instance (Figure 2D), +modifying the siblings of Prince should +also modify the sibling of his alias, Prince +Roger Nelson . +5. Preservation (PV):I f r is a one-to-many +relation, then adding a new object should +not affect the other objects encoded about +e. Hence, in such cases, we expect that any +existing triplet (e,r,o ′) for an object o′⁄= o∗ +would remain following the edit. For exam- +ple (Figure 2E), after inserting the sibling +Nicholas Carminowe for Prince,t h e +fact that Tyka Nelson is also his sibling +should be retained. +6. Relation Specificity (RS): We test that facts +about e, with relations whose objects are not +influenced by o, are indeed not affected by +the edit. For example (Figure 2F), modifying +the sibling of Prince should not change his +Mother. Note that these facts complement +those evaluated by Logical Generalization. +In §4.1, we describe how we generate factual ed- +iting evaluations, based on the above criteria. +3.2 Related Work +Knowledge Editing Methods Several methods +have been proposed to edit the factual knowl- +edge encoded in a model. De Cao et al. (2021) +and Mitchell et al. (2022) suggested using hyper- +networks to update the model weights. In addition, +Meng et al. (2022, 2023) proposed to modify en- +coded facts by updating the weights of MLP lay- +ers, following recent observations that these layers +can be cast as key-value memories (Geva et al., +2021) that store factual knowledge (Dai et al., +2022). Other methods learn encodings that update +the hidden representations created during model +inference (Hernandez et al., 2023a), or augment +the input context with edits (Zhong et al., 2023; +Zheng et al., 2023). In §5.1, we discuss state-of- +the-art KE methods used in this work in greater +detail. +Separately from factual KE, recent work has +also studied how to inject new facts into a model. +Previous methods suggested unsupervised pre- +training (Roberts et al., 2020; Zhang et al., 2021), +semi-parametric methods, where external infor- +mation is added from a knowledge-base (Zhang +286 +et al., 2019; Peters et al., 2019; Lewis et al., 2020; +Zhang et al., 2022), using adapters to store knowl- +edge (Wang et al., 2021a), or extending the MLP +layers (Yao et al., 2022). +Knowledge Editing Evaluation Recently, +there has been a growing interest in KE evalua- +tion (Yao et al., 2023). The prominent benchmarks +for evaluating factual KE are the Zero-Shot Rela- +tion Extraction (zsRE) (Levy et al., 2017; De Cao +et al., 2021) and CounterFact (Meng et al., 2022). +zsRE is a question-answering dataset for relation- +specific queries, which includes human generated +paraphrases that are used to measure robustness +to semantically equivalent inputs. For example, +for the triplet ( x, Country, y), zsRE contains +queries such as ‘‘ In which country is x? ’’. Coun- +terFact offers a more challenging setting, where +edits are counterfactuals of a low probability, +such as changing the City of The Louvre +from Paris to Rome. +Evaluation in zsRE and CounterFact focuses +on three primary aspects of (a) efficacy: checking +that the model generates the target object post- +editing, (b) paraphrasing: testing robustness in +generating the target for paraphrases of the input, +and (c) specificity: verifying that facts not related +to the edit are unaffected. In addition, Counter- +Fact evaluates the generation quality of the edited +model when prompted with the edit’s subject, +measuring: consistency, i.e., similarity with sub- +jects that share the same property as the edited +object, and fluency in terms of repetitiveness of +the generated text. More broadly, previous work +evaluated to which extent LMs have beliefs (Genin +and Huber, 2022; Kassner et al., 2021; Hase et al., +2023), and Hase et al. (2023) examined if updat- +ing beliefs propagates to entailed facts, extending +the Wikidata5m dataset (Wang et al., 2021b) to +test editing specificity. +Recently, Onoe et al. (2023) introduce the task +of entity knowledge propagation, aiming to exam- +ine the extent to which models are able to reason +about emergent entities that did not appear in pre- +training. In addition, Hoelscher-Obermaier et al. +(2023) show that existing KE methods can have +unwanted side effects and suffer from low speci- +ficity. A concurrent work by Zhong et al. (2023) +introduces MQUAKE, a benchmark that tests the +ability of models to perform multi-hop reasoning +after edits. While each of these benchmarks fo- +cuses on a single consequence of editing, R IPPLE- +EDITS provides a general framework for eval- +uating various types of edit ripple effects. Last, +Gupta et al. (2023) focus on editing commonsense +knowledge and introduce MEMIT-CSKPROBE, +a dataset for semantic generalization of common- +sense edits. RIPPLEEDITS is different from MEMIT- +CSKPROBE as it evaluates editing of factual +knowledge rather than commonsense knowledge. +4T h e R IPPLEEDITS Benchmark +In this section, we describe a data generation +pipeline (§4.1) for factual edit requests and queries +for evaluating their ripple effects. Then, we apply +our pipeline to create the R IPPLEEDITS benchmark +for comprehensive KE evaluation (§4.2), and val- +idate the quality of the data ( §4.3). +4.1 Data Generation Pipeline +We describe our data generation process (illus- +trated in Figure 3), that creates KE evaluation +examples, each consisting of a factual edit request +and a set of test queries that follow our criteria. +Since the pipeline involves manual writing of tem- +plates and logical rules per relation, we restrict the +edits and test queries to a fixed set of Nrel basic +relations.2 +Step 1: Factual Triplet Collection The first +step of the pipeline (Figure 3A) is to collect facts, +from which we will later create edit requests. To +this end, we use WIKIDATA, a relational knowledge +base consisting of facts that are expressed as +triplets (e,r,o ), where e is a subject entity, r is +a relation, and o is an object. We collect triplets +of three types: +• RECENT: To create ‘‘real’’ plausible edit re- +quests, we collect triplets that were inserted +to WIKIDATA only recently, and represent rel- +atively new facts. Therefore, they can be used +to create injection edit requests for models +that were trained before these facts were in- +troduced, to simulate cases of an out-of-date +model that requires factual updates. We col- +lect such facts by randomly sampling triplets +that have been modified during a range of +250 days after July 2022. +2The full list of relations is available in our codebase, +example relations are shown in Figure 4. +287 +Figure 3: Illustration of our data generation process. We start by sampling a fact from a KG (A), here +(Bill Gates , Spouse, Melinda Gates ). Then, we generate the target triplet for the edit (B), in this case, +choosing an object (Ricciarda Cybo Malaspina ) that shares the same type as the original object. Next, we +generate test queries (C) by sampling new triplets from the KG that should be retained or modified post-editing. +Last, we utilize pre-defined templates to translate the KG triplets to natural language phrases (D). +• RANDOM: We collect triplets corresponding +to random facts, for which we will later gen- +erate modification edits (similarly to Meng +et al., 2022). These edits simulate factual ed- +its that are meant to fix incorrect model pre- +dictions (e.g., predicting that the capital of +Germany is Frankfurt). To this end, we di- +vide the entities in WIKIDATA into 10 uniform +buckets, based on the number of triplets as- +sociated with them. Intuitively, this can be +viewed as a popularity measure. Then, we +sample Nent entities from each group and +randomly choose one triplet for each entity. +• POPULAR: The two previous triplet types are +randomly sampled from the entire knowledge +base, and most of them are likely to represent +facts about tail entities (except perhaps for a +small subset in the top bucket). Such entities +are often not captured by models (Mallen +et al., 2023), and therefore not suitable for +testing modification edits. To address this, +we sample triplets from WIKIDATA with a sub- +ject that is apopular entity, namely, it appears +in one of the top-viewed pages in Wikipedia.3 +Importantly, these types of triplets allow con- +trolling for the ripple effect severity ( §3), +i.e., how models handle the ripple effects of +popular entities versus tail entities. +Step 2: Edit Generation Once we obtain factual +triplets, we turn to generate edit requests for them +(Figure 3B). For R ECENT, triplets represent new +facts that are meant to be injected to the model, +assuming that the latter was trained before these +facts were introduced to the world. Hence, for +3We extracted the entities whose corresponding +Wikipedia page was included in the top-1000 most viewed +pages in at least one month during 2020-2022. +RECENT, the target triplet for injection is the triplet +itself. +For R ANDOM and P OPULAR triplets, we create +an edit by generating a target triplet as follows. +First, for every relation r, we create a set of can- +didate object entities Or by sampling Ncand trip- +lets (e1,r,o 1),..., (eNcand,r,o Ncand ) with the +relation r, and extracting their objects Or = {o1, +...,o Ncand}. Then, for every triplet (e,r,o ) in +RANDOM and P OPULAR, we sample a target ob- +ject o′⁄= o from Or. Sampling the target object +from triplets with the same relation makes the edit +request technically consistent with the original +triplet – the target object is of the same ‘‘type’’ as +the original object (for example, a triplet with the +relation Capital will get a new object of type +City). The new triplet (e,r,o ′) will thus result +in a ‘‘fake’’ fact, since it attaches a wrong object +o′to the pair (e,r ). For example, if R ANDOM con- +tains the triplet ( France, Capital, Paris), +its edit could be ( France, Capital, London). +Step 3: Evaluation Test Generation The next +step in the pipeline is to create ripple effect evalua- +tions for the factual edits we collected (Figure 3C). +To this end, we implement the evaluation crite- +ria introduced in §3.1, and generate test queries +for each criterion. Each test query corresponds +to a triplet of subject and object entities and a +possibly complex relation, that is expected to be +true post-editing. In what follows, we provide de- +tails on our implementation, using objects from +WIKIDATA. +For an entity e, we denote by S(e) the set of +triplets in WIKIDATA in which e is the subject, and +by T (e) the set of triplets in which e is the ob- +ject. Moreover, for every relation r, we manually +define a set Dr of relations that semantically de- +pend on it. Namely, for a given subject, changing +288 +r’s target object is expected to change the target +objects for the relations Dr. For instance, the set +Dr for the relation r = Mother, includes the +relations Sibling, Sister, Brother, Aunt, +and Uncle, among others. Then, for every rela- +tion r′∈ Dr, we craft a logical rule for obtaining +the new target for that relation post-editing. For +instance, for the relation r = Sibling,w es e ta +logical rule for r′= Mother such that if (e,r,e ′) +and (e′,r′,z′) are true for entities e,e′,z′, then +(e,r′,z′) should also be true. +Given an edit (e,r,o ) → (e,r,o ∗),w eu s e Dr +to generate test queries for Logical Generaliza- +tion and Relation Specificity.F o r Logical Gener- +alization, we apply the rule corresponding to each +relation r′∈ Dr to obtain a set of test queries +(x,r′,z′) about x ∈{ e,o,o ∗}, where z′is the +target obtained from the logical rule. For Relation +Specificity, we create a test query for every triplet +in S(e) with a relation that is not in Dr (but is in +our set of Nrel relations). +To generate text queries for Compositionality +I, we iterate through S(o∗) and for each triplet +(o∗,r′,z ) ∈S (o∗), we construct a two-hop query +(e,r ◦r′,z ) about e, with z as the answer. Simi- +larly, for Compositionality II , we iterate through +T (e) and for each triplet (z,r′,e ) ∈T (e),w e +construct a two-hop query (z,r′◦ r,o∗) about z +with o∗ as the answer. For Subject Aliasing ,w e +use information maintained by W IKIDATA to cre- +ate a test query (e′,r,o ∗) for every alias e′of +e. Last, for Preservation we create test triplets +(e,r,o 1),..., (e,r,o n) that check if the model re- +tained the original objects {o1,...,o n} in addi- +tion to the new edited object o∗. +Step 4: Phrasing in Natural Language At this +point (Figure 3D), we have factual edit requests +and their corresponding test queries. To use them +as inputs to LMs, we convert them from triplet- +form to natural language (NL). To this end, we +manually craft a template NL phrase per relation +(this is feasible since we use a fixed set of rela- +tions), and use it to convert all the triplets with +this relation. For instance, the template ‘‘The +date of birth of < e> is’’ converts trip- +lets with the relation r = Date of Birth and +a subject entity e. +For the Preservation triplets generated for an +edit (e,r, {o1,...,o n}) → (e,r, {o1,...,o n,o∗}), +whereo∗ is a new object added to a set of possibly +multiple (n ≥ 0) objects, we form a single NL +RECENT RANDOM POPULAR +# of factual edits 2,000 1,000 1,000 +# of queries per edit 26.8 18.8 25.6 +# of queries per criterion 5.24 3.1 4.2 +# of LG queries 2.5 3.6 2.6 +# of CI queries 11.7 4.7 6.1 +# of CII queries 5.1 5.1 3.9 +# of SA queries 1.8 1.3 4.7 +# of PV queries 0.6 0.4 0.5 +# of RS queries 5.1 3.7 7.8 +Subject triplets count 31.7 13.3 115.2 +Subject page back-links 278.1 121.6 3934.5 +Subject page views 189.6 67.91 7376.5 +Object triplets count 192.4 46.4 39.5 +Object page back-links 18634.2 3065.0 2136.0 +Object page views 2852.4 1379.7 1176.7 +Table 1: Statistics per subset of RIPPLEEDITS, show- +ing the average of different metrics. Breakdown by +evaluation criteria shows the number of queries of +each criterion per edit. For a given subject/object +entity, triplets count is the number of W IKIDATA +facts it is associated with, page back-links is the +number of Wikipedia pages with a link to the en- +tity’s page, and page views is the recent average +daily view count of the entity’s page. +query about other objects than the edited one, e.g., +‘‘The award received by < e> which +is not < o∗> is’’ . +4.2 Data Statistics +We used our data generation pipeline to collect +edits for 2,000 R ECENT facts, 1,000 R ANDOM facts, +and 1,000 P OPULAR facts, focusing on Nrel =5 4 +basic relations for which we manually crafted NL +templates and logical rules. 4 To obtain the R AN- +DOM subset, we set Nent = 200 to sample 200 +facts from each entity group in W IKIDATA.F o r +edit generation of R ANDOM and P OPULAR,w es e t +Ncand = 100, 000. We call our diagnostic bench- +mark RIPPLEEDITS, and publicly release it to the re- +search community. Notably, R IPPLEEDITS focuses +on ripple edits and is meant to complement exist- +ing benchmarks, and so it does not include pre- +vious evaluations, such as subject specificity and +model consistency. +Statistics on R IPPLEEDITS are presented in +Table 1, showing that our generation process re- +sulted in 18-26 test queries per edit and over 3 +queries per evaluation test, on average. Moreover, +4We release the templates and rules in our codebase. +289 +Figure 4: Most frequent relations and their frequency, in each subset of R IPPLEEDITS. +POPULAR edits contain more popular subjects (as +intended), while R ECENT edits have more popu- +lar objects. Figure 4 shows the top relations and +their frequency in each subset of R IPPLEEDITS, +demonstrating the diversity of the generated facts. +4.3 Data Quality +We conducted a manual analysis to validate that +our generation pipeline produces valid test queries. +Concretely, we sampled 200 random test queries +from R IPPLEEDITS and checked the following two +requirements: (a) soundness: the triplet that repre- +sents a given test query should be semantically +correct, namely, the entity type of the object +should match the relation type and the relation +type should match the entity type of the sub- +ject. For example, queries such as ‘‘The capital +of Hilary Clinton is’’ or ‘‘The sibling of Lebron +James is Los Angeles’’ would have been disquali- +fied. (b) grammatically correct: we check that the +phrasing of the test query in natural language is +grammatical. +We found that 100% of the queries were sound +(i.e., semantically clear and correct), showing that +the data curating process was designed properly. +Furthermore, 98.5% of the queries were gram- +matically correct, while the ones which were not +contain entity representations in a non-English lan- +guage. This shows that our templates are general +enough to properly fit various entity names. +5 Experiments +We use R IPPLEEDITS to evaluate recent KE meth- +ods, and show that despite substantial progress +on existing benchmarks, current methods struggle +to introduce consistent changes to the model’s +knowledge after an edit. Moreover, a simple in- +context editing baseline that conditions the gen- +eration on the edited fact obtains better results, +while leaving ample room for improvement for +future research. +5.1 Evaluation Setting +Data To evaluate how well an editing method +handles the ripple effects resulting from editing a +given model, the data first needs to be adjusted +such that (a) only cases of successful edits are +evaluated, and (b) only test queries that the model +answered correctly pre-editing are used for evalu- +ation. Concretely, for an editing method F and a +model M, an edit request x :( e,r,o ) → (e,r,o ′) +is included in the evaluation if the following con- +ditions are met when applying F to M and x:( a ) +M successfully generates the original objects for +the test queries before applying the edit, and (b) +M successfully generates o′when queried about +e and r, namely, the edit has successfully been +applied. For example, we verify that the model +can predict the children of o′before asking about +e’s new siblings. +Editing Methods We evaluate three KE meth- +ods: MEND (Mitchell et al., 2022), ROME (Meng +et al., 2022), and MEMIT (Meng et al., 2023). +MEND trains a network that modifies gradients +to produce local edits. ROME makes rank-one +updates to the weights of the Transformer’s MLP +layers to modify specific factual associations, and +290 +Figure 5: An example modification edit from our +ICE baseline. The color code of the KG is similar +to that described in Figure 2. We prepend the prefix +‘‘Imagine that ’’ to the input prompt, as counterfactu- +als can contradict knowledge embedded in a model’s +parameters. +MEMIT is an extension of ROME that is adjusted +to editing many facts at once. +Baseline Motivated by the recent success of +LMs to learn in-context and follow instructions +(Brown et al., 2020; Ouyang et al., 2022; Liu et al., +2023), specifically for knowledge editing (Zhong +et al., 2023; Zheng et al., 2023), we experiment +with an in-context editing (ICE) baseline for fac- +tual editing. Unlike the above methods, it does +not introduce changes to the model parameters, +but rather generation is conditioned on the new +fact. Concretely, given an edit(e,r,o ) → (e,r,o ∗) +and a test query q, we use the following prompt +to obtain an answer from the model: ‘‘Imag- +ine that < o∗> would have been < Pr>’’, +where Pr is a manually-written proposition of +r, such as ‘‘The mother of < e>’’ when r = +Mother and e is the subject. An example is +depicted in Figure 5. +Models We use 4 recent auto-regressive +decoder-only LMs of different sizes: GPT-2 XL +(Radford et al., 2019) with 1.5B parameters, GPT-J +(Chen et al., 2021) with 6B parameters, LLaMA +with 7B parameters, (Touvron et al., 2023), and +GPT-NeoX with 20B parameters (Black et al., +2022). In addition, as our baseline does not +require access to the model parameters, we also +evaluate it on the closed-source model GPT-3 +RECENT RANDOM POPULAR +Edits Tests Edits Tests Edits Tests +GPT-2 853 29% 689 33% 722 71% +GPT-J 801 33% 717 34% 760 76% +GPT-NEO 989 45% 801 46% 828 86% +LLAMA 847 44% 796 49% 784 87% +GPT-3 822 55% 760 74% 665 94% +Table 2: (a) Number of edits considered in our +evaluation (i.e., that have successfully applied), +from each subset, averaged over ROME, MEMIT, +and MEND, for the models: GPT-2, GPT-J, +GPT-NEO and LL AMA, and the ICE baseline for +GPT-3. (b) Portion of queries, on average, that +were used in our evaluation. +text-davinci-003 with 175B parameters +(Brown et al., 2020). However, for the baseline +we do not include results for GPT-2 and GPT-J as +the number of testable edits for these models is +rather small (≤ 20% for each of the data subsets). +For all model-method combinations, except for +ROME with LL AMA, we use the official imple- +mentation and hyperparameters from Meng et al. +(2022). We adjust ROME to LLAMA by following +the authors’ method and codebase. Table 2 shows +the number of edits and test queries left, for every +model, after filtering out non-successful edits and +inapplicable test queries (as described above). +Evaluation Each model-method pair is evalu- +ated separately, on every subset of R IPPLEEDITS. +For each evaluation criterion, we first compute the +average accuracy over the test queries per exam- +ple, and then average over all the examples. For a +given test query, we let the model generate a max- +imum of 20 tokens. A generation is considered +successful if one of the aliases of the target ob- +ject appears in the text. In cases of multiple gold +target objects (as in Preservation), we evaluate +each target object separately and consider the gen- +eration as correct if it matches at least one object. +5.2 Results +Tables 3, 4, 5 show the evaluation results on the +RECENT,R ANDOM, and P OPULAR subsets, respec- +tively. Considering the average scores across all +subsets, we observe that existing editing meth- +ods struggle to handle the ripple effect induced +by editing facts, with low average accuracy of +38–66 across all models. This suggests that, while +291 +LG CI CII SA PV RS Avg. +GPT-2 +ROME 20.2 35.6 46.8 86.8 100 55.4 57.5 +MEMIT 21.8 30.3 46.2 92.9 100 56.8 58.0 +MEND 28.9 23.7 20.7 87.1 100 51.9 52.1 +GPT-J ROME 15.2 29.5 50.5 90.3 99.4 60.0 57.5 +MEMIT 18.0 35.0 48.1 88.4 98.6 42.2 55.0 +GPT-NEO +ROME 27.2 54.3 69.4 98.9 98.4 80.3 71.4 +ICE 48.3 29.0 62.2 100 99.4 80.7 69.9 +LLAMA ROME 16.7 47.8 50.0 93.6 97.6 59.3 60.8 +ICE 59.6 74.8 85.0 100 99.5 77.9 82.8 +GPT-3 ICE 33.3 100 91.3 100 100 73.1 82.8 +Table 3: Accuracy on the R ECENT subset, by +MEND, ROME, MEMIT, and the ICE baseline, +on GPT-2, GPT-J, GPT-NEO,L LAMA, and GPT-3. +LG CI CII SA PV RS Avg. +GPT-2 +ROME 53.6 31.6 44.4 94.9 9.9 38.9 45.5 +MEMIT 58.4 30.5 49.8 100 20.0 36.2 49.1 +MEND 62.5 16.7 14.6 91.3 17.7 30.1 38.8 +GPT-J ROME 53.8 40.8 49.9 93.8 15.2 39.4 48.8 +MEMIT 53.0 35.7 48.2 95.6 18.2 39.9 48.4 +GPT-NEO +ROME 61.6 49.4 57.1 100 30.8 50.7 58.3 +ICE 78.6 90.0 55.6 100 100 61.9 81.0 +LLAMA ROME 54.3 35.5 49.5 96.0 17.8 38.9 48.7 +ICE 71.1 73.8 80.3 100 100 69.6 82.5 +GPT-3 ICE 69.0 83.3 89.7 100 100 100 90.3 +Table 4: Accuracy on the R ANDOM subset, by +MEND, ROME, MEMIT, and the ICE baseline, +on GPT-2, GPT-J, GPT-NEO,L LAMA, and GPT-3. +KE methods demonstrate high capability in mak- +ing local updates to the model’s knowledge, these +changes are mostly applied at a surface-level with- +out propagating to other related facts. Moreover, +we observe that our ICE baseline obtains the best +overall results. Specifically, it outperforms ROME +by more than 10 points for GPT-NEO and 29 points +for LLAMA, on average across subsets. Although +GPT-3 with ICE performs best on average, the 7B +LLAMA is highly competitive, performing better +or similarly on the R ECENT and POPULAR subsets. +Next, comparing results across evaluation cri- +teria shows that some ripple effects are handled +better than others. For example, while Subject +Aliasing accuracy is consistently high ( ≥ 86.8 +across all settings), the accuracy on other crite- +ria is generally lower and varies greatly between +models, methods, and edits (e.g., Logical Gener- +alization accuracy for ROME on GPT-J is 53.8 on +LG CI CII SA PV RS Avg. +GPT-2 +ROME 5.7 46.4 21.8 100 100 18.5 48.7 +MEMIT 6.7 45.2 21.2 100 100 24.3 49.6 +MEND 25.9 10.7 5.4 100 100 21.2 43.9 +GPT-J ROME 5.5 44.1 21.0 98.6 99.0 22.3 48.4 +MEMIT 7.0 45.9 23.7 100 100 24.8 50.2 +GPT-NEO +ROME 36.4 29.4 41.6 100 100 50.8 59.7 +ICE 37.5 92.4 40.1 100 100 74.4 74.1 +LLAMA ROME 22.0 37.4 16.2 100 100 20.6 49.4 +ICE 57.2 85.1 67.6 100 100 78.0 81.3 +GPT-3 ICE 31.0 86.1 65.6 100 100 83.8 77.7 +Table 5: Accuracy on the P OPULAR subset, by +MEND, ROME, MEMIT, and the ICE baseline, +on GPT-2, GPT-J, GPT-NEO,L LAMA, and GPT-3. +Figure 6: Accuracy averaged over evaluation criteria +of ROME, as a function of the model’s number of pa- +rameters, for the following models: GPT2-M, GPT2-L, +GPT2-XL, GPT-J, LLAMA, and GPT-NEO. +the R ANDOM subset, compared to only 5.5 on the +POPULAR subset). +Results Across Model Size We analyze how +editing performance on R IPPLEEDITS is influenced +by the model size. To this end, we further evalu- +ate ROME on smaller versions of GPT-2 – with +345M (GPT2-M) and 762M (GPT2-L) parame- +ters, and plot the average accuracy over the three +subsets as a function of model size. Figure 6 +presents the results, showing that editing perfor- +mance increases with model size, with ROME +obtaining substantially higher accuracy when ap- +plied to larger models. Nevertheless, our results +(Tables 3, 4, 5) show that when using ICE, the +7B LL AMA is competitive with the much larger +GPT-3, suggesting that simply scaling the model +size may not be sufficient to fix the drawbacks of +current editing methods. +292 +MEND ROME MEMIT +Relation Specificity 34.4 37.6 39.1 +Logical Generalization 39.1 26.5 29.0 +Compositionality I 17.0 37.9 35.3 +Compositionality II 13.6 37.7 39.1 +Table 6: Accuracy of MEND, ROME, and +MEMIT, using GPT-2, averaged over the three +RIPPLEEDITS splits - RECENT,R ANDOM and POPULAR. +Figure 7: The average accuracy of GPT-2 on different +evaluation criteria in RIPPLEEDITS. Results are averaged +over editing methods (ROME, MEMIT, and MEND); +error bars indicate standard deviation. +Results Across Methods Table 6 shows the ac- +curacy of MEND, ROME, and MEMIT, on GPT-2 +across our evaluation criteria, averaged over the +three subsets. Interestingly, MEND outperforms +ROME and MEMIT in Logical Generalization , +but is worse in Compositionality I and Compo- +sitionality II , suggesting that different methods +might better capture different types of ripple +effects. +Results Across Data Splits The subsets of +RIPPLEEDITS differ in whether edited facts are coun- +terfeit or real, and in the popularity of the edited +entities. These differences allow us to control for +the edit severity, as popular entities are expected to +introduce larger ripple effects (see§3). In Figure 7, +we show the accuracy on each subset and evalua- +tion criterion, averaged over the different editing +methods. Comparing R ANDOM and P OPULAR, that +differ in the popularity of the edited entities, we +see that while Logical Generalization accuracy +is substantially higher for R ANDOM, Preservation +accuracy is higher for POPULAR. This suggests that, +although retaining correct knowledge is easier for +popular entities, modifying other facts that log- +ically follow from an edit is harder for popular +entities, which could be explained by the severity +No effect Abstaining Noise +GPT-2 ROME 27% 31% 42% +ICE 32% 27% 41% +GPT-NEO +ROME 24% 40% 36% +ICE 10% 65% 25% +LLAMA ROME 20.5% 45% 34.5% +ICE 11% 71% 18% +Table 7: Error type distribution on 200 failures +of ROME and ICE, on GPT-2, GPT-N EO,a n d +LLAMA. +of these edits (i.e., the high number of facts that +are semantically related to them). +5.3 Error Analysis +ROME versus ICE We qualitatively analyze +the effect induced by KE methods to the model’s +knowledge. To this end, for each of ROME and +our ICE baseline and each of the models GPT-2, +GPT-NEO,a n dL L AMA, we sample 200 test +queries from RIPPLEEDITS on which the model fails +post-editing. We then label these failures using +three categories: (a) no effect, for cases when the +model predicts the original object, i.e., the edit in- +troduced no ripple effect, (b) abstaining, when the +model abstains from answering by generating text +like ‘‘unknown’’ or ‘‘a mystery’’ , and (c) noise, +when the model generates an incorrect object or +unrelated text. Table 7 presents the results, show- +ing that in most cases ( ≥ 68% across all settings) +factual editing introduces erroneous changes to the +model’s knowledge rather than making no change. +Interestingly, for both GPT-N EO and LL AMA, +where editing performance is better than GPT-2, +ROME introduces more incorrect changes while +ICE causes the model to abstain from answering. +GPT-3 versus LL AMA using ICE We further +looked into the performance on the LG tests, where +applying ICE to GPT-3 is notably inferior to ICE +on LL AMA (see Tables 3, 4, 5). Specifically, we +collected responses from each of the models to 100 +random LG queries, and analyzed them using the +same categories as described above. We observed +that GPT-3 abstains from answering the query +much more often than LL AMA (49% of the cases +for GPT-3 compared to only 28% in LL AMA), +which could explain the lower performance of +ICE on GPT-3 on these queries. +293 +6 Conclusion and Discussion +We introduce the notion of ripple effects in knowl- +edge editing, suggesting that editing a particular +fact implies further updates of related facts. We +additionally propose evaluation criteria for ripple +effects and create RIPPLEEDITS, a diagnostic bench- +mark designed to evaluate how well KE methods +handle the ripple effects of various edits. We eval- +uate prominent KE methods and show that they +often fail to introduce consistent edits that capture +the ripple effects of an edit, suggesting that fu- +ture development of KE methods should consider +those effects more carefully. Last, we show that a +simple in-context editing method achieves the best +results on R IPPLEEDITS, highlighting the potential +of such editing approaches. +Notably, our benchmark covers a small fraction +of all possible ripple-edits. For example, one could +consider ripple effects that involve more than two +hops, and explore the graph structure of different +edits. In addition, while we focus on ripple effects +of single edits, future work can consider the effect +of editing multiple facts in a single batch. Finally, +it would be interesting to consider cases where +models succeed in capturing ripple-edits, and an- +alyze how these are implemented mechanistically +in the transformer architecture (Geva et al., 2023). +Limitations Our data generation pipeline relies +on information from an existing knowledge-base +(WIKIDATA in our case), which could be incom- +plete or outdated. While R IPPLEEDITS does not aim +to cover all the possible ripple-edits in W IKI- +DATA, these concerns might be a major issue +when seeking a comprehensive evaluation or con- +sidering domain-specific knowledge-bases, which +often tend to be incomplete. A possible solution +to explore in that case is to use LMs internal +knowledge instead of an external knowledge-base +(Cohen et al., 2023). +With R IPPLEEDITS focusing on the ripple effect +of edits, it does not include tests, such as para- +phrasing of the edit and subject specificity, that +evaluate the edit itself and are covered by exist- +ing benchmarks (e.g., CounterFact). In addition, +it does not verify that many other facts that are +distantly related to the edit, i.e., triplets that are +not included in the close neighbourhood of the +edit, were retained post-editing. For example, we +expect that editing the capital of France would +not affect the population of Poland, yet this is not +explicitly checked. We note that building such an +evaluation is hard, since there are many facts to +consider and it is unclear how to determine auto- +matically which triplets should and should not be +affected by a certain edit. +Acknowledgments +We thank Maor Ivgi and Gal Elidan for valu- +able feedback and constructive suggestions. This +work is supported in part by the Israeli Science +Foundation. +References +Sidney Black, Stella Biderman, Eric Hallahan, +Quentin Anthony, Leo Gao, Laurence Golding, +Horace He, Connor Leahy, Kyle McDonell, +Jason Phang, Michael Pieler, Usvsn Sai +Prashanth, Shivanshu Purohit, Laria Reynolds, +Jonathan Tow, Ben Wang, and Samuel +Weinbach. 2022. GPT-NeoX-20B: An open- +source autoregressive language model. In Pro- +ceedings of BigScience Episode #5 – Workshop +on Challenges & Perspectives in Creat- +ing Large Language Models , pages 95–136, +virtual+Dublin. Association for Computa- +tional Linguistics. https://doi.org/10 +.18653/v1/2022.bigscience-1.9 +Tom B. Brown, Benjamin Mann, Nick Ryder, +Melanie Subbiah, Jared Kaplan, Prafulla +Dhariwal, Arvind Neelakantan, Pranav Shyam, +Girish Sastry, Amanda Askell, Sandhini +Agarwal, Ariel Herbert-Voss, Gretchen +Krueger, Tom Henighan, Rewon Child, Aditya +Ramesh, Daniel M. Ziegler, Jeffrey Wu, +Clemens Winter, Christopher Hesse, Mark +Chen, Eric Sigler, Mateusz Litwin, Scott +Gray, Benjamin Chess, Jack Clark, Christopher +Berner, Sam McCandlish, Alec Radford, Ilya +Sutskever, and Dario Amodei. 2020. Language +models are few-shot learners. In Advances +in Neural Information Processing Systems +33: Annual Conference on Neural Informa- +tion Processing Systems 2020, NeurIPS 2020, +December 6–12, 2020, virtual . +Mark Chen, Jerry Tworek, Heewoo Jun, Qiming +Yuan, Henrique Ponde de Oliveira Pinto, Jared +Kaplan, Harri Edwards, Yuri Burda, Nicholas +Joseph, Greg Brockman, Alex Ray, Raul Puri, +Gretchen Krueger, Michael Petrov, Heidy +294 +Khlaaf, Girish Sastry, Pamela Mishkin, Brooke +Chan, Scott Gray, Nick Ryder, Mikhail Pavlov, +Alethea Power, Lukasz Kaiser, Mohammad +Bavarian, Clemens Winter, Philippe Tillet, +Felipe Petroski Such, Dave Cummings, Matthias +Plappert, Fotios Chantzis, Elizabeth Barnes, +Ariel Herbert-Voss, William Hebgen Guss, +Alex Nichol, Alex Paino, Nikolas Tezak, Jie +Tang, Igor Babuschkin, Suchir Balaji, Shantanu +Jain, William Saunders, Christopher Hesse, +Andrew N. Carr, Jan Leike, Josh Achiam, Vedant +Misra, Evan Morikawa, Alec Radford, Matthew +Knight, Miles Brundage, Mira Murati, Katie +Mayer, Peter Welinder, Bob McGrew, Dario +Amodei, Sam McCandlish, Ilya Sutskever, and +Wojciech Zaremba. 2021. Evaluating large lan- +guage models trained on code. ArXiv preprint , +abs/2107.03374. https://arxiv.org/abs +/2107.03374 +Roi Cohen, Mor Geva, Jonathan Berant, +and Amir Globerson. 2023. Crawling the +internal knowledge-base of language models. In +Findings of the Association for Computational +Linguistics: EACL 2023 , pages 1856–1869, +Dubrovnik, Croatia. Association for Computa- +tional Linguistics. https://doi.org/10 +.18653/v1/2023.findings-eacl.139 +Damai Dai, Li Dong, Yaru Hao, Zhifang Sui, +Baobao Chang, and Furu Wei. 2022. Knowl- +edge neurons in pretrained transformers. In +Proceedings of the 60th Annual Meeting of +the Association for Computational Linguistics +(Volume 1: Long Papers) , pages 8493–8502, +Dublin, Ireland. Association for Computa- +tional Linguistics. https://doi.org/10 +.18653/v1/2022.acl-long.581 +Nicola De Cao, Wilker Aziz, and Ivan Titov. 2021. +Editing factual knowledge in language models. +In Proceedings of the 2021 Conference on Em- +pirical Methods in Natural Language Process- +ing, pages 6491–6506, Online and Punta Cana, +Dominican Republic. Association for Compu- +tational Linguistics. https://doi.org/10 +.18653/v1/2021.emnlp-main.522 +Bhuwan Dhingra, Jeremy R. Cole, Julian Martin +Eisenschlos, Daniel Gillick, Jacob Eisenstein, +and William W. Cohen. 2022. Time-aware lan- +guage models as temporal knowledge bases. +Transactions of the Association for Compu- +tational Linguistics , 10:257–273. https:// +doi.org/10.1162/tacla 00459 +Konstantin Genin and Franz Huber. 2022. For- +mal representations of belief. In Edward N. +Zalta and Uri Nodelman, editors, The Stan- +ford Encyclopedia of Philosophy , Fall 2022 +edition. Metaphysics Research Lab, Stanford +University. +Mor Geva, Jasmijn Bastings, Katja Filippova, +and Amir Globerson. 2023. Dissecting recall of +factual associations in auto-regressive language +models. arXiv preprint arXiv:2304.14767 . +https://doi.org/10.18653/v1/2023 +.emnlp-main.751 +Mor Geva, Roei Schuster, Jonathan Berant, and +Omer Levy. 2021. Transformer feed-forward +layers are key-value memories. In Proceed- +ings of the 2021 Conference on Empirical +Methods in Natural Language Processing , +pages 5484–5495, Online and Punta Cana, +Dominican Republic. Association for Compu- +tational Linguistics. https://doi.org/10 +.18653/v1/2021.emnlp-main.446 +Anshita Gupta, Debanjan Mondal, Akshay +Krishna Sheshadri, Wenlong Zhao, Xiang +Lorraine Li, Sarah Wiegreffe, and Niket +Tandon. 2023. Editing commonsense knowl- +edge in gpt. https://arxiv.org/abs +/2305.14956 +Peter Hase, Mona Diab, Asli Celikyilmaz, Xian +Li, Zornitsa Kozareva, Veselin Stoyanov, +Mohit Bansal, and Srinivasan Iyer. 2023. +Methods for measuring, updating, and visu- +alizing factual beliefs in language models. +In Proceedings of the 17th Conference of +the European Chapter of the Association for +Computational Linguistics , pages 2714–2731, +Dubrovnik, Croatia. Association for Computa- +tional Linguistics. https://doi.org/10 +.18653/v1/2023.eacl-main.199 +Benjamin Heinzerling and Kentaro Inui. 2021. +Language models as knowledge bases: On +entity representations, storage capacity, and +paraphrased queries. In Proceedings of the +16th Conference of the European Chapter +of the Association for Computational Lin- +guistics: Main Volume , pages 1772–1791, +Online. Association for Computational Linguis- +tics. https://doi.org/10.18653/v1 +/2021.eacl-main.153 +295 +Evan Hernandez, Belinda Z. Li, and Jacob +Andreas. 2023a. Inspecting and editing knowl- +edge representations in language models. +https://arxiv.org/abs/2304.00740 +Evan Hernandez, Belinda Z. Li, and Jacob +Andreas. 2023b. Measuring and manipulating +knowledge representations in language models. +ArXiv preprint, abs/2304.00740. +Jason Hoelscher-Obermaier, Julia Persson, Esben +Kran, Ioannis Konstas, and Fazl Barez. 2023. +Detecting edit failures in large language mod- +els: An improved specificity benchmark. In +Findings of the Association for Computational +Linguistics: ACL 2023 , pages 11548–11559, +Toronto, Canada. Association for Computa- +tional Linguistics. https://doi.org/10 +.18653/v1/2023.findings-acl.733 +Joel Jang, Seonghyeon Ye, Sohee Yang, Joongbo +Shin, Janghoon Han, Gyeonghun Kim, +Stanley Jungkyu Choi, and Minjoon Seo. 2022. +Towards continual knowledge learning of lan- +guage models. In The Tenth International +Conference on Learning Representations, ICLR +2022, Virtual Event, April 25-29, 2022 . +OpenReview.net. +Saurav Kadavath, Tom Conerly, Amanda Askell, +Tom Henighan, Dawn Drain, Ethan Perez, +Nicholas Schiefer, Zac Hatfield Dodds, Nova +DasSarma, Eli Tran-Johnson, Scott Johnston, +Sheer El-Showk, Andy Jones, Nelson Elhage, +Tristan Hume, Anna Chen, Yuntao Bai, Sam +Bowman, Stanislav Fort, Deep Ganguli, Danny +Hernandez, Josh Jacobson, Jackson Kernion, +Shauna Kravec, Liane Lovitt, Kamal Ndousse, +Catherine Olsson, Sam Ringer, Dario Amodei, +Tom Brown, Jack Clark, Nicholas Joseph, +Ben Mann, Sam McCandlish, Chris Olah, +and Jared Kaplan. 2022. Language mod- +els (mostly) know what they know. ArXiv +preprint, abs/2207.05221. https://arxiv +.org/abs/2207.05221 +Nora Kassner, Oyvind Tafjord, Hinrich Sch ¨utze, +and Peter Clark. 2021. BeliefBank: Adding +memory to a pre-trained language model for +a systematic notion of belief. In Proceed- +ings of the 2021 Conference on Empirical +Methods in Natural Language Processing , +pages 8849–8861, Online and Punta Cana, +Dominican Republic. Association for Compu- +tational Linguistics. https://doi.org/10 +.18653/v1/2021.emnlp-main.697 +Angeliki Lazaridou, Adhiguna Kuncoro, Elena +Gribovskaya, Devang Agrawal, Adam Liska, +Tayfun Terzi, Mai Gimenez, Cyprien de +Masson d’Autume, Tom ´as Kocisk ´y, Sebastian +Ruder, Dani Yogatama, Kris Cao, Susannah +Young, and Phil Blunsom. 2021. Mind the +gap: Assessing temporal generalization in neu- +ral language models. In Advances in Neural +Information Processing Systems 34: Annual +Conference on Neural Information Processing +Systems 2021, NeurIPS 2021, December 6-14, +2021, virtual, pages 29348–29363. +Omer Levy, Minjoon Seo, Eunsol Choi, and Luke +Zettlemoyer. 2017. Zero-shot relation extrac- +tion via reading comprehension. InProceedings +of the 21st Conference on Computational +Natural Language Learning (CoNLL 2017) , +pages 333–342, Vancouver, Canada. Associa- +tion for Computational Linguistics. https:// +doi.org/10.18653/v1/K17-1034 +Patrick S. H. Lewis, Ethan Perez, Aleksandra +Piktus, Fabio Petroni, Vladimir Karpukhin, +Naman Goyal, Heinrich K ¨uttler, Mike Lewis, +Wen-tau Yih, Tim Rockt ¨aschel, Sebastian +Riedel, and Douwe Kiela. 2020. Retrieval- +augmented generation for knowledge-intensive +NLP tasks. In Advances in Neural Information +Processing Systems 33: Annual Conference on +Neural Information Processing Systems 2020, +NeurIPS 2020, December 6-12, 2020, virtual . +Pengfei Liu, Weizhe Yuan, Jinlan Fu, Zhengbao +Jiang, Hiroaki Hayashi, and Graham Neubig. +2023. Pre-train, prompt, and predict: A sys- +tematic survey of prompting methods in natural +language processing. ACM Computing Surveys, +55(9):1–35. https://doi.org/10.1145 +/3560815 +Alex Mallen, Akari Asai, Victor Zhong, +Rajarshi Das, Daniel Khashabi, and Hannaneh +Hajishirzi. 2023. When not to trust lan- +guage models: Investigating effectiveness of +parametric and non-parametric memories. In +Proceedings of the 61st Annual Meeting of +the Association for Computational Linguistics +(Volume 1: Long Papers) , pages 9802–9822, +296 +Toronto, Canada. Association for Computa- +tional Linguistics. https://doi.org/10 +.18653/v1/2023.acl-long.546 +Kevin Meng, David Bau, Alex Andonian, and +Yonatan Belinkov. 2022. Locating and edit- +ing factual associations in gpt. Advances +in Neural Information Processing Systems , +35:17359–17372. +Kevin Meng, Arnab Sen Sharma, Alex J. +Andonian, Yonatan Belinkov, and David Bau. +2023. Mass-editing memory in a transformer. +In The Eleventh International Conference on +Learning Representations. +Eric Mitchell, Charles Lin, Antoine Bosselut, +Chelsea Finn, and Christopher D. Manning. +2022. Fast model editing at scale. In The Tenth +International Conference on Learning Repre- +sentations, ICLR 2022, Virtual Event, April +25-29, 2022. OpenReview.net. +Yasumasa Onoe, Michael Zhang, Shankar +Padmanabhan, Greg Durrett, and Eunsol +Choi. 2023. Can LMs learn new entities +from descriptions? Challenges in propagat- +ing injected knowledge. In Proceedings of +the 61st Annual Meeting of the Associa- +tion for Computational Linguistics (Volume 1: +Long Papers) , pages 5469–5485, Toronto, +Canada. Association for Computational Lin- +guistics. https://doi.org/10.18653 +/v1/2023.acl-long.300 +Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, +Carroll L. Wainwright, Pamela Mishkin, Chong +Zhang, Sandhini Agarwal, Katarina Slama, +Alex Ray, John Schulman, Jacob Hilton, Fraser +Kelton, Luke Miller, Maddie Simens, Amanda +Askell, Peter Welinder, Paul Christiano, +Jan Leike, and Ryan Lowe. 2022. Training +language models to follow instructions with hu- +man feedback. https://arxiv.org/abs +/2203.02155 +Matthew E. Peters, Mark Neumann, Robert Logan, +Roy Schwartz, Vidur Joshi, Sameer Singh, and +Noah A. Smith. 2019. Knowledge enhanced +contextual word representations. In Proceed- +ings of the 2019 Conference on Empirical +Methods in Natural Language Processing and +the 9th International Joint Conference on Nat- +ural Language Processing (EMNLP-IJCNLP) , +pages 43–54, Hong Kong, China. Associa- +tion for Computational Linguistics. https:// +doi.org/10.18653/v1/D19-1005 +Fabio Petroni, Tim Rockt¨aschel, Sebastian Riedel, +Patrick Lewis, Anton Bakhtin, Yuxiang Wu, +and Alexander Miller. 2019. Language models +as knowledge bases? InProceedings of the 2019 +Conference on Empirical Methods in Natural +Language Processing and the 9th International +Joint Conference on Natural Language Pro- +cessing (EMNLP-IJCNLP) , pages 2463–2473, +Hong Kong, China. Association for Computa- +tional Linguistics. https://doi.org/10 +.18653/v1/D19-1250 +Alec Radford, Jeffrey Wu, Rewon Child, David +Luan, Dario Amodei, and Ilya Sutskever. 2019. +Language models are unsupervised multitask +learners. OpenAI blog, 1(8):9. +Simon Razniewski, Andrew Yates, Nora Kassner, +and Gerhard Weikum. 2021. Language mod- +els as or for knowledge bases. ArXiv preprint , +abs/2110.04888. https://arxiv.org/abs +/2110.04888 +Adam Roberts, Colin Raffel, and Noam Shazeer. +2020. How much knowledge can you pack +into the parameters of a language model? +In Proceedings of the 2020 Conference on +Empirical Methods in Natural Language +Processing (EMNLP) , pages 5418–5426, On- +line. Association for Computational Linguis- +tics. https://doi.org/10.18653/v1 +/2020.emnlp-main.437 +Taylor Shin, Yasaman Razeghi, Robert L. Logan +IV, Eric Wallace, and Sameer Singh. 2020. +AutoPrompt: Eliciting knowledge from lan- +guage models with automatically generated +prompts. In Proceedings of the 2020 Confer- +ence on Empirical Methods in Natural Lan- +guage Processing (EMNLP), pages 4222–4235, +Online. Association for Computational Linguis- +tics. https://doi.org/10.18653/v1 +/2020.emnlp-main.346 +Chenglei Si, Zhe Gan, Zhengyuan Yang, +Shuohang Wang, Jianfeng Wang, Jordan Lee +Boyd-Graber, and Lijuan Wang. 2023. Prompt- +ing GPT-3 to be reliable. In The Eleventh +International Conference on Learning Repre- +sentations. +Hugo Touvron, Thibaut Lavril, Gautier Izacard, +Xavier Martinet, Marie-Anne Lachaux, +297 +Timoth´ee Lacroix, Baptiste Rozi `ere, Naman +Goyal, Eric Hambro, Faisal Azhar, Aurelien +Rodriguez, Armand Joulin, Edouard Grave, and +Guillaume Lample. 2023. Llama: Open and +efficient foundation language models. ArXiv +preprint, abs/2302.13971. https://arxiv +.org/abs/2302.13971 +Ruize Wang, Duyu Tang, Nan Duan, Zhongyu +Wei, Xuanjing Huang, Jianshu Ji, Guihong +Cao, Daxin Jiang, and Ming Zhou. 2021a. +K-Adapter: Infusing knowledge into pre-trained +models with adapters. In Findings of the +Association for Computational Linguistics: +ACL-IJCNLP 2021 , pages 1405–1418, On- +line. Association for Computational Linguis- +tics. https://doi.org/10.18653/v1 +/2021.findings-acl.121 +Xiaozhi Wang, Tianyu Gao, Zhaocheng Zhu, +Zhengyan Zhang, Zhiyuan Liu, Juanzi Li, +and Jian Tang. 2021b. KEPLER: A uni- +fied model for knowledge embedding and +pre-trained language representation. Transac- +tions of the Association for Computational +Linguistics, 9:176–194. https://doi.org +/10.1162/tacl_a_00360 +Yunzhi Yao, Shaohan Huang, Li Dong, Furu +Wei, Huajun Chen, and Ningyu Zhang. +2022. Kformer: Knowledge injection in trans- +former feed-forward layers. In Natural Lan- +guage Processing and Chinese Computing , +pages 131–143, Cham. Springer International +Publishing. https://doi.org/10.1007 +/978-3-031-17120-8_11 +Yunzhi Yao, Peng Wang, Bozhong Tian, Siyuan +Cheng, Zhoubo Li, Shumin Deng, Huajun +Chen, and Ningyu Zhang. 2023. Editing large +language models: Problems, methods, and +opportunities. https://arxiv.org/abs +/2305.13172 +Ningyu Zhang, Shumin Deng, Xu Cheng, Xi Chen, +Yichi Zhang, Wei Zhang, and Huajun Chen. +2021. Drop redundant, shrink irrelevant: Se- +lective knowledge injection for language +pretraining. In Proceedings of the Thirtieth +International Joint Conference on Artifi- +cial Intelligence, IJCAI-21 , pages 4007–4014. +International Joint Conferences on Artificial In- +telligence Organization. https://doi.org +/10.24963/ijcai.2021/552 +Xikun Zhang, Antoine Bosselut, Michihiro +Yasunaga, Hongyu Ren, Percy Liang, +Christopher D. Manning, and Jure Leskovec. +2022. Greaselm: Graph reasoning enhanced +language models. In The Tenth International +Conference on Learning Representations, ICLR +2022, Virtual Event, April 25-29, 2022 . +OpenReview.net. +Zhengyan Zhang, Xu Han, Zhiyuan Liu, Xin +Jiang, Maosong Sun, and Qun Liu. 2019. +ERNIE: Enhanced language representation with +informative entities. In Proceedings of the +57th Annual Meeting of the Association for +Computational Linguistics , pages 1441–1451, +Florence, Italy. Association for Computa- +tional Linguistics. https://doi.org/10 +.18653/v1/P19-1139 +Ce Zheng, Lei Li, Qingxiu Dong, Yuxuan Fan, +Zhiyong Wu, Jingjing Xu, and Baobao Chang. +2023. Can we edit factual knowledge by +in-context learning? https://doi.org/10 +.18653/v1/2023.emnlp-main.296 +Zexuan Zhong, Zhengxuan Wu, Christopher D. +Manning, Christopher Potts, and Danqi Chen. +2023. Mquake: Assessing knowledge editing +in language models via multi-hop ques- +tions. https://doi.org/10.18653/v1 +/2023.emnlp-main.971 +298 \ No newline at end of file diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/protocol.md b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..b11c4a8f247fc70963e55a387073913eca83b573 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/protocol.md @@ -0,0 +1,13 @@ +# 原论文复现的解码修订 + +本批继承[原论文复现协议](../implicit-reasoning-paper-reproduction-v1/protocol.md)的两条训练配方、原始数据、初始化seed、模型、优化器、评分、预算和固定镜像。当前正式结果目录为 `results/implicit-reasoning-paper-reproduction-v2/`;第一版两次尝试完整保留。 + +## 首次尝试与必要修复 + +第一版在训练前的全池初始评价中失败,没有进行科学训练更新。作者将词表长度52,463按8对齐到52,464,产生一个没有token字符串的输出类别52463。随机初始模型在18,986条完整测试池上生成该类别,作者 tokenizer 返回 None,全文解码报错。56条小样本CUDA短训练和重载没有覆盖该情况。 + +本次只把未映射生成id解码为可打印的 ``;保留原始id,按错误答案计分。既不删除该输出类别,也不遮蔽logits,不改变生成、损失、参数、梯度或训练样本。正常token继续使用作者的解码。新增回归测试覆盖真实52,463长度tokenizer及这个补齐类别。 + +使用相同固定镜像,先对全部18,986条测试池执行训练前评价、完整模型batch1024的两次FP16更新、保存、最终评价及新进程重载。此验证通过后,另立冻结源码并提交两个百万迭代任务;不覆盖v1失败记录和冻结源,不把工程重试计为新世界或科学重复。 + +来源、原始代码、PDF、依赖锁和镜像构建证据继续保存在v1材料目录;修订后的来源为本目录 `source/`,冻结配置和执行锁保存在本目录。W&B组为 `implicit-reasoning-paper-reproduction-v2`。 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/smoke-config.json b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/smoke-config.json new file mode 100644 index 0000000000000000000000000000000000000000..a119bff865df62f1bf305636fad700e63c4dd377 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/smoke-config.json @@ -0,0 +1,34 @@ +{ + "module": "paper_reproduction", + "source_root": "/ossfs/workspace/llm-memory-editability", + "results_root": "/ossfs/workspace/llm-memory-editability/results/implicit-reasoning-paper-validation-v2", + "specs": [ + { + "name": "author-fullpool-smoke", + "arm": "ii_plus_id", + "seed": 42, + "max_steps": 2, + "save_steps": 2, + "save_step_dense": -1, + "save_step_dense_interval": 2000, + "log_steps": 1, + "dataset": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-smoke-v2", + "data_file": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reproduction-v1/data-audit.json", + "data_files": { + "test.json": "3d8d526e3efddc2000d876a21eebc60979541868149343ce4df15c46bf243d6c", + "train.json": "4f8ed3097b49bb7b7fa1bd899bb6382224009f2175385095e7020b36f3fc732f", + "valid.json": "d631cd092cfc5f57a5e51a2f2bb7091935b892dedfddfb33e23e1d6bfb1ccb0d", + "vocab.json": "51f3a0975cf006a0d050600701eb7efc44158b42b68abb0ab85a6647a366620b" + }, + "tokenizer": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2", + "reference_model": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2", + "world_sha256": "554a9a479f6e528bef1ff5c7586f4a67f6683dd039e401d8087ccdcdd1086b14", + "paper": "Ye et al., NeurIPS 2025", + "original_experiment": "Section 2.3 / Figure 3", + "data_seed": 42, + "paper_data_commit": "d024e6bf353d167a8a140204bfa26b342ab1e824", + "author_training_commit": "734ca654ec7a71dd6737d640407fac14491d538c", + "tracking_group": "implicit-reasoning-paper-validation-v2" + } + ] +} diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/configs/experiment-tracking-defaults.json b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/configs/experiment-tracking-defaults.json new file mode 100644 index 0000000000000000000000000000000000000000..92273f717dfdee8e79a02a1a3fd47f874f8435f8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/configs/implicit-reasoning-paper-reproduction-v2.json b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/configs/implicit-reasoning-paper-reproduction-v2.json new file mode 100644 index 0000000000000000000000000000000000000000..8a8208c17e9afc41bef6660e50f8820bf1540be8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/configs/implicit-reasoning-paper-reproduction-v2.json @@ -0,0 +1,82 @@ +{ + "batch": "implicit-reasoning-paper-reproduction-v2", + "module": "paper_reproduction", + "gpus": [ + 0, + 1 + ], + "runtime": { + "docker_context": "lm-memory", + "docker_host": "unix:///run/docker-lm-memory/docker.sock", + "image": "sha256:24c345d3a3690bf481a4be1832078c1ad4cfd3637073237ab259a145cf95aa6c", + "python": "/opt/conda/bin/python", + "cpus": 4, + "memory": "16g", + "env": { + "PYTHONHASHSEED": "0", + "HF_HUB_OFFLINE": "1", + "TRANSFORMERS_OFFLINE": "1" + } + }, + "additional_sources": [ + "tests/test_paper_reproduction.py" + ], + "specs": [ + { + "name": "only_ii-seed42", + "arm": "only_ii", + "seed": 42, + "max_steps": 1000000, + "save_steps": 50000, + "save_step_dense": 40000, + "save_step_dense_interval": 2000, + "log_steps": 100, + "dataset": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reproduction-v1/only_ii", + "data_file": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reproduction-v1/data-audit.json", + "data_files": { + "train.json": "6f48e0bece52062f0fa9d5aae4a76438638b1607a8eae8408ee3e7bace422c4b", + "valid.json": "d631cd092cfc5f57a5e51a2f2bb7091935b892dedfddfb33e23e1d6bfb1ccb0d", + "test.json": "3d8d526e3efddc2000d876a21eebc60979541868149343ce4df15c46bf243d6c", + "vocab.json": "51f3a0975cf006a0d050600701eb7efc44158b42b68abb0ab85a6647a366620b" + }, + "tokenizer": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2", + "reference_model": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2", + "world_sha256": "554a9a479f6e528bef1ff5c7586f4a67f6683dd039e401d8087ccdcdd1086b14", + "paper": "Ye et al., NeurIPS 2025", + "original_experiment": "Section 2.3 / Figure 3", + "data_seed": 42, + "paper_data_commit": "d024e6bf353d167a8a140204bfa26b342ab1e824", + "author_training_commit": "734ca654ec7a71dd6737d640407fac14491d538c", + "tracking_group": "implicit-reasoning-paper-reproduction-v2" + }, + { + "name": "ii_plus_id-seed42", + "arm": "ii_plus_id", + "seed": 42, + "max_steps": 1000000, + "save_steps": 50000, + "save_step_dense": 40000, + "save_step_dense_interval": 2000, + "log_steps": 100, + "dataset": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reproduction-v1/ii_plus_id", + "data_file": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reproduction-v1/data-audit.json", + "data_files": { + "train.json": "fe63e765e4f9b37c033094939006f58f7c70fe40561af70c8df5a6b7790fe751", + "valid.json": "d631cd092cfc5f57a5e51a2f2bb7091935b892dedfddfb33e23e1d6bfb1ccb0d", + "test.json": "3d8d526e3efddc2000d876a21eebc60979541868149343ce4df15c46bf243d6c", + "vocab.json": "51f3a0975cf006a0d050600701eb7efc44158b42b68abb0ab85a6647a366620b" + }, + "tokenizer": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2", + "reference_model": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2", + "world_sha256": "554a9a479f6e528bef1ff5c7586f4a67f6683dd039e401d8087ccdcdd1086b14", + "paper": "Ye et al., NeurIPS 2025", + "original_experiment": "Section 2.3 / Figure 3", + "data_seed": 42, + "paper_data_commit": "d024e6bf353d167a8a140204bfa26b342ab1e824", + "author_training_commit": "734ca654ec7a71dd6737d640407fac14491d538c", + "tracking_group": "implicit-reasoning-paper-reproduction-v2" + } + ], + "retry_of": "implicit-reasoning-paper-reproduction-v1", + "retry_reason": "Both first attempts stopped at pre-training full-pool decoding of the unassigned padding vocabulary class 52463. Keep logits, architecture, training, data and seeds; make an unmapped generated id printable as an incorrect output." +} diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/scripts/execute_learning_use.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/scripts/execute_learning_use.py new file mode 100644 index 0000000000000000000000000000000000000000..7ae5cf765c29241aa8db0e741462f12835b1abc1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/scripts/execute_learning_use.py @@ -0,0 +1,364 @@ +"""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 "parent_run_dir" in spec: + parent = (PROJECT / spec["parent_run_dir"]).resolve() + spec["parent_run_dir"] = str(parent) + parent_run_sha256 = sha(parent / "run.json") + assert spec.get("parent_run_sha256", parent_run_sha256) == parent_run_sha256 + spec["parent_run_sha256"] = parent_run_sha256 + for filename in ("run.json", "sampling-plan.json", "audit.json"): + target = parent / filename + if target.exists(): + inputs[str(target)] = sha(target) + if "original_stage_a_steps" in spec: + target = parent / f"predictions-{spec['original_stage_a_steps']:07d}.json" + inputs[str(target)] = sha(target) + if "parent_checkpoint" in spec: + target = (PROJECT / spec["parent_checkpoint"]).resolve() + spec["parent_checkpoint"] = str(target) + checkpoint_sha256 = sha(target) + assert spec.get("parent_checkpoint_sha256", checkpoint_sha256) == checkpoint_sha256 + spec["parent_checkpoint_sha256"] = checkpoint_sha256 + inputs[str(target)] = checkpoint_sha256 + 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/implicit-reasoning-paper-reproduction-v2/source/scripts/run_memory_interface_next.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/scripts/run_memory_interface_next.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c8e478944e615761647dd0d1c900a86e48ae81 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c606cfd654948ec99bedce5244b7c6608a801a1d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/__main__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..860f4f8babf02fc2d6920b26bf4ac11a3e254766 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/alignment_coverage.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/alignment_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..6efacd7bf323dd87ad027292dee80a9f665032fa --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/architecture_bridge.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/architecture_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..3d611f12f7be01721c8f453b8981605455e4b585 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/architecture_bridge_toy.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/architecture_bridge_toy.py new file mode 100644 index 0000000000000000000000000000000000000000..a406337c9f1b455c1c07183ec90de18541f7d03b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_analysis.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae07fb7fccdec9430d5e69bc1b304a9fcebe914 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_branch.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c6ebef8f0f501ac43d2d94de8f4f59b954208b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_capacity.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_capacity.py new file mode 100644 index 0000000000000000000000000000000000000000..d07d84eb1c19bc5055e15255b0de00799b8713c5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_causal_paths.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_causal_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2d8963ce2c5db80362fdd38cc80e83c8415b53 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_confirmation_stats.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_confirmation_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..27d0d82cc96b250b88771946b569218a090bee50 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_context_control.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_context_control.py new file mode 100644 index 0000000000000000000000000000000000000000..26c20f349951ff08ba251e2e61c158ad8f4c0f85 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_context_gradient.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_context_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..89f78f244a71569026fd75d76ac6b10b702fed9d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_cross.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..960ef7e03dd29b834df68149d8aca7cbcd077a10 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_cross_continue.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_cross_continue.py new file mode 100644 index 0000000000000000000000000000000000000000..df0a21278c640164306e05b7465e24cc0e6d0df8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_cross_scale.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_cross_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..af5c92edca554475a9bdf9dee9b46438455b1f96 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_cross_train.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_cross_train.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5f3f45a169e643c408f1044eaa766b79a595fd --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_data.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3acf9b51a11985eb747a2c2565bc551ae803fd9b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_direction.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_direction.py new file mode 100644 index 0000000000000000000000000000000000000000..15e8d1db07bd56a73048608a8d9dfb99e5737a7a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_direction_cross.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_direction_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..27051c00db64d66676d95dc16a1351dff5d797a6 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_direction_formation.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_direction_formation.py new file mode 100644 index 0000000000000000000000000000000000000000..96a3aa141c344b0fea47995c861792eb5d95398a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_direction_refresh.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_direction_refresh.py new file mode 100644 index 0000000000000000000000000000000000000000..5f48462e2c66886ef8e483fa7e48986d075ad3fb --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_edit.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..685a33d6157d090f0afdfaa38b5c2d731eda4d0e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_followup.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..c90b76331ad0bbd37276b4a9fe14b865360e7a60 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_measure.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_measure.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf7c45f10b2be179635d21d0f3a7fde2ee6ca6c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_mechanism_causal.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_mechanism_causal.py new file mode 100644 index 0000000000000000000000000000000000000000..8ac824d1ef628725bf1ee9ca778d381516508a80 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_mechanism_causal_v2.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_mechanism_causal_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..322ecd4a965475d9878cbb14cb7a3eee131cf9ca --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_mechanism_edit.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_mechanism_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..6e51c693528d73250f62b70686f96b42b7eb9e4f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_mechanism_interventions.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_mechanism_interventions.py new file mode 100644 index 0000000000000000000000000000000000000000..4d87971e01bb7f679239d58f88ea4ac1b054eb88 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_model.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7190d562883dec0d900e7ac14e894975f76499fb --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_organization.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_organization.py new file mode 100644 index 0000000000000000000000000000000000000000..a64a674326bdc2e7202a987e0ac941b40640d912 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_organization_train.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_organization_train.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5d2bba261629aecc04944afd599bb827c634a8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_original_data.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_original_data.py new file mode 100644 index 0000000000000000000000000000000000000000..98352c46d29112ab2ac2be7212204897c13aea18 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_original_diagnostics.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_original_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..dc0de9f1aeb4e6e8a48ea33b265811985ebea4d8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_original_model.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_original_model.py new file mode 100644 index 0000000000000000000000000000000000000000..039ceaef72cf7fefa38bb094dbefbe9f7e88d651 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_original_report.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_original_report.py new file mode 100644 index 0000000000000000000000000000000000000000..8aace2494390c65045a2d379beb42695d3b84c8e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_original_train.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_original_train.py new file mode 100644 index 0000000000000000000000000000000000000000..eea8f0449758025224fd3bb37444cc7e54e7ef7c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_path_diagnostics.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_path_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..219336bcde27c897b81d6c253255dca79eb11d1c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_path_minimal.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_path_minimal.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2ed53451de1a88abe78ee5e58cb49745597c2b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_path_transfer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_path_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..0c54e9cfda468b9a153577dd716a037dde1577f1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_readout_control.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_readout_control.py new file mode 100644 index 0000000000000000000000000000000000000000..877089e7e83d985cfb9e4b5e65920b2db8312d4d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_relation_response.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_relation_response.py new file mode 100644 index 0000000000000000000000000000000000000000..2e69b15143ef5b90779481035823b06102c3b5ab --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_shortcut_confirmation.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_shortcut_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..3943eb3bac42c3c9c13d8b3c40061fc830348860 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py new file mode 100644 index 0000000000000000000000000000000000000000..8535796aba3f18178d69d214c04bc922b0dfa21d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_shortcut_control.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_shortcut_control.py new file mode 100644 index 0000000000000000000000000000000000000000..60ee531b9c2a08e1cf2cfba210a312300b93480d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_shortcut_edit.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_shortcut_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..856a9a8a4fd753c498c4b965d5c30a057bdebffd --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_shortcut_edit_v2.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_shortcut_edit_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..52dd3441331f501688eedfe95286f26462de3625 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_shortcut_matched_edit.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_shortcut_matched_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..684e672ca551a48aacb2f4bc81db94092282f4cf --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_train.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_train.py new file mode 100644 index 0000000000000000000000000000000000000000..958bf5b4de4feec20d76d07a5d28016fec584d7a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bridge_reencoding.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bridge_reencoding.py new file mode 100644 index 0000000000000000000000000000000000000000..1dbbe769879cff4d2b00a6c39164102b50d035e3 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bridge_workspace.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bridge_workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3ee68821631607b4922cfce3654cd2784d82ba --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/capacity_controls.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/capacity_controls.py new file mode 100644 index 0000000000000000000000000000000000000000..3806e6b81fda1ae9bc25fd74e38f846ddd3a456d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/capacity_scaling.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/capacity_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c152e8710de107c8fb2f4ba2275cdea5cbdcf3 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/cli.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..1aec4627fdf91a196893b3a6d47c8188da55d55b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/composition_curves.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/composition_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..13009dcfa856d01722da32842dcc3a7fe078a635 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/curve_tracking.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/curve_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..526a40aecb32ed282e9de766f3162546d80403ac --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/depth_step.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/depth_step.py new file mode 100644 index 0000000000000000000000000000000000000000..8f828c9ccea5c225dd4fc257587afe3c0ff7c6bf --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/depth_step_edit_calibration.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/depth_step_edit_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..fc14c085184dc030670f1eea92655b73d0eec7c8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/depth_step_mechanism.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/depth_step_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb78cafec65ea5b0a4031d27502f7d0c4b00e16 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/experiment_tracking.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/experiment_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..167c8e1a359008fa8b7c89642273e85c9699643e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/experiments.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/experiments.py new file mode 100644 index 0000000000000000000000000000000000000000..21513c79efc2f2e137213ca20f5444209e6d313d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_depth.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb93ea353cb12f972942a3cf658bc6593f81bb7 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_depth_bridge.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_depth_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..ca05be9fcd170cee34075ae1aa2fa0c2bcca1e2c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_depth_data.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_depth_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8696c3ffe204466f57619157a3f47739f899c6c4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_data.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..18cae2dbd6dfdd997883935619a80811eede27d0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_mechanism.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd1ad614952efa432b820d8f26f1e282657a947 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_model.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed46483cb7277c172f8848cefb9e2d085d67c0b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_same_bridge.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_same_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f3cac329831b303c1dc9ca05c270837de0614eec --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..48fa45f53e08b7da9c17a92df8eb5ba4efd8a229 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_supervision.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_supervision.py new file mode 100644 index 0000000000000000000000000000000000000000..104364e93299229e1a8216acabb046e5fae1dde4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_train.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_loop_train.py new file mode 100644 index 0000000000000000000000000000000000000000..ffee809fcc7335c7b68e3321427ffcc0342c3086 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_multihop.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_multihop.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0824b5e038658e91c3cbc5e521a316861f20a4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_multihop_data.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_multihop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d857233765485dc4bf1a210fda171628a20d9817 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_usage_data.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_usage_data.py new file mode 100644 index 0000000000000000000000000000000000000000..04e5650b0bdea1e25cfde235045efc9b14e0c769 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_usage_train.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grok_usage_train.py new file mode 100644 index 0000000000000000000000000000000000000000..8460dcf149ad8f229cc4c16783e8e7429acd0610 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grokking_dynamics_mechanism.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grokking_dynamics_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..9530969731263b69c576f12989a3610ead6036f5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grokking_reproduction.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/grokking_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f7ba958ea469d5edea6e98c9941dcc49427a6f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_data.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_data.py new file mode 100644 index 0000000000000000000000000000000000000000..b67eee718fd00d44c1de51a2821e24aa7251196b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_followup.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..89afed17153ba18880997b4089ddadb1b997f80b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_future.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_future.py new file mode 100644 index 0000000000000000000000000000000000000000..24171d0e5bc0c31f7cc4ac32af06d86dd8ec15f4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_interface.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..0135ee958b76df5e2df2aa4ea0c2c57c40f2b24a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_learning.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..78155602739f614f369304edc920dbb75b590bea --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_model.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_model.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8e5da864f18f673c829d8b68db641d728ca437 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_statistics.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..52bcc965886f86bf20041ec40ce6aa95b96a725f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_train.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/hebbian_train.py new file mode 100644 index 0000000000000000000000000000000000000000..f70905fa1648aeba1d7bad8aca55a77bbcadd72f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/independent_alignment.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/independent_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..88bc143ff025e794e6a5f1ec62e514b99563d88b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/interface_editing.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/interface_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..7065e910e82f4aa54e312af63f4f99925c4e1269 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/interface_tracking.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/interface_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d7812ba16f84199f575a2c6eb88ba64a6bf26d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/knowledge_change.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/knowledge_change.py new file mode 100644 index 0000000000000000000000000000000000000000..1481d60ac7e43d3617f38f6ca360b241dca20b70 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/latent_scaling.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/latent_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..7abd21f4255e3f7de35ecee337ed09d32da707ff --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/latent_support.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/latent_support.py new file mode 100644 index 0000000000000000000000000000000000000000..4b307c09f7a1fe633c634ae39b3a83e964675355 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_kv_learning.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_kv_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..dab5e168776aaab2d857d95f4c8a66473c24a902 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_kv_learning.py @@ -0,0 +1,153 @@ +"""Ordinary independent layers and first-round KV access in the audited GPT. + +The KV arm keeps every current-round causal key/value and additionally attends +to the same layer's first-round causal keys/values in one softmax. No cache is +carried between examples, batches, or calls. Both branches remain differentiable. +""" + +from __future__ import annotations + +import math + +import torch +from torch import nn +from torch.nn import functional as F +from transformers import GPT2Config + +from .grokking_reproduction import ReproductionGPT +from .loop_learning import architecture_manifest as base_manifest + +ARMS = ("standard", "loop_shared_kv", "loop_local") + + +class FirstRoundKVGPT(ReproductionGPT): + def __init__(self, config, repeats): + super().__init__(config, repeats) + self.disable_shared = False + self.duplicate_current = False # Engineering identity check, never a trained arm. + positions = torch.arange(config.n_positions) + causal = positions[None, :] <= positions[:, None] + self.register_buffer("shared_causal_mask", causal, persistent=False) + + def forward(self, tokens, positions=None): + if self.disable_shared: + return super().forward(tokens, positions) + batch, length = tokens.shape + config, transformer = self.config, self.transformer + x = transformer.wte(tokens) + transformer.wpe(torch.arange(length, device=tokens.device)) + x = F.dropout(x, config.embd_pdrop, self.training) + first_round = [] + for round_index in range(self.repeats): + for layer_index, block in enumerate(transformer.h): + q, k, v = block.attn.c_attn(block.ln_1(x)).split(config.n_embd, dim=2) + shape = (batch, length, config.n_head, config.n_embd // config.n_head) + q, k, v = (item.view(shape).transpose(1, 2) for item in (q, k, v)) + if round_index == 0: + first_round.append((k, v)) + y = F.scaled_dot_product_attention( + q, + k, + v, + is_causal=True, + dropout_p=config.attn_pdrop if self.training else 0.0, + ) + else: + cached_k, cached_v = ( + (k, v) if self.duplicate_current else first_round[layer_index] + ) + mask = self.shared_causal_mask[:length, :length] + y = F.scaled_dot_product_attention( + q, + torch.cat((cached_k, k), dim=2), + torch.cat((cached_v, v), dim=2), + attn_mask=torch.cat((mask, mask), dim=1), + dropout_p=config.attn_pdrop if self.training else 0.0, + ) + y = block.attn.c_proj(y.transpose(1, 2).reshape(batch, length, config.n_embd)) + x = x + F.dropout(y, config.resid_pdrop, self.training) + x = x + block.mlp(block.ln_2(x)) + x = transformer.ln_f(x) + if positions is not None: + x = x[torch.arange(batch, device=tokens.device)[:, None], positions] + return F.linear(x, transformer.wte.weight) + + +def construct(spec, device): + arm = spec["arm"] + if arm not in ARMS: + raise ValueError(f"Unknown architecture: {arm}") + base, repeats = int(spec["unique_layers"]), int(spec["repeats"]) + if base != int(spec["base_unique_blocks"]): + raise ValueError("Stored and base layer counts must agree") + if arm == "standard" and repeats != 1: + raise ValueError("The ordinary baseline executes independent layers once") + if arm != "standard" and repeats < 2: + raise ValueError("Loop comparison requires at least two rounds") + reference = int(spec["initialization_reference_layers"]) + if base < 1 or reference < base: + raise ValueError("Reference initialization must include every selected layer") + options = spec["model"] + if options["hidden_size"] % options["attention_heads"]: + raise ValueError("Hidden width must be divisible by the attention head count") + config = GPT2Config( + vocab_size=options["vocab_size"], + n_positions=options["positions"], + n_embd=options["hidden_size"], + n_head=options["attention_heads"], + n_layer=reference, + resid_pdrop=options["dropout"], + embd_pdrop=options["dropout"], + attn_pdrop=options["dropout"], + activation_function="gelu_new", + use_cache=False, + ) + torch.manual_seed(spec["initialization"]) + model = ( + FirstRoundKVGPT(config, repeats) + if arm == "loop_shared_kv" + else ReproductionGPT(config, repeats) + ) + # These are separately initialized layers of the reference, never copies. + model.transformer.h = nn.ModuleList(list(model.transformer.h)[:base]) + model.config.n_layer = base + model.loop_learning_info = { + "arm": arm, + "base_unique_blocks": base, + "logical_repeats": repeats, + "initialization_reference_layers": reference, + "initialization": int(spec["initialization"]), + "initialization_policy": "independent random reference layers; selected prefix", + "kv_access": "same-layer first round plus full current causal prefix" + if arm == "loop_shared_kv" + else "full current causal prefix", + "kv_gradient": "connected", + "kv_persistence": "one forward call only", + "kv_window": None, + "softmax_branches": "joint", + "initial_forward_equality_required": False, + } + return model.to(device) + + +def architecture_manifest(model): + result = base_manifest(model) + extra = ( + len(model.transformer.h) * (model.repeats - 1) if isinstance(model, FirstRoundKVGPT) else 0 + ) + return { + **result, + "attention_pair_multiples_per_sequence_square": result["executed_blocks"] + extra, + "cost_contract": "actual padded batches; shared attention pairs included; matmul estimate", + } + + +def extra_attention_flops(model, records, microbatch): + """Count additional dense QK and AV pairs, including padding and backward.""" + if not isinstance(model, FirstRoundKVGPT) or model.disable_shared: + return 0 + pairs = 0 + for start in range(0, len(records), microbatch): + chunk = records[start : start + microbatch] + length = math.ceil(max(len(r["encoded"]["input"]) for r in chunk) / 8) * 8 + pairs += len(chunk) * length * length + return 12 * model.config.n_embd * len(model.transformer.h) * (model.repeats - 1) * pairs diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_kv_learning_train.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_kv_learning_train.py new file mode 100644 index 0000000000000000000000000000000000000000..e72a3e082e351deee9df705920adbc9a582a2db3 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_kv_learning_train.py @@ -0,0 +1,86 @@ +"""Three-model comparison using the frozen Loop data and optimizer contract.""" + +from __future__ import annotations + +import argparse +import json +from contextlib import contextmanager +from pathlib import Path + +from . import sequential_transfer as st +from .loop_kv_learning import architecture_manifest, construct, extra_attention_flops +from .loop_learning import execution_digest +from .loop_learning_train import training_plan +from .realworld_composition_data import write_json + + +@contextmanager +def adapter(spec, out): + originals = {key: getattr(st, key) for key in ("construct", "training_plan", "update")} + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + + def build(_config, current_spec, device): + model = construct(current_spec, device) + target = out / "architecture.json" + if not target.exists(): + write_json( + target, + { + **architecture_manifest(model), + "initial_execution_sha256": execution_digest(model), + }, + ) + return model + + def update(model, optimizer, records, current_spec, device, pad): + result = originals["update"](model, optimizer, records, current_spec, device, pad) + result["estimated_matmul_training_flops"] += extra_attention_flops( + model, records, current_spec["microbatch_size"] + ) + return result + + st.construct, st.training_plan, st.update = build, training_plan, update + try: + yield + finally: + for key, value in originals.items(): + setattr(st, key, value) + + +def run(spec, out, device): + with adapter(spec, out): + return st.run(spec, out, device) + + +def audit(out, device): + spec = json.loads((Path(out) / "run.json").read_text())["spec"] + with adapter(spec, out): + return st.audit(out, device) + + +def preflight(spec, out, device): + with adapter(spec, out): + return st.preflight(spec, out, device) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path) + parser.add_argument("--run") + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--preflight", action="store_true") + parser.add_argument("--audit", action="store_true") + args = parser.parse_args() + if args.audit: + result = audit(args.out, args.device) + else: + config = json.loads(args.config.read_text()) + spec = next(row for row in config["specs"] if row["name"] == args.run) + result = (preflight if args.preflight else run)(spec, args.out, args.device) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_learning.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..c648d085b7f73069498c5dc95aa314e2a47946b1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_learning.py @@ -0,0 +1,160 @@ +"""Paired parameter-sharing interventions in the project's complete GPT-2. + +Every arm starts from the same seeded reference model. Repeating its prefix and +copying that prefix to independent blocks give exactly the same initial function +at the same executed depth. The intervention is the parameter constraint during +learning, not an extra embedding, readout, or change to the Transformer block. +""" + +from __future__ import annotations + +import copy +import hashlib + +import torch +from torch import nn +from transformers import GPT2Config + +from .grokking_reproduction import ReproductionGPT + +ARMS = ("shared", "untied", "mlp_shared", "shallow") + + +def construct(spec, device): + """Build an arm; reconstruction must use the same spec before loading state. + + ``base_unique_blocks`` selects the reference prefix and ``repeats`` its + logical unroll count. ``shallow`` executes that prefix once. ``mlp_shared`` + shares only the MLP module, leaving both LayerNorms and attention independent + at each occurrence. The input/output embedding is tied in every arm. + + All arms initialize ``initialization_reference_layers`` (default eight) + before selecting the prefix. Thus GPT-2's residual projection initialization + scale, shared prefix, embedding, and final LayerNorm do not depend on the arm + or unroll count. This is an intervention initialization, not native independent + initialization for the deeper untied model. + """ + arm = spec["arm"] + if arm not in ARMS: + raise ValueError(f"Unknown Loop learning arm: {arm}") + base = int(spec["base_unique_blocks"]) + repeats = int(spec["repeats"]) + reference = int(spec.get("initialization_reference_layers", 8)) + if base < 1 or repeats < 1 or reference < base: + raise ValueError("Need positive base/repeats and reference depth >= base depth") + options = spec["model"] + if options["hidden_size"] % options["attention_heads"]: + raise ValueError("Hidden width must be divisible by the attention head count") + config = GPT2Config( + vocab_size=options["vocab_size"], + n_positions=options.get("positions", 1024), + n_embd=options["hidden_size"], + n_head=options["attention_heads"], + n_layer=reference, + resid_pdrop=options["dropout"], + embd_pdrop=options["dropout"], + attn_pdrop=options["dropout"], + activation_function="gelu_new", + use_cache=False, + ) + torch.manual_seed(spec["initialization"]) + model = ReproductionGPT(config, repeats=1) + prefix = list(model.transformer.h)[:base] + if arm in {"shared", "shallow"}: + model.transformer.h = nn.ModuleList(prefix) + model.repeats = repeats if arm == "shared" else 1 + else: + blocks = [copy.deepcopy(block) for _ in range(repeats) for block in prefix] + if arm == "mlp_shared": + for index, block in enumerate(blocks): + block.mlp = blocks[index % base].mlp + model.transformer.h = nn.ModuleList(blocks) + model.config.n_layer = len(model.transformer.h) + model.loop_learning_info = { + "arm": arm, + "base_unique_blocks": base, + "logical_repeats": repeats, + "initialization_reference_layers": reference, + "initialization": int(spec["initialization"]), + "initialization_policy": "seeded reference prefix; identical occurrence copies", + "mlp_sharing_includes_layernorm": False, + } + return model.to(device) + + +def architecture_manifest(model): + """Count unique storage separately from repeated execution and module use.""" + blocks = list(model.transformer.h) + parameters = sum(parameter.numel() for parameter in model.parameters()) + return { + **model.loop_learning_info, + "unique_parameters": parameters, + "trainable_unique_parameters": sum( + parameter.numel() for parameter in model.parameters() if parameter.requires_grad + ), + # These dense arms execute every unique parameter in a full forward. + "active_unique_parameters": parameters, + "stored_blocks": len(blocks), + "execution_repeats": model.repeats, + "executed_blocks": len(blocks) * model.repeats, + "unique_block_modules": len({id(block) for block in blocks}), + "unique_attention_modules": len({id(block.attn) for block in blocks}), + "unique_mlp_modules": len({id(block.mlp) for block in blocks}), + "executed_block_parameter_uses": model.repeats + * sum(parameter.numel() for block in blocks for parameter in block.parameters()), + "hidden_size": model.config.n_embd, + "attention_heads": model.config.n_head, + "vocab_size": model.config.vocab_size, + "tied_input_output_embedding": True, + "flops_scope": ( + "Training matrix multiply estimate from actual padded input, readout positions, " + "and executed depth; excludes optimizer, normalization, nonlinearities, " + "evaluation and other overhead. It is not measured hardware FLOPs." + ), + } + + +def estimate_training_flops(model, executed_input_tokens, readout_positions, attention_pairs): + """Mirror realworld_composition.update's forward/backward matmul estimate. + + ``attention_pairs`` is sum(batch_size * padded_sequence_length**2) over + microbatches; ``readout_positions`` includes loss-masked padded answer slots. + Parameter sharing reduces storage, but does not reduce this executed cost. + """ + if min(executed_input_tokens, readout_positions, attention_pairs) < 0: + raise ValueError("FLOPs counters must be nonnegative") + width = model.config.n_embd + blocks = len(model.transformer.h) * model.repeats + return ( + 6 * 12 * width * width * blocks * executed_input_tokens + + 6 * width * model.config.vocab_size * readout_positions + + 12 * blocks * width * attention_pairs + ) + + +def execution_digest(model): + """Hash weights in execution order, canonicalizing the sharing convention. + + Identical digests verify identical expanded weights, not behavior on all + possible inputs. Dropout randomness and runtime numerics remain separate. + This intentionally differs from a raw state_dict checkpoint digest. + """ + digest = hashlib.sha256() + + def add(name, tensor): + value = tensor.detach().cpu().contiguous() + digest.update(f"{name}:{value.dtype}:{list(value.shape)}".encode()) + digest.update(value.view(torch.uint8).numpy().tobytes()) + + for name, parameter in model.transformer.wte.named_parameters(): + add("embedding." + name, parameter) + for name, parameter in model.transformer.wpe.named_parameters(): + add("position." + name, parameter) + for repeat in range(model.repeats): + for index, block in enumerate(model.transformer.h): + occurrence = repeat * len(model.transformer.h) + index + for name, parameter in block.named_parameters(): + add(f"occurrence.{occurrence}.{name}", parameter) + for name, parameter in model.transformer.ln_f.named_parameters(): + add("final_norm." + name, parameter) + return digest.hexdigest() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_learning_diagnostics.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_learning_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..1ff06d6d5169b6498fe571b93c9b7fef3aca92aa --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_learning_diagnostics.py @@ -0,0 +1,217 @@ +"""Local gradient geometry at the current weights of a paired Loop model. + +The caller supplies a fixed batch drawn only from training records. These +measurements describe gradients at one parameter point; they are not predictors +of held-out behavior or evidence that an observed geometry causes generalization. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import time + +import torch +from torch import nn + +from .realworld_composition import example_losses, pack + + +def _unfold(model): + """Untie every occurrence while retaining its exact current parameters.""" + expanded = copy.deepcopy(model) + expanded.transformer.h = nn.ModuleList( + [copy.deepcopy(block) for _ in range(model.repeats) for block in model.transformer.h] + ) + expanded.repeats = 1 + expanded.config.n_layer = len(expanded.transformer.h) + return expanded + + +def _gradient_vector(module): + gradients = [parameter.grad for parameter in module.parameters() if parameter.requires_grad] + if not gradients or any(gradient is None for gradient in gradients): + raise ValueError("Diagnostic modules must have nonempty, fully connected gradients") + return torch.cat([gradient.detach().reshape(-1) for gradient in gradients]).double() + + +def _gradient_geometry(vectors): + """Return Gram geometry, with undefined zero-gradient cosines as null.""" + stacked = torch.stack(vectors).double() + gram = stacked @ stacked.T + norms = gram.diag().clamp_min(0).sqrt() + denominator = norms[:, None] * norms[None, :] + cosines = gram / denominator.clamp_min(torch.finfo(gram.dtype).tiny) + norm_values = norms.cpu().tolist() + dots = gram.cpu().tolist() + cosine_values = cosines.clamp(-1, 1).cpu().tolist() + for i in range(len(vectors)): + for j in range(len(vectors)): + if not norm_values[i] or not norm_values[j]: + cosine_values[i][j] = None + summed = stacked.sum(dim=0) + sum_squared = float(summed.square().sum()) + individual_squared = float(gram.diag().sum()) + return { + "occurrence_gradient_norms": norm_values, + "gradient_dot_products": dots, + "gradient_cosines": cosine_values, + "summed_gradient_norm": sum_squared**0.5, + "summed_gradient_squared_norm": sum_squared, + "sum_individual_squared_norms": individual_squared, + "twice_pairwise_inner_product_sum": float(gram.sum() - gram.diag().sum()), + # One means zero net cross term, zero means complete cancellation; + # identical nonzero gradients give the number of occurrences. + "squared_norm_ratio": sum_squared / individual_squared if individual_squared else None, + "gradient_coordinates": stacked.shape[1], + } + + +def _gradient_reconstruction(reference, expanded): + """Compare each independent parameter with the sum over its actual aliases.""" + groups = {} + for repeat in range(reference.repeats): + for index, block in enumerate(reference.transformer.h): + occurrence = repeat * len(reference.transformer.h) + index + independent = dict(expanded.transformer.h[occurrence].named_parameters()) + for name, parameter in block.named_parameters(): + group = groups.setdefault(id(parameter), (parameter, [])) + group[1].append(independent[name]) + expanded_parameters = dict(expanded.named_parameters()) + for name, parameter in reference.named_parameters(): + if not name.startswith("transformer.h."): + groups[id(parameter)] = (parameter, [expanded_parameters[name]]) + absolute, relative, tied_count, coordinate_count = 0.0, 0.0, 0, 0 + for parameter, occurrences in groups.values(): + if not parameter.requires_grad: + continue + if parameter.grad is None or any(other.grad is None for other in occurrences): + raise ValueError("A trainable parameter has no diagnostic gradient") + expected = sum(other.grad.detach().double() for other in occurrences) + difference = parameter.grad.detach().double() - expected + absolute = max(absolute, float(difference.abs().max())) + denominator = max(float(expected.norm()), torch.finfo(torch.float64).tiny) + relative = max(relative, float(difference.norm()) / denominator) + tied_count += len(occurrences) > 1 + coordinate_count += parameter.numel() + return { + "maximum_absolute_error": absolute, + "maximum_relative_l2_error": relative, + "unique_parameter_tensors": len(groups), + "actually_tied_parameter_tensors": tied_count, + "trainable_parameter_coordinates": coordinate_count, + "interpretation": ( + "Each reference gradient equals the sum over its actual execution aliases. " + "For an untied parameter this is a one-occurrence equality." + ), + } + + +def diagnose(model, records, spec, device, pad): + """Measure current occurrence gradients without changing the source model. + + Two private model copies retain and fully unfold the source's current + weights. Both run in evaluation mode with autograd enabled, so dropout is + disabled and the loss is deterministic. No optimizer step is taken. The + original parameters, gradients, mode, and Torch RNG states are preserved. + Autocast is disabled: the diagnostic uses the model's own parameter dtype. + ``records`` must be a fixed, caller-selected training-only batch. + """ + if not records: + raise ValueError("Gradient diagnostics require a nonempty training batch") + info = model.loop_learning_info + for key in ("arm", "base_unique_blocks"): + if key in spec and spec[key] != info[key]: + raise ValueError(f"Diagnostic spec {key} differs from the actual model") + if any(not parameter.requires_grad for parameter in model.parameters()): + raise ValueError("Loop learning diagnostics expect the fully trainable model") + target = torch.device(device) + devices = [] + if target.type == "cuda": + devices = [target.index if target.index is not None else torch.cuda.current_device()] + start = time.monotonic() + with torch.random.fork_rng(devices=devices), torch.enable_grad(): + reference = copy.deepcopy(model).to(target).eval() + expanded = _unfold(model).to(target).eval() + reference.zero_grad(set_to_none=True) + expanded.zero_grad(set_to_none=True) + tokens, positions, labels = pack(records, pad, target) + with torch.autocast(target.type, enabled=False): + reference_logits = reference(tokens, positions) + reference_loss = example_losses(reference_logits, labels).mean() + reference_loss.backward() + expanded_logits = expanded(tokens, positions) + expanded_loss = example_losses(expanded_logits, labels).mean() + expanded_loss.backward() + base = info["base_unique_blocks"] + actual_blocks = [ + block for _ in range(reference.repeats) for block in reference.transformer.h + ] + groups = [] + for index in range(base): + occurrences = list(range(index, len(expanded.transformer.h), base)) + for component, attribute in (("attention", "attn"), ("mlp", "mlp")): + modules = [getattr(actual_blocks[i], attribute) for i in occurrences] + vectors = [ + _gradient_vector(getattr(expanded.transformer.h[i], attribute)) + for i in occurrences + ] + tied = len({id(module) for module in modules}) == 1 and len(modules) > 1 + shared_error = ( + float( + (_gradient_vector(modules[0]) - torch.stack(vectors).sum(dim=0)).abs().max() + ) + if tied + else None + ) + groups.append( + { + "base_block": index, + "component": component, + "executed_block_indices": occurrences, + "loop_iterations": [i // base for i in occurrences], + "actual_unique_modules": len({id(module) for module in modules}), + "actually_shared_across_occurrences": tied, + "shared_gradient_maximum_absolute_error": shared_error, + **_gradient_geometry(vectors), + } + ) + result = { + "kind": "current_weights_occurrence_gradient_geometry", + "arm": info["arm"], + "base_unique_blocks": base, + "executed_blocks": len(expanded.transformer.h), + "record_count": len(records), + "record_ids": [record.get("id") for record in records], + "encoded_records_sha256": hashlib.sha256( + json.dumps( + [record["encoded"] for record in records], sort_keys=True, separators=(",", ":") + ).encode() + ).hexdigest(), + "training_batch_selection": "fixed training-only batch supplied by the caller", + "loss_definition": "mean of per-example mean answer-and-EOS cross entropy", + "dropout_enabled": False, + "parameter_dtype": str(next(reference.parameters()).dtype), + "autocast_enabled": False, + "reference_loss": float(reference_loss.detach()), + "expanded_loss": float(expanded_loss.detach()), + "forward_maximum_absolute_error": float( + (reference_logits.detach() - expanded_logits.detach()).abs().max() + ), + "loss_absolute_error": float((reference_loss.detach() - expanded_loss.detach()).abs()), + "gradient_reconstruction": _gradient_reconstruction(reference, expanded), + "groups": groups, + "interpretation": ( + "Local derivatives at the same current weights. Attention and MLP reports " + "exclude their LayerNorm parameters; the complete gradient reconstruction " + "includes LayerNorm, embeddings and output readout. Sums for independent " + "modules describe a coordinated perturbation, not an actual shared parameter. " + "No optimizer update, held-out prediction, or causal claim about learning " + "efficiency is made by this diagnostic." + ), + } + # Reject nonfinite output rather than silently writing nonstandard JSON. + json.dumps(result, allow_nan=False) + result["diagnostic_wall_seconds"] = time.monotonic() - start + return result diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_learning_train.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_learning_train.py new file mode 100644 index 0000000000000000000000000000000000000000..19d9f5eca967aa17e9c9d7326293d748cf22ece4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/loop_learning_train.py @@ -0,0 +1,178 @@ +"""Paired Loop learning with full old-distribution replay and independent audit. + +The scoped adapter reuses the audited sequential trainer without changing any +historical implementation. Each experiment runs in its own Python process. +""" + +from __future__ import annotations + +import argparse +import json +from contextlib import contextmanager +from pathlib import Path + +from . import sequential_transfer as st +from .loop_learning import architecture_manifest, construct, execution_digest +from .realworld_composition_data import write_json + +_ORIGINAL_PLAN = st.training_plan + + +def training_plan(data, spec): + """Preserve the new-fact stream; replay the actual first-stage stream.""" + if spec["history"] != "sequential_composition": + raise ValueError("This first Loop matrix requires sequential_composition") + if spec.get("replay_source") != "full_stage_a": + raise ValueError("Declare full_stage_a replay explicitly") + records, plan = _ORIGINAL_PLAN(data, spec) + sa, sb, batch = (spec[k] for k in ("stage_a_steps", "stage_b_steps", "batch_size")) + new = spec.get("stage_b_new_per_batch", batch // 2) + old = batch - new + if batch % 2 or sb % 2 or old != batch // 2: + raise ValueError("Full replay requires an even batch, even B steps and half new facts") + if spec.get("stage_a_composition_per_batch", batch // 2) != batch // 2: + raise ValueError("First stage must balance old atoms and old compositions") + stream = plan[:sa].reshape(-1) + needed = sb * old + if needed > len(stream): + raise ValueError("Replay cannot exceed the actual first-stage stream") + plan[sa:, :old] = stream[:needed].reshape(sb, old) + return records, plan + + +def diagnostic_records(data, count=2): + """Fixed, training-only records; no held-out composition labels enter this.""" + return { + "old_atoms": [r for r in data["atoms"] if r["subset"] == "A"][:count], + "new_atoms": [r for r in data["atoms"] if r["subset"] == "B"][:count], + "old_compositions": data["train_compositions"][:count], + } + + +@contextmanager +def adapter(spec, out, diagnostics=False): + """Install process-local hooks and always restore the original functions.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + originals = { + key: getattr(st, key) for key in ("construct", "training_plan", "save_checkpoint", "update") + } + nodes = set(spec.get("diagnostic_nodes", [])) if diagnostics else set() + + def build(_config, current_spec, device): + model = construct(current_spec, device) + target = out / "architecture.json" + if not target.exists(): + write_json( + target, + { + **architecture_manifest(model), + "initial_execution_sha256": execution_digest(model), + }, + ) + return model + + def save(path, model, optimizer, step, *args): + originals["save_checkpoint"](path, model, optimizer, step, *args) + target = out / f"diagnostics-{step:07d}.json" + if step in nodes and not target.exists(): + from .loop_learning_diagnostics import diagnose + + data = json.loads(Path(spec["data_file"]).read_text()) + from transformers import GPT2TokenizerFast + + tokenizer = GPT2TokenizerFast.from_pretrained(spec["tokenizer"]) + device = next(model.parameters()).device + batches = diagnostic_records(data, spec.get("diagnostic_examples_per_role", 2)) + results = { + role: diagnose(model, records, spec, device, tokenizer.eos_token_id) + for role, records in batches.items() + } + write_json( + target, + { + "step": step, + "scope": "fixed training records; eval-mode local gradients", + "record_ids": {k: [r["id"] for r in v] for k, v in batches.items()}, + "roles": results, + }, + ) + + def update(model, optimizer, records, current_spec, device, pad): + first = next(model.parameters()) + state_step = optimizer.state.get(first, {}).get("step", 0) + step = int(state_step) + 1 + selected = step in nodes or step - 1 in nodes + before = ( + { + name: p.detach().clone() + for name, p in model.named_parameters() + if name.startswith("transformer.h.") + } + if selected + else {} + ) + result = originals["update"](model, optimizer, records, current_spec, device, pad) + if selected: + squares = {} + for name, parameter in model.named_parameters(): + if name in before: + family = ".".join(name.split(".")[:4]) + value = (parameter.detach() - before[name]).double().square().sum().item() + squares[family] = squares.get(family, 0.0) + value + write_json( + out / f"actual-update-{step:07d}.json", + { + "step": step, + "gradient_norm_before_clipping": result["gradient_norm"], + "learning_rate": optimizer.param_groups[0]["lr"], + "unique_block_update_l2": {k: v**0.5 for k, v in squares.items()}, + }, + ) + return result + + st.construct, st.training_plan = build, training_plan + st.save_checkpoint, st.update = save, update + try: + yield + finally: + for key, value in originals.items(): + setattr(st, key, value) + + +def run(spec, out, device): + with adapter(spec, out, diagnostics=True): + return st.run(spec, out, device) + + +def audit(out, device): + spec = json.loads((Path(out) / "run.json").read_text())["spec"] + with adapter(spec, out): + return st.audit(out, device) + + +def preflight(spec, out, device): + with adapter(spec, out): + return st.preflight(spec, out, device) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path) + parser.add_argument("--run") + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--preflight", action="store_true") + parser.add_argument("--audit", action="store_true") + args = parser.parse_args() + if args.audit: + result = audit(args.out, args.device) + else: + config = json.loads(args.config.read_text()) + spec = next(row for row in config["specs"] if row["name"] == args.run) + result = (preflight if args.preflight else run)(spec, args.out, args.device) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/low_rank.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/low_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..3a58bee0d460cb3ae042e17d22b7132b2035bd4b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/memory_reuse.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/memory_reuse.py new file mode 100644 index 0000000000000000000000000000000000000000..89520ed7649557ad7e4cfc2611ac85b8d9db8396 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/moe_sequential.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/moe_sequential.py new file mode 100644 index 0000000000000000000000000000000000000000..484ab496630e1e7c52561f08759173f6eecd0edc --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/moe_sequential.py @@ -0,0 +1,216 @@ +"""Sparse versus dense sequential learning, using the audited existing trainers. + +The ordinary four-layer path is unchanged, so compatible completed ordinary +runs can be reused. MoE uses the already tested whole-batch balancing update; +wide dense uses its actual FFN dimensions in the compute ledger. +""" + +from __future__ import annotations + +import argparse +import json +from contextlib import contextmanager +from pathlib import Path + +import torch + +from . import parametric_architecture as architecture +from . import parametric_architecture_train as architecture_train +from . import sequential_transfer as st +from .grok_depth import utc +from .grokking_reproduction import model_digest +from .loop_learning_train import training_plan +from .realworld_composition_data import sha256, write_json + +ARMS = ("D4", "M4", "W4") + + +def construct(config, spec, device): + arm = spec.get("architecture", "D4" if spec.get("arm") == "standard" else None) + if arm not in ARMS: + raise ValueError(f"Unknown sequential architecture: {arm}") + if spec.get("unique_layers", 4) != 4 or spec.get("repeats", 1) != 1: + raise ValueError("This comparison executes four independent layers once") + return architecture.construct(config, {**spec, "architecture": arm}, device) + + +def manifest(model): + ledger = architecture.parameter_ledger(model) + return { + **ledger, + "unique_parameters": ledger["total_parameters"], + "trainable_unique_parameters": ledger["trainable_parameters"], + "active_unique_parameters": ledger["nominal_parameters_selected_per_token"], + "hidden_size": model.config.n_embd, + "attention_heads": model.config.n_head, + "vocab_size": model.config.vocab_size, + "tied_input_output_embedding": True, + "initialization": architecture.initialization_manifest(model), + "initial_model_sha256": model_digest(model), + "scope": "same GPT-2 backbone; dense 4d, eight 2d experts top-2, wide 16d FFN", + "flops_scope": "actual padded attention/readout and valid expert tokens; 3x forward", + } + + +@contextmanager +def adapter(spec, out): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + keys = ("construct", "training_plan", "update", "save_checkpoint") + originals = {key: getattr(st, key) for key in keys} + last_update = {} + + def build(config, current_spec, device): + model = construct(config, current_spec, device) + target = out / "architecture.json" + if not target.exists(): + write_json(target, manifest(model)) + return model + + def update(model, optimizer, records, current_spec, device, pad): + if model.kind == "dense": + result = originals["update"](model, optimizer, records, current_spec, device, pad) + else: + result = architecture_train.update(model, optimizer, records, current_spec, device, pad) + last_update.clear() + last_update.update(result) + step = int(optimizer.state[next(model.parameters())]["step"]) + selected = set(current_spec.get("evaluation_nodes", [])) + selected |= { + current_spec["stage_a_steps"], + current_spec["stage_a_steps"] + current_spec["stage_b_steps"], + } + if step % current_spec.get("status_interval", 50) == 0 or step in selected: + with (out / "update-details.jsonl").open("a") as stream: + stream.write(json.dumps({"step": step, **result}, allow_nan=False) + "\n") + return result + + def save(path, model, optimizer, step, counts, counters, history, sampling): + if history and history[-1]["step"] == step and last_update: + history[-1].update( + answer_ce=last_update["loss"], + balance_loss=last_update.get("balance_loss", 0.0), + objective=last_update.get("objective", last_update["loss"]), + router=architecture_train._routing_metrics(last_update.get("router")), + ) + router = last_update.get("router", {}) + for layer, entropy in enumerate(router.get("router_entropy_per_layer", [])): + history[-1][f"router_entropy_layer_{layer}"] = entropy + for expert, value in enumerate(router["assignment_fractions"][layer]): + history[-1][f"router_fraction_layer_{layer}_expert_{expert}"] = value + write_json(out / "learning.json", history) + originals["save_checkpoint"]( + path, model, optimizer, step, counts, counters, history, sampling + ) + + st.construct, st.training_plan = build, training_plan + st.update, st.save_checkpoint = update, save + try: + yield + finally: + for key, value in originals.items(): + setattr(st, key, value) + + +def run(spec, out, device): + with adapter(spec, out): + return st.run(spec, out, device) + + +def audit(out, device): + spec = json.loads((Path(out) / "run.json").read_text())["spec"] + with adapter(spec, out): + return st.audit(out, device) + + +def preflight(spec, out, device): + with adapter(spec, out): + return st.preflight(spec, out, device) + + +def verify_reused(config, out, device): + """Read-only re-evaluation of old weights under the new ordinary builder.""" + results = [] + for entry in config["reused_runs"]: + root = Path(entry["run_dir"]) + metadata = json.loads((root / "run.json").read_text()) + spec = metadata["spec"] + if spec["arm"] != "standard": + raise ValueError("Reused baseline must have independent ordinary layers") + if any(sha256(root / name) != value for name, value in entry["files"].items()): + raise ValueError("A reused baseline artifact has changed") + if not json.loads((root / "audit.json").read_text())["passed"]: + raise ValueError("A reused baseline lacks its independent reload audit") + with adapter(spec, Path(out) / entry["name"]): + data, tokenizer, model, actual_device = st._setup(spec, device) + records, plan = training_plan(data, spec) + sampling = st.plan_manifest(records, plan, spec) + expected_sampling = json.loads((root / "sampling-plan.json").read_text()) + if sampling != expected_sampling: + raise AssertionError("Reused ordinary sample stream/exposure differs") + if model_digest(model) != metadata["initial_model_sha256"]: + raise AssertionError("Reused ordinary initial weights differ") + for filename, step in ( + ("stage-a.pt", spec["stage_a_steps"]), + ("latest.pt", spec["stage_a_steps"] + spec["stage_b_steps"]), + ): + state = torch.load(root / filename, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + if state["step"] != step or state["plan_sha256"] != sampling["plan_sha256"]: + raise AssertionError("Reused checkpoint step or sample stream differs") + metrics, predictions = st.evaluate_transfer( + model, + data, + tokenizer, + actual_device, + full=True, + autonomous=True, + batch=spec["evaluation_batch_size"], + ) + expected = json.loads((root / f"predictions-{step:07d}.json").read_text()) + history = json.loads((root / "learning.json").read_text()) + expected_metrics = next(row["metrics"] for row in history if row["step"] == step) + if predictions != expected or metrics != expected_metrics: + raise AssertionError("Reused endpoint generations/scores differ") + results.append( + { + "name": entry["name"], + "step": step, + "passed": True, + "predictions_recomputed": sum(map(len, predictions.values())), + } + ) + result = { + "passed": bool(results) and all(row["passed"] for row in results), + "nodes": results, + "old_artifacts_modified": False, + "created_utc": utc(), + } + write_json(Path(out) / "reuse-validation.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, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--preflight", action="store_true") + parser.add_argument("--audit", action="store_true") + parser.add_argument("--verify-reused", action="store_true") + args = parser.parse_args() + if args.audit: + result = audit(args.out, args.device) + else: + config = json.loads(args.config.read_text()) + if args.verify_reused: + result = verify_reused(config, args.out, args.device) + else: + spec = next(row for row in config["specs"] if row["name"] == args.run) + result = (preflight if args.preflight else run)(spec, args.out, args.device) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/multihop_scaling.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/multihop_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..64b5a3d67ef6bab20c60904e626e811876d72279 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/natural_composition_confirmation.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/natural_composition_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9608e59339683c91de69b2f1f392b93b8f0171 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/natural_composition_confirmation_v2.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/natural_composition_confirmation_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e949ff27eac75a758644d6a7ffd81f2a9477ea --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/neural.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/neural.py new file mode 100644 index 0000000000000000000000000000000000000000..ce1f02e8195f4e583817b3781b044f021a41fbfb --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/neural_data.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/neural_data.py new file mode 100644 index 0000000000000000000000000000000000000000..555b2a06a7db0805d441a3f8f89bc2100deaa72a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/neural_models.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/neural_models.py new file mode 100644 index 0000000000000000000000000000000000000000..448b3499cdce6fac7d4bcac1e60883f4c383df82 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/paper_reproduction.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/paper_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..d41519fb25f6585ecf3f10c58dde6cc8edfa2170 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/paper_reproduction.py @@ -0,0 +1,484 @@ +"""Run Ye et al. Figure 3 with the authors' notebook and training implementation.""" + +from __future__ import annotations + +import ast +import hashlib +import json +import math +import os +import random +import re +import time +from contextlib import contextmanager +from pathlib import Path + +from .experiment_tracking import read_json, write_json + +TOKEN = re.compile(r"||") + + +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 notebook_functions(notebook): + """Execute only the original function definitions; no notebook file writes.""" + import numpy as np + from tqdm.auto import tqdm + + cells = read_json(notebook)["cells"] + namespace = {"np": np, "tqdm": tqdm} + for index in (1, 3): + parsed = ast.parse("".join(cells[index]["source"])) + definitions = ast.Module( + body=[node for node in parsed.body if isinstance(node, ast.FunctionDef)], + type_ignores=[], + ) + exec(compile(definitions, f"{notebook}:cell-{index}", "exec"), namespace) + return namespace + + +def validate_data(groups, training, *, expected_id, expected_ood, expected_ii): + """Check graph truth, structural roles, held-out queries and the actual sample count.""" + id_rows, ood_rows = groups["ID Triples"], groups["OOD Triples"] + assert len(id_rows) == expected_id and len(ood_rows) == expected_ood + atomic = {} + membership = {} + for kind, rows in (("I", id_rows), ("O", ood_rows)): + for row in rows: + parts = TOKEN.findall(row["target_text"]) + assert len(parts) == 4 and parts[-1] == "" + h, relation, tail, _ = parts + key = (h, relation) + assert key not in atomic + assert row["input_text"] == h + relation + atomic[key], membership[key] = tail, kind + assert len(training["only_ii"]) == expected_ii + assert training["ii_plus_id"] == id_rows + training["only_ii"] + train_queries = {row["input_text"] for row in training["only_ii"]} + assert len(train_queries) == expected_ii + assert all(len(TOKEN.findall(row["input_text"])) == 3 for row in training["only_ii"]) + checked = 0 + for name, rows in groups.items(): + if name in {"ID Triples", "OOD Triples"}: + continue + role = "II" if name == "Train-II" else name.removeprefix("Test-") + seen = set() + for row in rows: + h, r1, r2 = TOKEN.findall(row["input_text"]) + bridge = atomic[(h, r1)] + tail = atomic[(bridge, r2)] + assert row["target_text"] == h + r1 + r2 + tail + "" + assert membership[(h, r1)] + membership[(bridge, r2)] == role + assert row["input_text"] not in seen + seen.add(row["input_text"]) + assert (row["input_text"] in train_queries) == (name == "Train-II") + checked += 1 + return {"passed": True, "atomic_truths": len(atomic), "composition_truths": checked} + + +def prepare(notebook, destination, *, seed=42, entities=2000, relations=200, degree=20): + import numpy as np + + destination = Path(destination) + if destination.exists(): + raise FileExistsError(destination) + assert os.environ.get("PYTHONHASHSEED") == "0", "Fix the authors' set iteration order" + random.seed(seed) + np.random.seed(seed) + functions = notebook_functions(notebook) + values = functions["build_base_dataset"](entities, relations, out_degree=degree) + entity_tokens, relation_tokens, id_rows, ood_rows, ii, test_ii, io, oi, oo = values + choose = functions["choose"] + # Notebook passes 7.2 * N as float, which choose() interprets as a ratio. + # Table 2 specifies 273600. Pass an integer COUNT rather than changing phi. + expected_ii = round(7.2 * len(id_rows)) + candidate_count = len(ii) + evaluation = { + "ID Triples": choose(id_rows, 3000), + "OOD Triples": choose(ood_rows, 3000), + "Test-II": choose(test_ii, 3000), + "Test-IO": choose(io, 3000), + "Test-OI": choose(oi, 3000), + "Test-OO": choose(oo, 3000), + } + ii = choose(ii, expected_ii) + evaluation["Train-II"] = choose(ii, 3000) + training = {"only_ii": ii, "ii_plus_id": id_rows + ii} + full_groups = {"ID Triples": id_rows, "OOD Triples": ood_rows, "Train-II": ii} + full_groups.update( + {name: rows for name, rows in evaluation.items() if name.startswith("Test-")} + ) + audit = validate_data( + full_groups, + training, + expected_id=round(entities * degree * 0.95), + expected_ood=round(entities * degree * 0.05), + expected_ii=expected_ii, + ) + probes = [dict(row, type=name) for name, rows in evaluation.items() for row in rows] + vocab = entity_tokens + relation_tokens + ["", "", "", "", "", ""] + for arm, rows in training.items(): + for filename, data in { + "train.json": rows, + "valid.json": evaluation["Test-OO"], + "test.json": probes, + "vocab.json": vocab, + }.items(): + write_json(destination / arm / filename, data) + write_json(destination / "atomic-truth.json", full_groups["ID Triples"] + ood_rows) + audit.update( + seed=seed, + python_hash_seed=0, + notebook_sha256=sha(notebook), + candidate_train_ii=candidate_count, + selected_train_ii=expected_ii, + training_counts={arm: len(rows) for arm, rows in training.items()}, + evaluation_counts={name: len(rows) for name, rows in evaluation.items()}, + same_ii_and_probes=True, + integer_count_fix="Paper Table 2 rather than notebook float-as-ratio sampling", + files={ + str(path.relative_to(destination)): sha(path) for path in destination.rglob("*.json") + }, + ) + write_json(destination / "data-audit.json", audit) + return audit + + +def score_predictions(rows): + groups = {} + for row in rows: + group = groups.setdefault( + row["type"], {"total": 0, "paper_correct": 0, "strict_correct": 0} + ) + group["total"] += 1 + group["paper_correct"] += row["model_output"] == row["target_text"] + group["strict_correct"] += row["strict_answer_eos"] + for group in groups.values(): + group["paper_accuracy"] = group["paper_correct"] / group["total"] + group["strict_answer_eos_accuracy"] = group["strict_correct"] / group["total"] + return groups + + +def install_author_imports(): + import sys + + # The fixed image contains the authors' two bundled packages, not stock HF GPT-2. + sys.path[:0] = [ + "/opt/paper-upstream/transformers/src", + "/opt/paper-upstream/simpletransformers", + ] + import transformers + + assert transformers.__version__ == "4.37.0.dev0" + assert str(Path(transformers.__file__)).startswith("/opt/paper-upstream/") + + +@contextmanager +def decode_unmapped_tokens(tokenizer): + """Make padded output classes printable failures without changing generation logits.""" + original = tokenizer._convert_id_to_token + + def convert(index): + token = original(index) + return token if token is not None else f"" + + tokenizer._convert_id_to_token = convert + try: + yield + finally: + tokenizer._convert_id_to_token = original + + +def predict_with_raw(model, probes, destination): + """Keep original generation/scoring and also preserve the unmodified token outputs.""" + module = model.model.module if hasattr(model.model, "module") else model.model + generate = module.generate + raw = [] + + def capture(*args, **kwargs): + result = generate(*args, **kwargs) + raw.extend(result.detach().cpu().tolist()) + return result + + module.generate = capture + try: + # Original predict() modifies its input rows in place. + original = getattr(model, "predict_original", model.predict) + with decode_unmapped_tokens(model.lm_tokenizer): + original([dict(row) for row in probes], str(destination)) + finally: + module.generate = generate + rows = read_json(Path(destination) / "all_items.json") + assert len(raw) == len(rows) + for row, ids in zip(rows, raw, strict=True): + unpadded = [token for token in ids if token != model.lm_tokenizer.pad_token_id] + expected = model.lm_tokenizer.encode(row["target_text"]) + # Stop at the answer delimiter; tokens afterwards are outside the task. + row["strict_answer_eos"] = unpadded[: len(expected)] == expected + row["raw_token_ids"] = ids + with decode_unmapped_tokens(model.lm_tokenizer): + row["raw_output"] = model.lm_tokenizer.decode(ids, skip_special_tokens=False) + write_json(Path(destination) / "raw-predictions.json", rows) + return score_predictions(rows) + + +class Observer: + """Record updates without changing the authors' optimizer, gradients or data order.""" + + def __init__(self, out, spec, training_count): + self.out, self.spec = Path(out), spec + self.started = time.monotonic() + self.evaluation_seconds = 0.0 + self.examples = self.atomics = self.compositions = 0 + self.history = [] + self.step = 0 + self.skipped_updates = 0 + self.training_count = training_count + self.latest_training = {} + self.scaler_state = None + + def after_update(self, model, step, inputs, loss, optimizer, scheduler, scaler, skipped): + self.step = step + count = len(inputs["target_ids"]) + atomic_count = int((inputs["lm_labels"][:, 2] != -100).sum().item()) + self.examples += count + self.atomics += atomic_count + self.compositions += count - atomic_count + finite_loss = float(loss.item()) + assert math.isfinite(finite_loss), f"Non-finite training loss at step {step}" + self.skipped_updates += int(skipped) + self.scaler_state = scaler.state_dict() if scaler is not None else None + self.latest_training = {"loss": finite_loss, "learning_rate": scheduler.get_last_lr()[0]} + save_steps = self.spec.get("save_steps", 50000) + dense_limit = self.spec.get("save_step_dense", 40000) + dense_interval = self.spec.get("save_step_dense_interval", 2000) + checkpoint = (save_steps > 0 and step % save_steps == 0) or ( + dense_limit > 0 and step <= dense_limit and step % dense_interval == 0 + ) + # Do not publish this step before its evaluation: the sidecar has a monotonic cursor. + if not checkpoint and (step in {1, 10} or step % self.spec.get("log_steps", 100) == 0): + self.record(step, **self.latest_training) + + def record(self, step, **values): + wall = time.monotonic() - self.started + entry = { + "step": step, + "wall_seconds": wall, + "training_seconds": wall - self.evaluation_seconds, + "examples": self.examples, + "atomic_examples": self.atomics, + "composition_examples": self.compositions, + "supervised_tokens": 2 * self.examples, + "executed_input_tokens": 10 * self.examples, + "data_epochs": self.examples / self.training_count, + "amp_skipped_updates": self.skipped_updates, + "successful_updates": step - self.skipped_updates, + **values, + } + # Evaluation at a logging step replaces that record, avoiding duplicate W&B steps. + if self.history and self.history[-1]["step"] == step: + entry = {**self.history.pop(), **entry} + self.history.append(entry) + write_json(self.out / "learning.json", self.history) + write_json(self.out / "status.json", {"state": "training", **entry}) + print(json.dumps({"step": step, "examples": self.examples, **values}), flush=True) + + +def model_args(spec, out): + return { + "reprocess_input_data": True, + "overwrite_output_dir": False, + "max_seq_length": 10, + "max_length": 10, + "max_gen_length": None, + "block_size": 10, + "train_batch_size": 1024, + "eval_batch_size": 512, + "gradient_accumulation_steps": 1, + "learning_rate": 1e-4, + "num_train_epochs": 20, + "save_eval_checkpoints": False, + "save_steps": spec.get("save_steps", 50000), + "use_multiprocessing": False, + "output_dir": str(out / "model-output"), + "manual_seed": spec["seed"], + "fp16": True, + "truncation": True, + "dataloader_num_workers": 0, + "use_multiprocessed_decoding": False, + "save_best_model": False, + "save_model_every_epoch": False, + "save_epoch_interval": 0, + "scheduler": "constant_schedule_with_warmup", + "weight_decay": 0.1, + "evaluate_during_training": True, + "predict_during_training": True, + "mlm": False, + "warmup_steps": 2000, + "max_steps": spec["max_steps"], + "n_layer": 8, + "n_inner": None, + "n_head": None, + "memory_dim": 1536, + # File locations and console verbosity only; training defaults remain intact. + "silent": True, + "cache_dir": str(out / "cache"), + "tensorboard_dir": str(out / "tensorboard"), + "no_cache": True, + } + + +def run(spec, out, device): + import numpy as np + import pandas as pd + import torch + + install_author_imports() + from simpletransformers.seq2seq import Seq2SeqModel + + out = Path(out) + assert not (out / "model-output").exists(), "No automatic restart or overwrite" + dataset = Path(spec["dataset"]) + for filename, expected in spec["data_files"].items(): + assert sha(dataset / filename) == expected + training = read_json(dataset / "train.json") + probes = read_json(dataset / "test.json") + observer = Observer(out, spec, len(training)) + + class RecordedModel(Seq2SeqModel): + def predict(self, *args, **kwargs): + # The inherited train() invokes this only at a saved checkpoint. + start = time.monotonic() + destination = Path(args[1] if len(args) > 1 else kwargs["output_dir"]) + metrics = predict_with_raw(self, probes, destination) + observer.evaluation_seconds += time.monotonic() - start + observer.record(observer.step, metrics=metrics, **observer.latest_training) + return metrics + + def save_model(self, output_dir, optimizer=None, scheduler=None, **kwargs): + super().save_model(output_dir, optimizer, scheduler, **kwargs) + torch.save( + { + "python": random.getstate(), + "numpy": np.random.get_state(), + "torch_cpu": torch.get_rng_state(), + "torch_cuda": torch.cuda.get_rng_state_all(), + "step": observer.step, + "amp_scaler": observer.scaler_state, + }, + Path(output_dir) / "rng-state.pt", + ) + + # Avoid override recursion when predict_with_raw calls the authors' predict(). + original_predict = Seq2SeqModel.predict + RecordedModel.predict_original = original_predict + model = RecordedModel( + "gpt2", + spec["reference_model"], + args=model_args(spec, out), + ddp_args={ + "local_rank": -1, + "rank": -1, + "gpu": None, + "world_size": -1, + "dist_url": "env://", + "dist_backend": "nccl", + }, + new_tokens=read_json(dataset / "vocab.json"), + init_weights=True, + ) + model.paper_observer = observer + model._move_model_to_device() + assert model.language_model.config.n_layer == 8 + assert model.language_model.config.n_embd == 768 + assert model.language_model.config.n_head == 12 + assert model.language_model.config.vocab_size == 52464 + assert not getattr(model.language_model.config, "add_recurrence", False) + metadata = { + "spec": spec, + "model": "Author GPT-2, independent 8 layers", + "tracking_group": spec.get("tracking_group", "implicit-reasoning-paper-reproduction-v1"), + "job_type": "paper-reproduction", + "tags": ["paper-reproduction", "Ye-et-al-NeurIPS-2025", "Figure-3"], + "parameters": sum(p.numel() for p in model.language_model.parameters()), + "vocab_size": 52464, + "dtype": "FP32 parameters, author FP16 AMP", + "gpu_name": torch.cuda.get_device_name(device), + "world_sha256": spec["world_sha256"], + "learning_step_unit": "author iterations; successful updates and AMP skips also recorded", + } + torch.save(model.language_model.state_dict(), out / "initial-state.pt") + metadata["initial_model_sha256"] = sha(out / "initial-state.pt") + write_json(out / "run.json", metadata) + write_json(out / "learning.json", []) + write_json(out / "resolved-model-args.json", vars(model.args)) + write_json(out / "resolved-model-config.json", model.language_model.config.to_dict()) + model.lm_tokenizer.save_pretrained(out / "tokenizer") + start = time.monotonic() + metrics = predict_with_raw(model, probes, out / "predictions-0000000") + observer.evaluation_seconds += time.monotonic() - start + observer.record(0, metrics=metrics) + steps, _ = model.train_model( + train_data=pd.DataFrame(training), + eval_data=pd.DataFrame(read_json(dataset / "valid.json")), + test_data=probes, + output_dir=str(out / "model-output"), + save_step_dense=spec.get("save_step_dense", 40000), + save_step_dense_interval=spec.get("save_step_dense_interval", 2000), + show_running_loss=False, + ) + assert steps == spec["max_steps"], (steps, spec["max_steps"]) + final = out / "model-output" / f"checkpoint-{steps}" + assert (final / "raw-predictions.json").exists(), "Final step must be a checkpoint node" + write_json(out / "complete.json", {"step": steps, "final_checkpoint": str(final)}) + write_json(out / "status.json", {"state": "awaiting_independent_reload", "step": steps}) + + +def audit(out, device): + """Fresh-process reload of authors' saved final model and the complete frozen test pool.""" + import torch + + install_author_imports() + from simpletransformers.seq2seq import Seq2SeqModel + + out = Path(out) + spec = read_json(out / "run.json")["spec"] + final = Path(read_json(out / "complete.json")["final_checkpoint"]) + model = Seq2SeqModel( + "gpt2", + str(final), + args=model_args(spec, out), + ddp_args={ + "local_rank": -1, + "rank": -1, + "gpu": None, + "world_size": -1, + "dist_url": "env://", + "dist_backend": "nccl", + }, + init_weights=False, + ) + model._move_model_to_device() + predict_with_raw(model, read_json(Path(spec["dataset"]) / "test.json"), out / "reload-audit") + written = read_json(final / "raw-predictions.json") + reloaded = read_json(out / "reload-audit/raw-predictions.json") + assert [row["raw_token_ids"] for row in written] == [row["raw_token_ids"] for row in reloaded] + assert score_predictions(written) == score_predictions(reloaded) + assert torch.isfinite(next(model.language_model.parameters())).all().item() + write_json( + out / "audit.json", + { + "passed": True, + "step": spec["max_steps"], + "queries": len(written), + "raw_generation_exact_match": True, + "metrics": score_predictions(reloaded), + }, + ) + write_json(out / "status.json", {"state": "complete", "step": spec["max_steps"]}) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/parametric_architecture.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/parametric_architecture.py new file mode 100644 index 0000000000000000000000000000000000000000..a9be8f8ef618d4d7767ffc27c5a8b9a67ff77d9a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/parametric_architecture.py @@ -0,0 +1,444 @@ +"""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"), + "W4": (4, 1, "wide"), + "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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/parametric_architecture_train.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/parametric_architecture_train.py new file mode 100644 index 0000000000000000000000000000000000000000..55c77a2f48a116b87a2159b90bb2ab76a6730887 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/qwen_constraints.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/qwen_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..6181f6dad22ab1a99443ffddb19f67c7c6ad701b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/qwen_path_learning.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/qwen_path_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..bc113a47da9c9fc22e346812c7f48f5ae7bc8b92 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/qwen_path_train.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/qwen_path_train.py new file mode 100644 index 0000000000000000000000000000000000000000..fabb31112396100c708fafd83993acdb8c46f918 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/realworld_composition.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/realworld_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..a05d1c9d956093315cedab365228e2fce72b6022 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/realworld_composition_data.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/realworld_composition_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e907ece415c9c6e027e965818c1b8e6f82a2462e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/realworld_confirmation.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/realworld_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..5cfed1010e1cc6f386e54d10c69675d34f4bed4a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/realworld_confirmation_analysis.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/realworld_confirmation_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..1b6fcadbe2e7be2944fe6e398e29c0812ca1329f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/recurrence_use.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/recurrence_use.py new file mode 100644 index 0000000000000000000000000000000000000000..3f2cf4432769a0bc1ea0278bf25468307718877b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/representation_alignment.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/representation_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..923e412fdf09bfaf85ca6de1fcb11cf4d6e754de --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/residual_cache.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/residual_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..20f4f21ac38bfedf6fa1d48968333c80c07f06ea --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/sequential_data.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/sequential_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e7d9838643105debcddeb8128eef246b0d8c515f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/sequential_data.py @@ -0,0 +1,380 @@ +"""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 + available_ids = safe | b_ids + for role in ["BA", "AB"]: + candidates = [ + row + for row in rows + if set(row["atom_ids"]) <= available_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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/sequential_replay.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/sequential_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..74e07bda915bd1239ba1189222380679038deb1f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/sequential_replay.py @@ -0,0 +1,489 @@ +"""Continue a fixed stage-A model with atomic or full old-data replay. + +The new-fact stream is copied exactly from the parent's original stage B. +Half of every batch is old data: either A atomics or the original alternating +atomic/composition stream. Both arms intentionally reset AdamW and its schedule. +All counters describe the newly executed continuation, never inherited A work. +""" + +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 . import sequential_transfer as original +from .grok_depth import utc +from .realworld_composition import model_digest, optimizer_for, update +from .realworld_composition_data import sha256, write_json + +ARMS = ("atom_replay", "full_replay") +COUNTERS = ( + "examples", + "supervised_tokens", + "effective_input_tokens", + "executed_input_tokens", + "estimated_matmul_training_flops", +) + + +def array_hash(values): + return hashlib.sha256(np.ascontiguousarray(values).tobytes()).hexdigest() + + +def continuation_plan(data, parent_spec, spec): + """Derive both suffixes from the original materialized plan without resampling.""" + if spec["replay_arm"] not in ARMS: + raise ValueError("Unknown replay arm") + if parent_spec["history"] != "sequential_composition": + raise ValueError("Continuation requires an original composition-learning parent") + if spec["original_stage_a_steps"] != parent_spec["stage_a_steps"]: + raise ValueError("The inherited stage-A boundary cannot change") + batch = parent_spec["batch_size"] + steps = spec["stage_b_steps"] + if batch % 2 or steps < 2 or steps % 2 or steps > parent_spec["stage_b_steps"]: + raise ValueError("Use an even batch and even positive suffix within the original B stream") + if spec.get("batch_size", batch) != batch: + raise ValueError("Continuation must preserve the parent batch size") + half = batch // 2 + if ( + parent_spec.get("stage_a_composition_per_batch", half) != half + or parent_spec.get("stage_b_new_per_batch", half) != half + ): + raise ValueError("The original plan must have the specified 50:50 mixtures") + records, parent_plan = original.training_plan(data, parent_spec) + boundary = parent_spec["stage_a_steps"] + first = parent_plan[:boundary] + slots = steps * half + old = first.reshape(-1) if spec["replay_arm"] == "full_replay" else first[:, :half].reshape(-1) + if len(old) < slots: + raise ValueError("The inherited stage-A stream is too short for this replay budget") + replay = old[:slots].reshape(steps, half).copy() + new = parent_plan[boundary : boundary + steps, -half:].copy() + if any(records[index].get("subset") != "B" for index in new.reshape(-1)): + raise AssertionError("The copied new stream contains a non-B example") + if any(records[index].get("subset") == "B" for index in replay.reshape(-1)): + raise AssertionError("Old replay contains B knowledge") + if spec["replay_arm"] == "atom_replay": + if any(records[index].get("subset") != "A" for index in replay.reshape(-1)): + raise AssertionError("Atomic replay contains a composition") + else: + atomic_slots = sum(records[index].get("subset") == "A" for index in replay.reshape(-1)) + if atomic_slots != slots // 2: + raise AssertionError("Full replay does not preserve the original 50:50 old mixture") + plan = np.concatenate((replay, new), axis=1) + manifest = original.plan_manifest(records, plan, {"history": spec["replay_arm"]}) + manifest.update( + new_stream_sha256=array_hash(new), + replay_stream_sha256=array_hash(replay), + parent_plan_sha256=array_hash(parent_plan), + stage_a_prefix_sha256=array_hash(first), + stage_b_steps=steps, + old_per_batch=half, + new_per_batch=half, + replay_source="original A plan flattened prefix" + if spec["replay_arm"] == "full_replay" + else "original A plan atomic columns flattened prefix", + inherited_examples=int(first.size), + ) + return records, plan, manifest, parent_plan + + +def learning_rate(spec, local_step): + steps = spec["stage_b_steps"] + if not 0 <= local_step <= steps: + raise ValueError("Learning-rate step must be a local continuation update") + warmup = spec.get("warmup_steps", max(1, steps // 100)) + if not 1 <= warmup < steps: + raise ValueError("Warmup must be positive and shorter than the continuation") + peak = spec.get("learning_rate", 3e-4) + if local_step <= warmup: + return peak * local_step / warmup + fraction = (local_step - warmup) / (steps - warmup) + floor = spec.get("minimum_lr_fraction", 0.1) + return peak * (floor + (1 - floor) * (1 + math.cos(math.pi * fraction)) / 2) + + +def fresh_optimizer(model, spec): + betas = tuple(spec.get("optimizer_betas", [0.9, 0.95])) + if betas != (0.9, 0.95): + raise ValueError("This recipe fixes fresh AdamW betas to (0.9, 0.95)") + optimizer = optimizer_for(model, spec.get("learning_rate", 3e-4), spec.get("weight_decay", 0.1)) + optimizer.defaults["betas"] = betas + for group in optimizer.param_groups: + group["betas"] = betas + if optimizer.state: + raise AssertionError("A new continuation cannot inherit Adam moments") + return optimizer + + +def _load_source(spec, device): + directory, checkpoint_path = Path(spec["parent_run_dir"]), Path(spec["parent_checkpoint"]) + if checkpoint_path.resolve() != (directory / "stage-a.pt").resolve(): + raise ValueError("Use the declared parent's saved stage-a.pt") + if sha256(checkpoint_path) != spec["parent_checkpoint_sha256"]: + raise ValueError("Parent stage-A checkpoint hash changed") + run_path = directory / "run.json" + expected_run_hash = spec.get("parent_run_sha256", spec.get("parent_run_file_sha256")) + if expected_run_hash is None or sha256(run_path) != expected_run_hash: + raise ValueError("Parent run metadata hash missing or changed") + parent_metadata = json.loads(run_path.read_text()) + parent_spec = parent_metadata["spec"] + if not (directory / "audit.json").exists() or not json.loads( + (directory / "audit.json").read_text() + ).get("passed"): + raise ValueError("The source run must have passed its independent audit") + for key in ("model", "data_sha256", "initialization", "unique_layers", "repeats"): + if key in spec and spec[key] != parent_spec[key]: + raise ValueError(f"Continuation cannot change inherited {key}") + for key in ("data_file", "tokenizer"): + if key in spec and Path(spec[key]).resolve() != Path(parent_spec[key]).resolve(): + raise ValueError(f"Continuation cannot change inherited {key}") + data, tokenizer, model, device = original._setup(parent_spec, device) + records, plan, manifest, parent_plan = continuation_plan(data, parent_spec, spec) + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + parent_plan_record = json.loads((directory / "sampling-plan.json").read_text()) + if not ( + checkpoint["plan_sha256"] + == parent_plan_record["plan_sha256"] + == manifest["parent_plan_sha256"] + ): + raise ValueError("Parent checkpoint, metadata and regenerated sampling plan disagree") + boundary = parent_spec["stage_a_steps"] + if checkpoint["step"] != boundary: + raise ValueError("Source checkpoint is not at the original A/B boundary") + expected_counts = np.bincount(parent_plan[:boundary].reshape(-1), minlength=len(records)) + if not np.array_equal(checkpoint["counts"], expected_counts): + raise ValueError("Inherited stage-A exposures differ from the frozen prefix") + if checkpoint["counters"]["examples"] != int(expected_counts.sum()): + raise ValueError("Inherited stage-A example counter is inconsistent") + model.load_state_dict(checkpoint["model"]) + torch.set_rng_state(checkpoint["cpu_rng"]) + if device.type == "cuda": + if checkpoint["cuda_rng"] is None: + raise ValueError("A GPU continuation requires the saved parent CUDA RNG") + torch.cuda.set_rng_state(checkpoint["cuda_rng"], device) + inherited = { + "step": boundary, + "model_sha256": model_digest(model), + "counters": checkpoint["counters"], + "counts": checkpoint["counts"].tolist(), + "cpu_rng_sha256": array_hash(checkpoint["cpu_rng"].numpy()), + "cuda_rng_sha256": array_hash(checkpoint["cuda_rng"].numpy()) + if checkpoint["cuda_rng"] is not None + else None, + } + return data, tokenizer, model, device, parent_spec, records, plan, manifest, inherited + + +def _evaluate(model, data, tokenizer, device, spec, *, full): + return original.evaluate_transfer( + model, + data, + tokenizer, + device, + full=full, + autonomous=full, + batch=spec.get("evaluation_batch_size", 64), + ) + + +def _nodes(spec): + nodes = sorted(set(spec.get("evaluation_nodes", [])) | {0, spec["stage_b_steps"]}) + if nodes[0] < 0 or nodes[-1] != spec["stage_b_steps"]: + raise ValueError("Evaluation nodes must use local B steps within the new budget") + return set(nodes) + + +def run(spec, out, device="cuda:0"): + 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 continuation has a different spec") + return json.loads((out / "complete.json").read_text()) + nodes = _nodes(spec) + loaded = _load_source(spec, device) + data, tokenizer, model, device, parent_spec, records, plan, manifest, inherited = loaded + boundary, budget = inherited["step"], len(plan) + optimizer = fresh_optimizer(model, spec) + training_spec = {**parent_spec, **spec} + training_spec["microbatch_size"] = spec.get("microbatch_size", parent_spec["microbatch_size"]) + counts = np.zeros(len(records), dtype=np.int64) + counters = {key: 0 for key in COUNTERS} + counters.update(training_seconds=0.0, wall_seconds=0.0) + history, initial_local = [], 0 + if (out / "latest.pt").exists(): + previous = json.loads((out / "run.json").read_text()) + if previous["spec"] != spec or previous["parent_model_sha256"] != inherited["model_sha256"]: + raise ValueError("Resume would change the continuation or its parent") + state = original.restore_checkpoint(out / "latest.pt", model, optimizer, manifest) + initial_local = state["step"] - boundary + if not 0 <= initial_local <= budget: + raise ValueError("Resume checkpoint is outside the continuation budget") + counts, counters, history = state["counts"], state["counters"], state["history"] + metadata = {**previous, "pid": os.getpid(), "resumed_from_step": state["step"]} + else: + if (out / "run.json").exists(): + raise FileExistsError("An existing attempt has no recoverable checkpoint") + metadata = { + "spec": spec, + "parent_spec": parent_spec, + "model": parent_spec["model"], + "phase": spec.get("phase", "development"), + "replay_arm": spec["replay_arm"], + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else "cpu", + "dtype": "BF16 AMP; FP32 parameters/AdamW", + "job_type": "sequential-replay", + "tracking_group": spec.get("tracking_group"), + "parameters": sum(parameter.numel() for parameter in model.parameters()), + "initial_model_sha256": inherited["model_sha256"], + "parent_model_sha256": inherited["model_sha256"], + "parent_checkpoint_sha256": spec["parent_checkpoint_sha256"], + "parent_stage_a_step": boundary, + "world_sha256": parent_spec["data_sha256"], + "optimizer": "fresh AdamW; betas=(.9,.95); clip=1; no inherited moments", + "optimizer_reset": True, + "weight_decay_scope": "specified decay on weights; zero on bias and layer norm", + "learning_step_unit": "global_optimizer_update", + "counter_scope": "new stage-B continuation only; inherited A costs recorded separately", + "inherited_stage_a": inherited, + "sampling_manifest": {key: value for key, value in manifest.items() if key != "counts"}, + "created_utc": utc(), + } + write_json(out / "sampling-plan.json", manifest) + write_json(out / "run.json", metadata) + write_json(out / "learning.json", history) + started, wall_offset = time.perf_counter(), counters["wall_seconds"] + loss = history[-1].get("loss") if history else None + latest_local = initial_local + for local in range(initial_local, budget + 1): + global_step = boundary + local + if local > initial_local: + for group in optimizer.param_groups: + group["lr"] = learning_rate(spec, local) + ids = plan[local - 1] + selected = [records[index] for index in ids] + original._sync(device) + began = time.perf_counter() + result = update( + model, optimizer, selected, training_spec, device, tokenizer.eos_token_id + ) + original._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 COUNTERS[2:]: + counters[key] += result[key] + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + if local % spec.get("status_interval", 50) == 0: + write_json( + out / "status.json", + { + "state": "training", + "step": global_step, + "branch_step": local, + "local_optimizer_updates": local, + "target_step": boundary + budget, + "loss": loss, + "pid": os.getpid(), + **counters, + "updated_utc": utc(), + }, + ) + if local in nodes and not any(row["step"] == global_step for row in history): + metrics, raw = _evaluate( + model, data, tokenizer, device, spec, full=local in {0, budget} + ) + write_json(out / f"predictions-{global_step:07d}.json", raw) + if local == 0: + expected_path = Path(spec["parent_run_dir"]) / f"predictions-{boundary:07d}.json" + if raw != json.loads(expected_path.read_text()): + raise AssertionError("Restored stage-A predictions differ from the parent") + exposure = {} + for name, subset in (("A", "A"), ("B", "B"), ("composition", None)): + indices = ( + [index for index, row in enumerate(records) if row.get("subset") == subset] + if subset + else list(range(len(data["atoms"]), len(records))) + ) + exposure[name] = float(counts[indices].mean()) if indices else 0.0 + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + history.append( + { + "step": global_step, + "branch_step": local, + "local_optimizer_updates": local, + "stage": "B", + "stage_a_boundary": local == 0, + "condition": spec["replay_arm"], + "metrics": metrics, + "loss": loss, + "learning_rate": learning_rate(spec, local), + "exposures": exposure, + "atomic_A_epochs": exposure["A"], + "atomic_B_epochs": exposure["B"], + "composition_epochs": exposure["composition"], + **counters, + "created_utc": utc(), + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + } + ) + write_json(out / "learning.json", history) + original.save_checkpoint( + out / "latest.pt", + model, + optimizer, + global_step, + counts, + counters, + history, + manifest, + ) + latest_local = local + print( + json.dumps( + { + "step": global_step, + "branch_step": local, + "arm": spec["replay_arm"], + "loss": loss, + "metrics": metrics, + } + ), + flush=True, + ) + elif local > initial_local and local % spec.get("checkpoint_interval", 500) == 0: + original.save_checkpoint( + out / "latest.pt", + model, + optimizer, + global_step, + counts, + counters, + history, + manifest, + ) + latest_local = local + if latest_local != budget: + original.save_checkpoint( + out / "latest.pt", + model, + optimizer, + boundary + budget, + counts, + counters, + history, + manifest, + ) + final = history[-1] + write_json(out / "endpoint.json", final["metrics"]) + result = { + "state": "trained_pending_independent_reload", + "step": boundary + budget, + "local_optimizer_updates": budget, + "parent_stage_a_step": boundary, + "pid": os.getpid(), + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + "plan_sha256": manifest["plan_sha256"], + "new_stream_sha256": manifest["new_stream_sha256"], + **counters, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + return result + + +def audit(out, device="cuda:0"): + """Independently reload both the inherited boundary and the new endpoint.""" + out = Path(out) + metadata = json.loads((out / "run.json").read_text()) + spec = metadata["spec"] + 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("Continuation checkpoint differs from recorded endpoint") + loaded = _load_source(spec, device) + data, tokenizer, model, device, _parent_spec, records, plan, manifest, inherited = loaded + if metadata["parent_model_sha256"] != inherited["model_sha256"]: + raise ValueError("Inherited model changed") + boundary_metrics, boundary_raw = _evaluate(model, data, tokenizer, device, spec, full=True) + expected_boundary = json.loads((out / f"predictions-{inherited['step']:07d}.json").read_text()) + history = json.loads((out / "learning.json").read_text()) + if boundary_raw != expected_boundary or boundary_metrics != history[0]["metrics"]: + raise AssertionError("Independent stage-A boundary scoring differs") + 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 continuation model or update count differs") + if ( + state["plan_sha256"] != manifest["plan_sha256"] + or manifest["plan_sha256"] != trained["plan_sha256"] + ): + raise ValueError("Continuation sampling plan changed") + expected_counts = np.bincount(plan.reshape(-1), minlength=len(records)) + if not np.array_equal(state["counts"], expected_counts): + raise ValueError("New-only exposures differ from the continuation plan") + if state["counters"]["examples"] != int(plan.size) or trained["examples"] != int(plan.size): + raise ValueError("New-only example accounting includes inherited work or misses updates") + optimizer_steps = {int(value["step"]) for value in state["optimizer"]["state"].values()} + if optimizer_steps != {len(plan)}: + raise ValueError("Fresh optimizer step counters did not start from zero") + if any(tuple(group["betas"]) != (0.9, 0.95) for group in state["optimizer"]["param_groups"]): + raise ValueError("Optimizer recipe changed") + if [row["branch_step"] for row in history] != sorted(_nodes(spec)): + raise ValueError("Continuation evaluation nodes are incomplete") + for row in history: + if ( + row["step"] != inherited["step"] + row["branch_step"] + or row["local_optimizer_updates"] != row["branch_step"] + or row["examples"] != row["branch_step"] * plan.shape[1] + ): + raise ValueError("Continuation trajectory step/exposure accounting changed") + metrics, raw = _evaluate(model, data, tokenizer, device, spec, full=True) + 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 continuation endpoint scoring differs") + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "model_sha256": trained["model_sha256"], + "checkpoint_sha256": trained["checkpoint_sha256"], + "parent_boundary_recomputed": True, + "fresh_optimizer_verified": True, + "new_only_exposures_exact": True, + "new_stream_sha256": manifest["new_stream_sha256"], + "predictions_recomputed": sum(map(len, boundary_raw.values())) + + sum(map(len, raw.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": trained["step"], + "local_optimizer_updates": len(plan), + "independently_reloaded": True, + }, + ) + return result diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/sequential_transfer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/sequential_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..865c5a8343f84fdb340f7961bca649b71b1efd76 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/shared_cache.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/shared_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf5aec02ab0270e60a6c41882c24bdd4b3d34cc --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/small_lm_composition.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/small_lm_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..f7bc9b1ea8e7d825eb5f27c33bb4d7e38bb7bcc1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/small_lm_followup.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/small_lm_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..4c986ea475b4f0abe83ea3d0411a049344ac0e08 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/storage_composition.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/storage_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..094211c26edecbed2a534bad16c84c42b2cdebd0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/storage_frontier.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/storage_frontier.py new file mode 100644 index 0000000000000000000000000000000000000000..db36e560aed8b173bb72c836b3d02dc8381bbcc5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/text_loss_source.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/text_loss_source.py new file mode 100644 index 0000000000000000000000000000000000000000..6f9377848d4673a2937273cf26a33f8e859874d0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/text_pretrain.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/text_pretrain.py new file mode 100644 index 0000000000000000000000000000000000000000..2682a0925a00e0e8b0eef3781521830d891ef9d7 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/text_structure.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/text_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c74f97848144e288267dedd2df039a1f8c1a52 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/twohop_depth.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/twohop_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..19b9a4b76eadef68acf7603b8434567145244311 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/write_target_editing.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/write_target_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f395611444591e300b48869efe3a3840054e582 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/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/implicit-reasoning-paper-reproduction-v2/source/tests/test_paper_reproduction.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/tests/test_paper_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..7278670989d78a6bb9de9900d3847ffe45c3fcb8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/tests/test_paper_reproduction.py @@ -0,0 +1,100 @@ +"""Scientific contracts for the original-paper reproduction.""" + +import copy +from pathlib import Path + +import pytest + +from llm_memory_editability.paper_reproduction import ( + decode_unmapped_tokens, + prepare, + read_json, + score_predictions, + validate_data, +) + +NOTEBOOK = ( + Path(__file__).resolve().parents[1] + / "docs/development-artifacts/implicit-reasoning-paper-reproduction-v1" + / "upstream/notebooks/data_preparation.ipynb" +) + + +@pytest.fixture +def prepared(tmp_path, monkeypatch): + monkeypatch.setenv("PYTHONHASHSEED", "0") + destination = tmp_path / "data" + audit = prepare(NOTEBOOK, destination, entities=30, relations=40, degree=10) + return destination, audit + + +def test_paper_count_and_paired_compositions(prepared): + root, audit = prepared + only = read_json(root / "only_ii/train.json") + plus = read_json(root / "ii_plus_id/train.json") + # An accidentally float-valued count would select every candidate in the notebook. + assert len(only) == round(7.2 * 285) == 2052 + assert audit["candidate_train_ii"] > len(only) + assert plus[285:] == only + assert read_json(root / "only_ii/test.json") == read_json(root / "ii_plus_id/test.json") + assert audit["evaluation_counts"]["OOD Triples"] == 15 + assert audit["same_ii_and_probes"] + + +def test_all_queries_keep_truth_and_held_out_roles(prepared): + _, audit = prepared + assert audit["passed"] + assert audit["atomic_truths"] == 300 + assert audit["composition_truths"] > 2052 + + +def test_existing_dataset_cannot_be_overwritten(prepared): + root, _ = prepared + with pytest.raises(FileExistsError): + prepare(NOTEBOOK, root) + + +def test_wrong_hop_role_is_rejected(): + atomic = {"input_text": "", "target_text": ""} + composition = {"input_text": "", "target_text": ""} + groups = {"ID Triples": [atomic], "OOD Triples": [], "Train-II": [composition]} + train = {"only_ii": [composition], "ii_plus_id": [atomic, composition]} + assert validate_data(groups, train, expected_id=1, expected_ood=0, expected_ii=1)["passed"] + bad = copy.deepcopy(groups) + bad["Test-OI"] = [composition] + with pytest.raises(AssertionError): + validate_data(bad, train, expected_id=1, expected_ood=0, expected_ii=1) + + +def test_paper_canonicalization_does_not_hide_missing_eos(): + rows = [ + { + "type": "Test-II", + "target_text": "answer", + "model_output": "answer", + "strict_answer_eos": False, + } + ] + metrics = score_predictions(rows)["Test-II"] + assert metrics["paper_accuracy"] == 1 + assert metrics["strict_answer_eos_accuracy"] == 0 + + +def test_padding_class_is_an_incorrect_printable_token(): + from transformers import GPT2Tokenizer + + reference = NOTEBOOK.parents[5] / "data/implicit-reasoning-paper-reference-v1/gpt2" + tokenizer = GPT2Tokenizer.from_pretrained(reference, local_files_only=True) + vocabulary = ( + NOTEBOOK.parents[5] / "data/implicit-reasoning-paper-reproduction-v1/only_ii/vocab.json" + ) + tokenizer.add_tokens(read_json(vocabulary)) + text = "normal text" + ids = tokenizer.encode(text) + unmapped = len(tokenizer) + assert unmapped == 52463 + assert tokenizer._convert_id_to_token(unmapped) is None + with decode_unmapped_tokens(tokenizer): + assert tokenizer.decode(ids) == text + assert tokenizer.decode([unmapped]) == f"" + assert tokenizer._convert_id_to_token(unmapped) is None diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/validation.json b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/validation.json new file mode 100644 index 0000000000000000000000000000000000000000..a31a014ca5a27a2aba52dc049351bf58b3c3fdb5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/validation.json @@ -0,0 +1,67 @@ +{ + "passed": true, + "full_pool_queries": 18986, + "batch_size": 1024, + "steps": 2, + "embedding_update_norm": 0.00027920061256736517, + "all_parameters_finite": true, + "unmapped_class_queries_retained_as_failures": 1, + "raw_token_reload_exact_match": true, + "audit": { + "passed": true, + "step": 2, + "queries": 18986, + "raw_generation_exact_match": true, + "metrics": { + "ID Triples": { + "total": 3000, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + }, + "OOD Triples": { + "total": 2000, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + }, + "Test-II": { + "total": 3000, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + }, + "Test-IO": { + "total": 3000, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + }, + "Test-OI": { + "total": 3000, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + }, + "Test-OO": { + "total": 1986, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + }, + "Train-II": { + "total": 3000, + "paper_correct": 0, + "strict_correct": 0, + "paper_accuracy": 0.0, + "strict_answer_eos_accuracy": 0.0 + } + } + } +} diff --git a/docs/development-artifacts/independent-alignment-v1/execution-lock.json b/docs/development-artifacts/independent-alignment-v1/execution-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..9f82144c89e81b49d5bd302636adce11193705f0 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-v1/execution-lock.json @@ -0,0 +1,3 @@ +{ + "config_sha256": "bf5c5fcbc36d4679f097032bbe96a62b2f380d770b114c56cd62a98e5dc51eeb" +} diff --git a/docs/development-artifacts/independent-alignment-v1/frozen-config.json b/docs/development-artifacts/independent-alignment-v1/frozen-config.json new file mode 100644 index 0000000000000000000000000000000000000000..1c6c9e68ce57972dafd72620b73c8391f40c990c --- /dev/null +++ b/docs/development-artifacts/independent-alignment-v1/frozen-config.json @@ -0,0 +1,766 @@ +{ + "batch": "independent-alignment-v1", + "created_utc": "2026-10-07T03:20:47.489225+00:00", + "repository": "/ossfs/workspace/llm-memory-editability", + "source_root": "/ossfs/workspace/llm-memory-editability/docs/development-artifacts/independent-alignment-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/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/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_independent_alignment.py": "254a2a107976b727c1e6f557605bc7ef4e45fcda8da9ae3f8435c55df6bf60fb", + "scripts/run_shared_cache_branch.py": "9230d184923b5a4eb527952174397ec0954ecf96c45e2787c48c62230077e816", + "scripts/report_independent_alignment.py": "76ee1391d351bb8f1fe3aa74ee73d435dc4c2bf791d884070719859d70b6d866", + "scripts/audit_independent_alignment_tracking.py": "89ec8d965b149160a6a8693ede1ef45d48606f6a02fd405a3e77ff99a5ae89d5", + "tests/test_independent_alignment.py": "9a36ff04b75e4da75c172ce0b1bb5f417c02e564e89cdb56d44898feca029e2f", + "configs/experiment-tracking-defaults.json": "41d4b73b9d2f57f71fe51dd8500275f2c9fb3476ec24a9eeee3a8deadb5ecaa2", + "configs/representation-alignment-confirmation-v1.json": "7716c0c2cd67087404b83029e870e7568569bb3166c23e1ff15aca7e207a3b2a", + "docs/development-artifacts/independent-alignment-v1/protocol.md": "438bc9f25b9d42808a8f172dd72651ecc243a9cad0e3650256c0de637271a503", + "docs/development-artifacts/independent-alignment-v1/literature-methods.md": "a81c5c810d9e31d72377aee3b96b3848a237099cefaadbe550f9cff1699fc3bc" + }, + "git_commit": "f298768b6843c8e53a0009b3adc0291eda5fea2c", + "historical_scientific_sources_exact": true, + "historical_config_sha256": "7716c0c2cd67087404b83029e870e7568569bb3166c23e1ff15aca7e207a3b2a", + "specs": [ + { + "phase": "development", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 770011, + "initialization": 771011, + "arm": "bridge_ce", + "bridge_weight": 0.3, + "alignment_weight": 0.0, + "name": "development-w770011-i771011-bridge_ce", + "initial_model_sha256": "cb110e386e61ff521c01a13f36fa66ca54ba29c338b2841ea6c85aa0b1f71eec", + "parameters": 458880, + "data_sha256": "26e6a732000c6913c30dd18e62894fc7c7282259ac2a02765c9225a38d7bf6c9" + }, + { + "phase": "development", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 770011, + "initialization": 771011, + "arm": "aligned", + "bridge_weight": 0.3, + "alignment_weight": 0.3, + "name": "development-w770011-i771011-aligned", + "initial_model_sha256": "cb110e386e61ff521c01a13f36fa66ca54ba29c338b2841ea6c85aa0b1f71eec", + "parameters": 458880, + "data_sha256": "26e6a732000c6913c30dd18e62894fc7c7282259ac2a02765c9225a38d7bf6c9" + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 107270811, + "initialization": 107270821, + "arm": "bridge_ce", + "bridge_weight": 0.3, + "alignment_weight": 0.0, + "name": "confirmation-w107270811-i107270821-bridge_ce", + "initial_model_sha256": "b82094bed91a55b0a566f922a4502c87cc333c21d65a4f15d4f7b691fed43a91", + "parameters": 458880, + "data_sha256": "4ddfe769d03a5a5975755e95522df0a877a064c8ad92dea0256cf82539fc51cb" + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 107270811, + "initialization": 107270821, + "arm": "aligned", + "bridge_weight": 0.3, + "alignment_weight": 0.3, + "name": "confirmation-w107270811-i107270821-aligned", + "initial_model_sha256": "b82094bed91a55b0a566f922a4502c87cc333c21d65a4f15d4f7b691fed43a91", + "parameters": 458880, + "data_sha256": "4ddfe769d03a5a5975755e95522df0a877a064c8ad92dea0256cf82539fc51cb" + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 107270811, + "initialization": 107270822, + "arm": "bridge_ce", + "bridge_weight": 0.3, + "alignment_weight": 0.0, + "name": "confirmation-w107270811-i107270822-bridge_ce", + "initial_model_sha256": "537bf8dadf4808a4774b1144e1d32304dd32e8992423967d073732d8e6b5d8be", + "parameters": 458880, + "data_sha256": "4ddfe769d03a5a5975755e95522df0a877a064c8ad92dea0256cf82539fc51cb" + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 107270811, + "initialization": 107270822, + "arm": "aligned", + "bridge_weight": 0.3, + "alignment_weight": 0.3, + "name": "confirmation-w107270811-i107270822-aligned", + "initial_model_sha256": "537bf8dadf4808a4774b1144e1d32304dd32e8992423967d073732d8e6b5d8be", + "parameters": 458880, + "data_sha256": "4ddfe769d03a5a5975755e95522df0a877a064c8ad92dea0256cf82539fc51cb" + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 107270812, + "initialization": 107270821, + "arm": "bridge_ce", + "bridge_weight": 0.3, + "alignment_weight": 0.0, + "name": "confirmation-w107270812-i107270821-bridge_ce", + "initial_model_sha256": "b82094bed91a55b0a566f922a4502c87cc333c21d65a4f15d4f7b691fed43a91", + "parameters": 458880, + "data_sha256": "681919a4927752efd3260db27f8bda409b78fb09a1bd49da486375e4d589ff08" + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 107270812, + "initialization": 107270821, + "arm": "aligned", + "bridge_weight": 0.3, + "alignment_weight": 0.3, + "name": "confirmation-w107270812-i107270821-aligned", + "initial_model_sha256": "b82094bed91a55b0a566f922a4502c87cc333c21d65a4f15d4f7b691fed43a91", + "parameters": 458880, + "data_sha256": "681919a4927752efd3260db27f8bda409b78fb09a1bd49da486375e4d589ff08" + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 107270812, + "initialization": 107270822, + "arm": "bridge_ce", + "bridge_weight": 0.3, + "alignment_weight": 0.0, + "name": "confirmation-w107270812-i107270822-bridge_ce", + "initial_model_sha256": "537bf8dadf4808a4774b1144e1d32304dd32e8992423967d073732d8e6b5d8be", + "parameters": 458880, + "data_sha256": "681919a4927752efd3260db27f8bda409b78fb09a1bd49da486375e4d589ff08" + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 107270812, + "initialization": 107270822, + "arm": "aligned", + "bridge_weight": 0.3, + "alignment_weight": 0.3, + "name": "confirmation-w107270812-i107270822-aligned", + "initial_model_sha256": "537bf8dadf4808a4774b1144e1d32304dd32e8992423967d073732d8e6b5d8be", + "parameters": 458880, + "data_sha256": "681919a4927752efd3260db27f8bda409b78fb09a1bd49da486375e4d589ff08" + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 107270813, + "initialization": 107270821, + "arm": "bridge_ce", + "bridge_weight": 0.3, + "alignment_weight": 0.0, + "name": "confirmation-w107270813-i107270821-bridge_ce", + "initial_model_sha256": "b82094bed91a55b0a566f922a4502c87cc333c21d65a4f15d4f7b691fed43a91", + "parameters": 458880, + "data_sha256": "29954c1321490d36dc8a1e6829da99429ee32a666f823b788b9c4d7bc62ba894" + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 107270813, + "initialization": 107270821, + "arm": "aligned", + "bridge_weight": 0.3, + "alignment_weight": 0.3, + "name": "confirmation-w107270813-i107270821-aligned", + "initial_model_sha256": "b82094bed91a55b0a566f922a4502c87cc333c21d65a4f15d4f7b691fed43a91", + "parameters": 458880, + "data_sha256": "29954c1321490d36dc8a1e6829da99429ee32a666f823b788b9c4d7bc62ba894" + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 107270813, + "initialization": 107270822, + "arm": "bridge_ce", + "bridge_weight": 0.3, + "alignment_weight": 0.0, + "name": "confirmation-w107270813-i107270822-bridge_ce", + "initial_model_sha256": "537bf8dadf4808a4774b1144e1d32304dd32e8992423967d073732d8e6b5d8be", + "parameters": 458880, + "data_sha256": "29954c1321490d36dc8a1e6829da99429ee32a666f823b788b9c4d7bc62ba894" + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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": 2, + "repeats": 1, + "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 + ], + "world": 107270813, + "initialization": 107270822, + "arm": "aligned", + "bridge_weight": 0.3, + "alignment_weight": 0.3, + "name": "confirmation-w107270813-i107270822-aligned", + "initial_model_sha256": "537bf8dadf4808a4774b1144e1d32304dd32e8992423967d073732d8e6b5d8be", + "parameters": 458880, + "data_sha256": "29954c1321490d36dc8a1e6829da99429ee32a666f823b788b9c4d7bc62ba894" + } + ], + "gpus": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "runtime": { + "docker_context": "lm-memory", + "image": "sha256:a994f1a1886220693eb26b7ff201147fbd4b49477d335ab2707330cab771063f", + "python": "/opt/conda/bin/python", + "cpus": 2, + "memory": "12g" + }, + "maximum_run_seconds": 1200, + "maximum_engineering_seconds": 300, + "development_prerequisite": 0.99, + "updates": 224000, + "maximum_allocated_gpu_hours": 6 +} diff --git a/docs/development-artifacts/independent-alignment-v1/literature-methods.md b/docs/development-artifacts/independent-alignment-v1/literature-methods.md new file mode 100644 index 0000000000000000000000000000000000000000..7e1bbba58cc625bea07c66f2f940d30103d6bfd2 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-v1/literature-methods.md @@ -0,0 +1,9 @@ +# 方法复核与本轮改变 + +2026-10-07,先阅读旧[开发](../representation-alignment-v1/design.md)、[确认契约](../representation-alignment-v1/confirmation-design.md)及对应科学实现,核对事实划分、标签、位置、loss、采样、预算和完整生成评分。 + +Gatmiry等《Can Looped Transformers Learn to Implement Multi-step Gradient Descent for In-context Learning?》的[§3–5与附录A](https://arxiv.org/html/2410.08292v1)已在线复核。§3讨论高斯上下文线性回归、受约束P/Q矩阵及共享状态迭代;§5比较单层循环L次与L个独立注意力层,输入维度10、单位协方差并考察样本量/分布变化;附录A允许每层独立的A与u。它提示在相同执行深度下检验共享到独立层的适用性,不提供本项目完整非线性GPT事实记忆的对齐保证。本轮借鉴这项比较逻辑,并复用自己已验证的完整GPT干预。 + +另复核现有Coconut原文§3与§4.1(本机results/literature-framing-review-20261007/coconut2025.txt):其用最后hidden state作后续输入Embedding,通过多阶段删除CoT训练,正常NLL并屏蔽问题/潜在状态loss,推理增加连续状态前向。它直接研究生成状态的继续使用,但改变了推理流程和课程。本轮保持普通两层前向,在同首跳标签下比较额外几何训练项,因此不能把本轮称为Coconut复现。原文入口:[Training Large Language Models to Reason in a Continuous Latent Space](https://arxiv.org/abs/2412.06769)。 + +本轮唯一科学扩展为普通两独立层,保持宽度、两次块执行及组内信息/预算匹配。主比较不新增单独全文CE臂:用户指定的两组正好区分同标签情况下额外几何目标的作用。更多层、多跳、真实事实、新知识迁移及共享与独立同函数初始化均待本轮后决定。 diff --git a/docs/development-artifacts/independent-alignment-v1/local-validation.json b/docs/development-artifacts/independent-alignment-v1/local-validation.json new file mode 100644 index 0000000000000000000000000000000000000000..fa884286b1643d65448ab32a57df4fc91f63533b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-v1/local-validation.json @@ -0,0 +1,15 @@ +{ + "passed": true, + "related_tests": 39, + "tests": [ + "test_independent_alignment", + "test_representation_alignment", + "test_latent_scaling", + "test_grok_loop_model", + "test_knowledge_change_tracking" + ], + "ruff_check": true, + "ruff_format_check": true, + "python": "3.10.16 (main, Dec 11 2024, 16:24:50) [GCC 11.2.0]", + "utc": "2026-10-07T03:20:54.786570+00:00" +} diff --git a/docs/development-artifacts/independent-alignment-v1/postrun-validation.json b/docs/development-artifacts/independent-alignment-v1/postrun-validation.json new file mode 100644 index 0000000000000000000000000000000000000000..0128d048345818f1fe8a8427dccedb7e9358c33e --- /dev/null +++ b/docs/development-artifacts/independent-alignment-v1/postrun-validation.json @@ -0,0 +1,8 @@ +{ + "passed": true, + "source_hashes_passed": true, + "world_equal_weighting_check": true, + "missing_links": [], + "utc": "2026-10-07T03:26:38.033035+00:00", + "wandb_remote_audit_passed": true +} diff --git a/docs/development-artifacts/independent-alignment-v1/protocol.md b/docs/development-artifacts/independent-alignment-v1/protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..4f4bd8c92c2fc3c3899c28b39f5ffb495edce5cb --- /dev/null +++ b/docs/development-artifacts/independent-alignment-v1/protocol.md @@ -0,0 +1,37 @@ +# 普通独立层 Transformer 的表示训练干预复核 + +2026-10-07,按用户指定的下一步优先级实施;新知识迁移排在本轮之后。 + +## 问题与关键比较 + +已有共享单块执行两次的完整GPT中,单跳及中间实体读出均100%,同标签首跳CE与额外输入表示对齐的严格两跳成绩分别12.60%和92.32%。本轮检验额外表示约束的收益是否也出现在普通独立层Transformer,结论层级是受控训练的行为规律。 + +两组使用相同事实、全文下一词元损失和首跳实体标签。bridge_ce的辅助CE系数β=.3;aligned在同样β上增加λ=.3的单位向量平方距离。两组均执行完整辅助计算图,辅助几何项的权重是唯一组内差异。目标为stopgrad(E_b),不强制向量幅度相等。首跳状态为第一层结束、位置3的完整残差;该位置只能看BOS、主体、所有格和第一关系。第二关系、答案和测试链不进入其训练信号。 + +## 模型、数据与预算 + +普通GPT-2式两层,layers=2、repeats=1,各层参数及存储独立,宽128、4头、4倍GELU MLP、pre-LayerNorm、普通残差、可训练词/位置Embedding及绑定读出,dropout=0。458,880参数;旧共享模型260,608参数。保持宽度和执行深度,独立层自然增加参数量,且标准初始化的残差缩放随独立层数变化。因此本轮回答干预能否适用于普通模型,不把跨历史批次差值解释为纯共享约束的因果效应。 + +完全复用旧representation-alignment的世界生成器、训练实现、目标、三流采样、优化器和评分,其科学源码哈希必须与旧确认契约一致。每世界1024原子例(768共同+256锚点)、256训练组合;熟悉池按(主体,最终实体)留出,严格池512题,两条必要事实只在单跳训练中出现,严格事实与训练组合用到的事实不相交。人工事实、单词元实体和模板语言的范围明确保留。 + +每条从零训练16,000步,batch=192,三个流各64;lr=.001,wd=.01,warmup=200,余弦最低倍率.1。节点0/256/1000/2000/4000/8000/16000。每条组合64×16000/256=4000次平均曝光,原子和逐事实曝光数组另存。两组匹配初值、世界、采样流、曝光、更新次数和估算矩阵计算;采样、初值和数据哈希必须成对一致。所有参数训练,无新增推理头或执行次数。 + +开发复用旧世界770011、初值771011,两组各一条16k轨迹。正式三个新世界107270811/107270812/107270813,各两初始化107270821/107270822,两组共12条;stream_seed沿用776101。总14条、224000科学更新;八卡各8步工程训练另计,不纳入均值。 + +## 校准、主评分与解释 + +开发核对两组共同原子、训练组合及纯前缀共同/严格首跳读出均≥99%;只检查这些任务前提,不用严格或熟悉组合测试成绩选择配方。λ=.3直接沿用已验证干预,不扫描λ、层位置或最好节点。若前提不满足,保留结果并停止新世界扩展,不自动调参、加时或重启。正式全部固定端点保留,无按效果淘汰。 + +主指标为严格只见单跳事实的两跳完整生成(答案、句号和自产EOS全正确)。辅报熟悉事实留出组合、原子及训练组合、两条必要原子覆盖、自主两次调用和覆盖条件子集。原模型ln_final及绑定读出测纯四词元前缀的首跳身份,记录正确率和对输入Embedding的余弦,无拟合探针;这些是操作核查,不能单凭角度差异证明唯一中介。全量生成及逐题结果保存。 + +先在每世界平均两个初始化,再将三个世界等权平均;报告六个成对差值及三个世界差值。开发不进入正式均值,世界为独立单位,查询/初始化不增加独立世界数。展示全部学习曲线;主端点固定16000,不用最好中途值。正、零和负效应均报告;原子/读出不匹配的世界单独标记,不直接归因为组合能力上限。 + +若两组事实和首跳身份已掌握而对齐仍提升严格两跳,支持该训练干预不限于参数共享架构。若几何目标有效、前提满足而组合收益小,说明这套具体输入方向约束的效应存在架构条件。若前提失败,结论收窄为旧配方尚未建立可比条件。均不证明唯一MLP机制、必要条件、自然LM通用规律或新知识迁移。 + +## 执行与验收 + +LM专属Docker context,固定旧架构镜像digest;每条独立容器,单GPU、2CPU、12GiB内存,无网络、只读源码、独立/tmp与持久输出目录。GPU0–7只在现有批次完成且实际空闲时使用,不操作旧训练。冻结源码、配置及执行锁;拒绝无记录重启。八卡实际FP32/BF16矩阵计算、反向、同步、CUDA Graph/eager一更新对照、8步训练及独立重载通过后开展科学比较。 + +每个正式端点用独立进程重载全部生成、NLL、图真值和前缀读出,另按原始生成重计分并核对逐事实曝光。W&B在训练启动时同时运行,组independent-alignment-v1;保留网络失败与重试,核验远端所有节点和结束状态。学习过程与资源均记录,训练段耗时和含启动/评价/重载的分配耗时分开。每条最多1200秒,八卡工程每条最多300秒;最大分配预算6GPU小时,不追加实验矩阵。使用旧科学实现的评估时间不算训练更新。 + +方法复核见[literature-methods.md](literature-methods.md)。本轮不启动此前计划的新知识迁移。 diff --git a/docs/development-artifacts/independent-alignment-v1/source/configs/experiment-tracking-defaults.json b/docs/development-artifacts/independent-alignment-v1/source/configs/experiment-tracking-defaults.json new file mode 100644 index 0000000000000000000000000000000000000000..92273f717dfdee8e79a02a1a3fd47f874f8435f8 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/configs/representation-alignment-confirmation-v1.json b/docs/development-artifacts/independent-alignment-v1/source/configs/representation-alignment-confirmation-v1.json new file mode 100644 index 0000000000000000000000000000000000000000..f745bd121c422afa89c985caf8c98188029306d0 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-v1/source/configs/representation-alignment-confirmation-v1.json @@ -0,0 +1,732 @@ +{ + "created_utc": "2026-10-02T04:04:08.160814+00:00", + "phase": "new-world fixed comparison", + "specs": [ + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774101, + "initialization": 775101, + "arm": "baseline", + "bridge_weight": 0.0, + "alignment_weight": 0.0 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774101, + "initialization": 775101, + "arm": "bridge_ce", + "bridge_weight": 0.3, + "alignment_weight": 0.0 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774101, + "initialization": 775101, + "arm": "aligned", + "bridge_weight": 0.3, + "alignment_weight": 0.3 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774101, + "initialization": 775102, + "arm": "baseline", + "bridge_weight": 0.0, + "alignment_weight": 0.0 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774101, + "initialization": 775102, + "arm": "bridge_ce", + "bridge_weight": 0.3, + "alignment_weight": 0.0 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774101, + "initialization": 775102, + "arm": "aligned", + "bridge_weight": 0.3, + "alignment_weight": 0.3 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774102, + "initialization": 775101, + "arm": "baseline", + "bridge_weight": 0.0, + "alignment_weight": 0.0 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774102, + "initialization": 775101, + "arm": "bridge_ce", + "bridge_weight": 0.3, + "alignment_weight": 0.0 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774102, + "initialization": 775101, + "arm": "aligned", + "bridge_weight": 0.3, + "alignment_weight": 0.3 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774102, + "initialization": 775102, + "arm": "baseline", + "bridge_weight": 0.0, + "alignment_weight": 0.0 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774102, + "initialization": 775102, + "arm": "bridge_ce", + "bridge_weight": 0.3, + "alignment_weight": 0.0 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774102, + "initialization": 775102, + "arm": "aligned", + "bridge_weight": 0.3, + "alignment_weight": 0.3 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774103, + "initialization": 775101, + "arm": "baseline", + "bridge_weight": 0.0, + "alignment_weight": 0.0 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774103, + "initialization": 775101, + "arm": "bridge_ce", + "bridge_weight": 0.3, + "alignment_weight": 0.0 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774103, + "initialization": 775101, + "arm": "aligned", + "bridge_weight": 0.3, + "alignment_weight": 0.3 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774103, + "initialization": 775102, + "arm": "baseline", + "bridge_weight": 0.0, + "alignment_weight": 0.0 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774103, + "initialization": 775102, + "arm": "bridge_ce", + "bridge_weight": 0.3, + "alignment_weight": 0.0 + }, + { + "phase": "confirmation", + "stream_seed": 776101, + "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 + ], + "world": 774103, + "initialization": 775102, + "arm": "aligned", + "bridge_weight": 0.3, + "alignment_weight": 0.3 + } + ], + "source": { + "configs/experiment-tracking-defaults.json": "41d4b73b9d2f57f71fe51dd8500275f2c9fb3476ec24a9eeee3a8deadb5ecaa2", + "scripts/run_latent_scaling.py": "77551c23127308a1976c759c4cc445e6969edd22b6ae0c9d886f56d6a385f85d", + "scripts/run_representation_alignment.py": "784c9d87eb305f291c288d48a8878a2f785fdcaa2adb01beca49c469feed30a9", + "scripts/run_storage_composition.py": "77f936f88b6000a584b1c9c1a7a0f57e7d3882abc6c726fe4a39fd6e8740615d", + "scripts/run_storage_frontier.py": "5edd1ccb8d8f4c1085abbc572716e91dfa71eac112a17ed27985af4ce455c9c1", + "src/llm_memory_editability/bios_model.py": "99efb7feeeb15f33dd3f08174c1190f4aa470e3877d8ac6692b2d43fed4c5f4d", + "src/llm_memory_editability/experiment_tracking.py": "3808d306164e837f990764267fda842d1399e74cc98f290c3f69b91683173585", + "src/llm_memory_editability/grok_depth.py": "7d6d5af38a5dc4438b1e7ff44df8e833169d500f0d60d8933932bdb8822aca26", + "src/llm_memory_editability/grok_loop_model.py": "07e84388997a1710e5c821e54cf6d23726e4289aab178347761e060851fea6cc", + "src/llm_memory_editability/latent_scaling.py": "231050e859da58c52b9ea47d09fb5de91271df0d24cbab42dead3f911adc6119", + "src/llm_memory_editability/representation_alignment.py": "9794218f052a19019a5cb6427b84877a5174de3c0485bad441cdaed0ec7bd6b6", + "src/llm_memory_editability/storage_composition.py": "fa4d8b073ecb3ac69a3204ee446a4bc1ecf0c36f9d8dd1dcd0b6835c245e4c5a", + "src/llm_memory_editability/storage_frontier.py": "2a1adcbbb0439ed771e17090878b9f7c9861d2fef4544172a88c35bd037d4a22", + "src/llm_memory_editability/text_pretrain.py": "cd777a56ba270d3c71ed3260f68501ee0685d4cc58a4f7b952719236adf874cb", + "tests/test_latent_scaling.py": "a4c0f9a607ffe8451c4e761ddc9fac2b91d56cf7f4fe586859b173f7999bb6e1", + "tests/test_representation_alignment.py": "f14672ee0906ffe374c1bd2afa37f8a72acf327c3e4091fbe0785f6bfcc8706a", + "tests/test_storage_composition.py": "bf28eedcfcd7afeed7f0dd463cf29790309cb981f645f77842c5af161d4349a1", + "tests/test_storage_frontier.py": "ed9ffb2cb33980a38aa2e7c593b36559ea9026b4893aa4da5e3f0eab6f78fadb", + "scripts/report_representation_alignment.py": "95ad6b4193b3877a575f80f04be5137cdc0814c764c32eca0c8946dcf55710fa", + "docs/development-artifacts/representation-alignment-v1/confirmation-design.md": "6fb890db0c426959fc08b633118d259ba57f0dd0b49dafa7601ada18c5ffdd40" + }, + "selected_alignment_weight": 0.3, + "selection_rule": "minimum development lambda that improves familiar test over bridge_ce with <=1 pp atomic decrease; strict pool not used" +} diff --git a/docs/development-artifacts/independent-alignment-v1/source/docs/development-artifacts/independent-alignment-v1/literature-methods.md b/docs/development-artifacts/independent-alignment-v1/source/docs/development-artifacts/independent-alignment-v1/literature-methods.md new file mode 100644 index 0000000000000000000000000000000000000000..7e1bbba58cc625bea07c66f2f940d30103d6bfd2 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-v1/source/docs/development-artifacts/independent-alignment-v1/literature-methods.md @@ -0,0 +1,9 @@ +# 方法复核与本轮改变 + +2026-10-07,先阅读旧[开发](../representation-alignment-v1/design.md)、[确认契约](../representation-alignment-v1/confirmation-design.md)及对应科学实现,核对事实划分、标签、位置、loss、采样、预算和完整生成评分。 + +Gatmiry等《Can Looped Transformers Learn to Implement Multi-step Gradient Descent for In-context Learning?》的[§3–5与附录A](https://arxiv.org/html/2410.08292v1)已在线复核。§3讨论高斯上下文线性回归、受约束P/Q矩阵及共享状态迭代;§5比较单层循环L次与L个独立注意力层,输入维度10、单位协方差并考察样本量/分布变化;附录A允许每层独立的A与u。它提示在相同执行深度下检验共享到独立层的适用性,不提供本项目完整非线性GPT事实记忆的对齐保证。本轮借鉴这项比较逻辑,并复用自己已验证的完整GPT干预。 + +另复核现有Coconut原文§3与§4.1(本机results/literature-framing-review-20261007/coconut2025.txt):其用最后hidden state作后续输入Embedding,通过多阶段删除CoT训练,正常NLL并屏蔽问题/潜在状态loss,推理增加连续状态前向。它直接研究生成状态的继续使用,但改变了推理流程和课程。本轮保持普通两层前向,在同首跳标签下比较额外几何训练项,因此不能把本轮称为Coconut复现。原文入口:[Training Large Language Models to Reason in a Continuous Latent Space](https://arxiv.org/abs/2412.06769)。 + +本轮唯一科学扩展为普通两独立层,保持宽度、两次块执行及组内信息/预算匹配。主比较不新增单独全文CE臂:用户指定的两组正好区分同标签情况下额外几何目标的作用。更多层、多跳、真实事实、新知识迁移及共享与独立同函数初始化均待本轮后决定。 diff --git a/docs/development-artifacts/independent-alignment-v1/source/docs/development-artifacts/independent-alignment-v1/protocol.md b/docs/development-artifacts/independent-alignment-v1/source/docs/development-artifacts/independent-alignment-v1/protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..4f4bd8c92c2fc3c3899c28b39f5ffb495edce5cb --- /dev/null +++ b/docs/development-artifacts/independent-alignment-v1/source/docs/development-artifacts/independent-alignment-v1/protocol.md @@ -0,0 +1,37 @@ +# 普通独立层 Transformer 的表示训练干预复核 + +2026-10-07,按用户指定的下一步优先级实施;新知识迁移排在本轮之后。 + +## 问题与关键比较 + +已有共享单块执行两次的完整GPT中,单跳及中间实体读出均100%,同标签首跳CE与额外输入表示对齐的严格两跳成绩分别12.60%和92.32%。本轮检验额外表示约束的收益是否也出现在普通独立层Transformer,结论层级是受控训练的行为规律。 + +两组使用相同事实、全文下一词元损失和首跳实体标签。bridge_ce的辅助CE系数β=.3;aligned在同样β上增加λ=.3的单位向量平方距离。两组均执行完整辅助计算图,辅助几何项的权重是唯一组内差异。目标为stopgrad(E_b),不强制向量幅度相等。首跳状态为第一层结束、位置3的完整残差;该位置只能看BOS、主体、所有格和第一关系。第二关系、答案和测试链不进入其训练信号。 + +## 模型、数据与预算 + +普通GPT-2式两层,layers=2、repeats=1,各层参数及存储独立,宽128、4头、4倍GELU MLP、pre-LayerNorm、普通残差、可训练词/位置Embedding及绑定读出,dropout=0。458,880参数;旧共享模型260,608参数。保持宽度和执行深度,独立层自然增加参数量,且标准初始化的残差缩放随独立层数变化。因此本轮回答干预能否适用于普通模型,不把跨历史批次差值解释为纯共享约束的因果效应。 + +完全复用旧representation-alignment的世界生成器、训练实现、目标、三流采样、优化器和评分,其科学源码哈希必须与旧确认契约一致。每世界1024原子例(768共同+256锚点)、256训练组合;熟悉池按(主体,最终实体)留出,严格池512题,两条必要事实只在单跳训练中出现,严格事实与训练组合用到的事实不相交。人工事实、单词元实体和模板语言的范围明确保留。 + +每条从零训练16,000步,batch=192,三个流各64;lr=.001,wd=.01,warmup=200,余弦最低倍率.1。节点0/256/1000/2000/4000/8000/16000。每条组合64×16000/256=4000次平均曝光,原子和逐事实曝光数组另存。两组匹配初值、世界、采样流、曝光、更新次数和估算矩阵计算;采样、初值和数据哈希必须成对一致。所有参数训练,无新增推理头或执行次数。 + +开发复用旧世界770011、初值771011,两组各一条16k轨迹。正式三个新世界107270811/107270812/107270813,各两初始化107270821/107270822,两组共12条;stream_seed沿用776101。总14条、224000科学更新;八卡各8步工程训练另计,不纳入均值。 + +## 校准、主评分与解释 + +开发核对两组共同原子、训练组合及纯前缀共同/严格首跳读出均≥99%;只检查这些任务前提,不用严格或熟悉组合测试成绩选择配方。λ=.3直接沿用已验证干预,不扫描λ、层位置或最好节点。若前提不满足,保留结果并停止新世界扩展,不自动调参、加时或重启。正式全部固定端点保留,无按效果淘汰。 + +主指标为严格只见单跳事实的两跳完整生成(答案、句号和自产EOS全正确)。辅报熟悉事实留出组合、原子及训练组合、两条必要原子覆盖、自主两次调用和覆盖条件子集。原模型ln_final及绑定读出测纯四词元前缀的首跳身份,记录正确率和对输入Embedding的余弦,无拟合探针;这些是操作核查,不能单凭角度差异证明唯一中介。全量生成及逐题结果保存。 + +先在每世界平均两个初始化,再将三个世界等权平均;报告六个成对差值及三个世界差值。开发不进入正式均值,世界为独立单位,查询/初始化不增加独立世界数。展示全部学习曲线;主端点固定16000,不用最好中途值。正、零和负效应均报告;原子/读出不匹配的世界单独标记,不直接归因为组合能力上限。 + +若两组事实和首跳身份已掌握而对齐仍提升严格两跳,支持该训练干预不限于参数共享架构。若几何目标有效、前提满足而组合收益小,说明这套具体输入方向约束的效应存在架构条件。若前提失败,结论收窄为旧配方尚未建立可比条件。均不证明唯一MLP机制、必要条件、自然LM通用规律或新知识迁移。 + +## 执行与验收 + +LM专属Docker context,固定旧架构镜像digest;每条独立容器,单GPU、2CPU、12GiB内存,无网络、只读源码、独立/tmp与持久输出目录。GPU0–7只在现有批次完成且实际空闲时使用,不操作旧训练。冻结源码、配置及执行锁;拒绝无记录重启。八卡实际FP32/BF16矩阵计算、反向、同步、CUDA Graph/eager一更新对照、8步训练及独立重载通过后开展科学比较。 + +每个正式端点用独立进程重载全部生成、NLL、图真值和前缀读出,另按原始生成重计分并核对逐事实曝光。W&B在训练启动时同时运行,组independent-alignment-v1;保留网络失败与重试,核验远端所有节点和结束状态。学习过程与资源均记录,训练段耗时和含启动/评价/重载的分配耗时分开。每条最多1200秒,八卡工程每条最多300秒;最大分配预算6GPU小时,不追加实验矩阵。使用旧科学实现的评估时间不算训练更新。 + +方法复核见[literature-methods.md](literature-methods.md)。本轮不启动此前计划的新知识迁移。 diff --git a/docs/development-artifacts/independent-alignment-v1/source/scripts/audit_independent_alignment_tracking.py b/docs/development-artifacts/independent-alignment-v1/source/scripts/audit_independent_alignment_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..f67291b953df071f696e8ecaf897e6ce09b4569b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-v1/source/scripts/audit_independent_alignment_tracking.py @@ -0,0 +1,58 @@ +"""Verify remote W&B nodes, scientific final step and independent reload markers.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from llm_memory_editability.grok_depth import utc, write_json + + +def audit(config_path): + import wandb + + config = json.loads(Path(config_path).read_text()) + root = Path(config["repository"]) / "results" / config["batch"] + defaults = json.loads( + (Path(config["source_root"]) / "configs/experiment-tracking-defaults.json").read_text() + ) + api = wandb.Api(timeout=60) + records = [] + for spec in config["specs"]: + path = root / "tracking-wandb" / spec["name"] / "state.json" + if not path.exists(): + records.append(dict(name=spec["name"], passed=False, reason="missing_tracking_state")) + continue + local = json.loads(path.read_text()) + remote = api.run(f"{defaults['entity']}/{defaults['project']}/{local['run_id']}") + history = list(remote.scan_history(keys=["training/step"])) + steps = sorted({int(r["training/step"]) for r in history}) + passed = ( + set(steps) == set(spec["nodes"]) + and remote.state == "finished" + and remote.summary.get("independently_reloaded") is True + and remote.summary.get("scientific_final_step") == spec["steps"] + ) + records.append( + dict( + name=spec["name"], + passed=passed, + steps=steps, + state=remote.state, + independently_reloaded=remote.summary.get("independently_reloaded"), + scientific_final_step=remote.summary.get("scientific_final_step"), + url=local["url"], + ) + ) + result = dict(passed=all(r["passed"] for r in records), runs=records, utc=utc()) + write_json(root / "tracking-cloud-audit.json", result) + print(json.dumps(dict(passed=result["passed"], runs=len(records)))) + if not result["passed"]: + raise SystemExit(1) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path, required=True) + audit(parser.parse_args().config) diff --git a/docs/development-artifacts/independent-alignment-v1/source/scripts/report_independent_alignment.py b/docs/development-artifacts/independent-alignment-v1/source/scripts/report_independent_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..07b3559c784167b83997ed9040dd4ae1d96e4761 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-v1/source/scripts/report_independent_alignment.py @@ -0,0 +1,309 @@ +"""Recount the fixed endpoints, verify pairing/exposure and report all worlds.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import numpy as np + +from llm_memory_editability.grok_depth import EpochStream, write_json +from llm_memory_editability.latent_scaling import build_world +from llm_memory_editability.representation_alignment import pack_training + +TASKS = ("common_atomic", "train_composite", "familiar_test", "strict_test") + + +def recount(path, spec): + with ( + np.load(path / "world.npz") as world, + np.load(path / f"predictions-{spec['steps']:06d}.npz") as prediction, + ): + scores = {} + for task in TASKS: + generated = prediction[task + "_generated"] + correct = ( + (generated[:, 0] == world[task][:, -1]) + & (generated[:, 1] == 5) + & (generated[:, 2] == 1) + ) + np.testing.assert_array_equal(correct, prediction[task + "_correct"]) + scores[task] = float(correct.mean()) + for task in ("familiar_test", "strict_test"): + coverage = prediction[task + "_coverage"] + scores[task + "_atomic_coverage"] = float(coverage.mean()) + scores[task + "_autonomous_two_calls"] = float(prediction[task + "_two_calls"].mean()) + return scores + + +def exposure_audit(path, spec): + _, sizes = pack_training(build_world(spec)) + exposures = np.load(path / "exposures.npz") + for j, size in enumerate(sizes): + stream = EpochStream(size, spec["stream_seed"] + j) + drawn = stream.take(spec["steps"] * spec["batch_size"] // 3) + expected = np.bincount(drawn, minlength=size) + np.testing.assert_array_equal(expected, exposures[f"stratum{j}"]) + + +def aggregate(rows, keys): + result, by_world = {}, [] + for world in sorted({r["world"] for r in rows}): + for arm in ("bridge_ce", "aligned"): + subset = [r for r in rows if r["world"] == world and r["arm"] == arm] + if not subset: + continue + by_world.append( + dict( + world=world, + arm=arm, + **{k: float(np.mean([r[k] for r in subset])) for k in keys}, + ) + ) + for arm in ("bridge_ce", "aligned"): + subset = [r for r in by_world if r["arm"] == arm] + if subset: + result[arm] = {k: float(np.mean([r[k] for r in subset])) for k in keys} + return result, by_world + + +def report(config_path): + config = json.loads(Path(config_path).read_text()) + root = Path(config["repository"]) / "results" / config["batch"] + target = root / "report" + target.mkdir(parents=True, exist_ok=True) + rows, histories = [], {} + for spec in config["specs"]: + path = root / "runs" / spec["name"] + if not (path / "audit.json").exists(): + continue + audit = json.loads((path / "audit.json").read_text()) + assert audit["passed"] + complete = json.loads((path / "complete.json").read_text()) + scores = recount(path, spec) + for task in TASKS: + assert scores[task] == complete["metrics"][task]["accuracy"] + exposure_audit(path, spec) + diagnostics = json.loads((path / "state-diagnostics.json").read_text()) + scores.update( + { + task + "_first_hop_readout": diagnostics[task][ + "first_hop_original_readout_accuracy" + ] + for task in ("common_atomic", "familiar_test", "strict_test") + } + ) + scores.update( + { + task + "_cosine": diagnostics[task]["mean_cosine_to_input_embedding"] + for task in ("familiar_test", "strict_test") + } + ) + rows.append( + dict( + name=spec["name"], + phase=spec["phase"], + world=spec["world"], + initialization=spec["initialization"], + arm=spec["arm"], + parameters=spec["parameters"], + steps=spec["steps"], + **scores, + training_seconds=complete["training_seconds"], + **{ + k: complete[k] + for k in ["world_sha256", "initial_model_sha256", "sample_stream_sha256"] + }, + ) + ) + histories[spec["name"]] = json.loads((path / "learning.json").read_text()) + if not rows: + raise RuntimeError("No audited endpoints") + pairs = [] + keys = [ + k + for k in rows[0] + if k in TASKS + or k.endswith( + ("_first_hop_readout", "_cosine", "_atomic_coverage", "_autonomous_two_calls") + ) + ] + for world, initialization in sorted({(r["world"], r["initialization"]) for r in rows}): + pair = { + r["arm"]: r + for r in rows + if (r["world"], r["initialization"]) == (world, initialization) + } + assert set(pair) == {"bridge_ce", "aligned"}, pair.keys() + for k in ["world_sha256", "initial_model_sha256", "sample_stream_sha256"]: + assert pair["bridge_ce"][k] == pair["aligned"][k], k + a, b = pair["aligned"], pair["bridge_ce"] + pairs.append( + dict( + phase=a["phase"], + world=world, + initialization=initialization, + **{k + "_difference": a[k] - b[k] for k in keys}, + ) + ) + with ( + np.load(root / "runs" / a["name"] / "exposures.npz") as x, + np.load(root / "runs" / b["name"] / "exposures.npz") as y, + ): + for k in x.files: + np.testing.assert_array_equal(x[k], y[k]) + confirmation = [r for r in rows if r["phase"] == "confirmation"] + means, world_means = aggregate(confirmation, keys) + development, _ = aggregate([r for r in rows if r["phase"] == "development"], keys) + prereqs = [ + r + for r in confirmation + if min( + r["common_atomic"], + r["train_composite"], + r["common_atomic_first_hop_readout"], + r["strict_test_first_hop_readout"], + ) + < 0.99 + ] + summary = dict( + batch=config["batch"], + audited_runs=len(rows), + confirmation_runs=len(confirmation), + confirmation_worlds=len({r["world"] for r in confirmation}), + means=means, + world_means=world_means, + pairs=pairs, + development=development, + pairing_and_exposure_audit_passed=True, + prereq_unmatched_runs=[r["name"] for r in prereqs], + total_training_gpu_hours=sum(r["training_seconds"] for r in rows) / 3600, + historical_reference=dict( + bridge_ce_strict=0.1260, aligned_strict=0.9232, unpaired_historical_context=True + ), + ) + write_json(target / "summary.json", summary) + with (target / "endpoints.csv").open("w") as f: + writer = csv.DictWriter(f, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + with (target / "pairs.csv").open("w") as f: + writer = csv.DictWriter(f, fieldnames=list(pairs[0])) + writer.writeheader() + writer.writerows(pairs) + text = [ + "# 普通独立层的表示训练干预复核", + "", + f"固定16k端点:{len(rows)}条重载通过,正式{len(confirmation)}条,三个新世界各两个初始化。", + "开发不进入正式均值;先平均每世界初始化,再世界等权。", + "", + "| 两层普通Transformer | 单跳 | 训练组合 | 中间实体读出(严格池) " + "| 熟悉留出组合 | 严格只见单跳事实的组合 |", + "| --- | ---: | ---: | ---: | ---: | ---: |", + ] + for arm, label in [("bridge_ce", "同首跳实体CE"), ("aligned", "同首跳CE+表示对齐")]: + if arm in means: + m = means[arm] + text.append( + "| " + + label + + " | " + + " | ".join( + f"{100 * m[k]:.2f}%" + for k in [ + "common_atomic", + "train_composite", + "strict_test_first_hop_readout", + "familiar_test", + "strict_test", + ] + ) + + " |" + ) + if means: + delta = 100 * (means["aligned"]["strict_test"] - means["bridge_ce"]["strict_test"]) + positives = sum( + p["strict_test_difference"] > 0 for p in pairs if p["phase"] == "confirmation" + ) + text += [ + "", + f"严格组合差值{delta:+.2f}个百分点,六配对中{positives}个为正。", + f"正式前提不匹配的轨迹:{len(prereqs)}条,全部保留;见summary.json。", + "", + "| 世界 | 首跳CE严格 | 对齐严格 | 差值(百分点) |", + "| --- | ---: | ---: | ---: |", + ] + for world in sorted({r["world"] for r in confirmation}): + w = {r["arm"]: r for r in world_means if r["world"] == world} + x, y = w["bridge_ce"]["strict_test"], w["aligned"]["strict_test"] + text.append(f"| {world} | {100 * x:.2f}% | {100 * y:.2f}% | {100 * (y - x):+.2f} |") + text += [ + "", + "结果解释限定于宽128、两独立层、人工事实和模板两跳。组内只改变对齐权重。", + "旧共享模型12.60%/92.32%是不同世界上的历史参照;独立层有更多参数且标准初始化缩放不同,跨批次差值不能归因为纯共享约束。", + "方向、首跳身份与组合同时改善不能唯一定位MLP或证明方向对齐是必要条件。新知识迁移尚未开展。", + "", + f"科学训练段合计{summary['total_training_gpu_hours']:.4f}GPU小时;容器启动、评价和重载分配耗时另见controller-state.json。", + "逐题完整生成重计分、配对初值/世界/采样、逐事实曝光与独立重载均通过。W&B云端完成需另见tracking-cloud-audit.json。", + "", + ] + (target / "report.md").write_text("\n".join(text)) + plot(rows, histories, target) + print(json.dumps(dict(audited=len(rows), means=means, report=str(target)), ensure_ascii=False)) + + +def plot(rows, histories, target): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, axes = plt.subplots(1, 2, figsize=(10, 3.6), constrained_layout=True) + for ax, task, title in zip( + axes, + ["familiar_test", "strict_test"], + ["Familiar facts: held-out chains", "Facts with atomic training only"], + strict=True, + ): + for arm, color in [("bridge_ce", "#5973a6"), ("aligned", "#cf733c")]: + values = [] + for world in sorted({r["world"] for r in rows if r["phase"] == "confirmation"}): + subset = [ + r + for r in rows + if r["phase"] == "confirmation" and r["world"] == world and r["arm"] == arm + ] + if subset: + values.append( + np.mean( + [ + [p["metrics"][task]["accuracy"] for p in histories[r["name"]]] + for r in subset + ], + axis=0, + ) + ) + if values: + nodes = [p["step"] for p in histories[subset[0]["name"]]] + scores = 100 * np.asarray(values) + ax.plot(nodes, scores.mean(0), label=arm, color=color) + ax.fill_between(nodes, scores.min(0), scores.max(0), color=color, alpha=0.15) + ax.set( + title=title, + xlabel="Optimizer updates", + ylabel="Full generation accuracy (%)", + ylim=(0, 100), + ) + ax.grid(alpha=0.2) + axes[0].legend(frameon=False) + fig.savefig(target / "learning.png", dpi=180) + fig.savefig(target / "learning.pdf") + plt.close(fig) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path, required=True) + report(parser.parse_args().config) diff --git a/docs/development-artifacts/independent-alignment-v1/source/scripts/run_independent_alignment.py b/docs/development-artifacts/independent-alignment-v1/source/scripts/run_independent_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0cf7aadb4d33ac03b51b1016190d72cd0816b3 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-v1/source/scripts/run_independent_alignment.py @@ -0,0 +1,548 @@ +"""Freeze and execute a paired replication of state alignment in ordinary GPT.""" + +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 = "independent-alignment-v1" +ARTIFACT = REPOSITORY / "docs/development-artifacts" / BATCH +RESULTS = REPOSITORY / "results" / BATCH +SCRIPT = "scripts/run_independent_alignment.py" + + +def read(path): + return json.loads(Path(path).read_text()) + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def specifications(): + parent = read(REPOSITORY / "configs/representation-alignment-confirmation-v1.json") + base = next(s for s in parent["specs"] if s["arm"] == "bridge_ce") + result = [] + worlds = [(770011, "development", [771011])] + worlds += [ + (w, "confirmation", [107270821, 107270822]) for w in [107270811, 107270812, 107270813] + ] + for world, phase, initializations in worlds: + for initialization in initializations: + for arm, weight in [("bridge_ce", 0.0), ("aligned", 0.3)]: + spec = dict( + base, + layers=2, + repeats=1, + world=world, + phase=phase, + initialization=initialization, + arm=arm, + bridge_weight=0.3, + alignment_weight=weight, + ) + spec["name"] = f"{phase}-w{world}-i{initialization}-{arm}" + result.append(spec) + return result + + +def freeze(): + from llm_memory_editability.independent_alignment import validate_model + from llm_memory_editability.latent_scaling import build_world, data_digest, model_digest + from llm_memory_editability.representation_alignment import new_model + + destination = ARTIFACT / "source" + if destination.exists(): + raise FileExistsError(destination) + parent = read(REPOSITORY / "configs/representation-alignment-confirmation-v1.json") + scientific = [ + p for p in parent["source"] if p.startswith("src/") and "experiment_tracking" not in p + ] + assert all(sha(REPOSITORY / p) == parent["source"][p] for p in scientific) + specs = specifications() + for spec in specs: + model = new_model(spec, "cpu") + validate_model(spec, model) + spec.update( + initial_model_sha256=model_digest(model), + parameters=sum(p.numel() for p in model.parameters()), + data_sha256=data_digest(build_world(spec)), + ) + for world, initialization in {(s["world"], s["initialization"]) for s in specs}: + pair = [s for s in specs if (s["world"], s["initialization"]) == (world, initialization)] + assert len(pair) == 2 + assert len({s["initial_model_sha256"] for s in pair}) == 1 + assert len({s["data_sha256"] for s in pair}) == 1 + paths = [ + *REPOSITORY.glob("src/llm_memory_editability/*.py"), + REPOSITORY / SCRIPT, + REPOSITORY / "scripts/run_shared_cache_branch.py", + REPOSITORY / "scripts/report_independent_alignment.py", + REPOSITORY / "scripts/audit_independent_alignment_tracking.py", + REPOSITORY / "tests/test_independent_alignment.py", + REPOSITORY / "configs/experiment-tracking-defaults.json", + REPOSITORY / "configs/representation-alignment-confirmation-v1.json", + ARTIFACT / "protocol.md", + ARTIFACT / "literature-methods.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, + created_utc=utc(), + repository=str(REPOSITORY), + source_root=str(destination), + source=hashes, + git_commit=subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), + historical_scientific_sources_exact=True, + historical_config_sha256=sha( + REPOSITORY / "configs/representation-alignment-confirmation-v1.json" + ), + specs=specs, + gpus=list(range(8)), + runtime=read(REPOSITORY / "configs/composition-data-curves-v1.json")["runtime"], + maximum_run_seconds=1200, + maximum_engineering_seconds=300, + development_prerequisite=0.99, + updates=sum(s["steps"] for s in specs), + maximum_allocated_gpu_hours=6, + ) + write_json(ARTIFACT / "frozen-config.json", config) + write_json( + ARTIFACT / "execution-lock.json", dict(config_sha256=sha(ARTIFACT / "frozen-config.json")) + ) + print( + json.dumps( + {"runs": len(specs), "updates": config["updates"], "parameters": specs[0]["parameters"]} + ) + ) + + +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 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 preflight(spec, out): + import numpy as np + import torch + + from llm_memory_editability.grok_depth import make_optimizer + from llm_memory_editability.independent_alignment import validate_model + from llm_memory_editability.latent_scaling import build_world, model_digest + from llm_memory_editability.representation_alignment import ( + RepresentationStep, + new_model, + objective, + pack_training, + ) + + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + assert torch.cuda.device_count() == 1 + for dtype in (torch.float32, torch.bfloat16): + x = torch.randn(64, 64, device="cuda", dtype=dtype, requires_grad=True) + loss = (x @ x.T).float().square().mean() + loss.backward() + torch.cuda.synchronize() + assert torch.isfinite(loss) and torch.isfinite(x.grad).all() + model = new_model(spec, "cuda:0") + validate_model(spec, model) + initial = model_digest(model) + table = tuple(torch.as_tensor(a, device="cuda") for a in pack_training(build_world(spec))[0]) + lr = torch.tensor(spec["lr"], device="cuda") + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + graph = RepresentationStep(model, optimizer, table, spec["batch_size"], spec) + assert model_digest(model) == initial + index = torch.arange(spec["batch_size"], device="cuda") + graph(index) + reference = new_model(spec, "cuda:0") + other_lr = torch.tensor(spec["lr"], device="cuda") + other_opt = make_optimizer(reference, other_lr, spec["weight_decay"]) + other_opt.zero_grad(set_to_none=False) + loss, _ = objective( + reference, *(part[index] for part in table), spec["bridge_weight"], spec["alignment_weight"] + ) + loss.backward() + torch.nn.utils.clip_grad_norm_(reference.parameters(), 1.0, foreach=True) + other_opt.step() + error = max( + float((a - b).abs().max()) + for a, b in zip(model.parameters(), reference.parameters(), strict=True) + ) + assert error <= 1e-6, error + assert np.isfinite(error) + write_json( + out / "preflight.json", + dict( + passed=True, + cuda_computation=True, + fp32=True, + bf16=True, + graph_update_max_parameter_error=error, + independent_parameters=True, + torch=torch.__version__, + ), + ) + + +def train_or_audit(config, name, out, mode, engineering): + import torch + + from llm_memory_editability import independent_alignment as experiment + + spec = next(s for s in config["specs"] if s["name"] == name) + if engineering: + spec = dict(spec, steps=8, nodes=[0, 8]) + if mode == "preflight": + preflight(spec, out) + elif mode == "train": + experiment.train(spec, out, config["source"], torch.device("cuda:0")) + else: + experiment.audit(out, torch.device("cuda:0")) + + +def worker(config, name, out, engineering): + arguments = [ + "--config", + str(ARTIFACT / "frozen-config.json"), + "--name", + name, + "--out", + str(out), + ] + if engineering: + arguments.append("--engineering") + budget = config["maximum_engineering_seconds" if engineering else "maximum_run_seconds"] + began = time.monotonic() + try: + modes = ["preflight", "train", "audit"] if engineering else ["train", "audit"] + for mode in modes: + subprocess.run( + [sys.executable, "-u", str(Path(config["source_root"]) / SCRIPT), mode, *arguments], + check=True, + timeout=max(1, budget - (time.monotonic() - began)), + ) + write_json( + out / "worker-completion.json", + dict(passed=True, allocated_seconds=time.monotonic() - began), + ) + except BaseException: + write_json(out / "failure.json", dict(utc=utc(), traceback=traceback.format_exc())) + raise + + +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-independent-alignment-{'eng-' if engineering else ''}{gpu}-{name}" + cmd = [ + "docker", + "--context", + config["runtime"]["docker_context"], + "run", + "--name", + cname, + "--label", + "project=llm-memory-editability", + "--label", + "batch=" + BATCH, + "--label", + "run=" + name, + "--network=none", + "--gpus", + f"device={gpu}", + "--cpus", + str(config["runtime"]["cpus"]), + "--memory", + config["runtime"]["memory"], + "--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"] + "/" + SCRIPT, + "worker", + "--config", + str(ARTIFACT / "frozen-config.json"), + "--name", + name, + "--out", + str(out), + ] + if engineering: + cmd.append("--engineering") + write_json(out / "container-command.json", dict(command=cmd, gpu=gpu, container=cname)) + log = (out / "worker.log").open("a") + p = subprocess.Popen(cmd, stdout=log, stderr=subprocess.STDOUT) + for _ in range(30): + inspected = subprocess.run( + ["docker", "--context", "lm-memory", "inspect", cname], capture_output=True, text=True + ) + if inspected.returncode == 0: + info = json.loads(inspected.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 p, log, out, cname, spec + + +def prerequisite(config): + rows = [] + for spec in config["specs"]: + if spec["phase"] != "development": + continue + out = RESULTS / "runs" / spec["name"] + m = read(out / "complete.json")["metrics"] + d = read(out / "state-diagnostics.json") + values = [m[t]["accuracy"] for t in ["common_atomic", "train_composite"]] + values += [ + d[t]["first_hop_original_readout_accuracy"] for t in ["common_atomic", "strict_test"] + ] + rows.append( + dict( + name=spec["name"], + prerequisite_values=values, + passed=min(values) >= config["development_prerequisite"], + ) + ) + result = dict( + passed=all(r["passed"] for r in rows), + runs=rows, + composition_test_not_used=True, + recipe_not_reselected=True, + ) + write_json(RESULTS / "development-prerequisite.json", result) + return result["passed"] + + +def controller(config): + from run_shared_cache_branch import gpu_free + + 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("Existing execution history; do not silently restart") + for b in ["residual-cache-comparison-v1", "knowledge-change-v1"]: + previous = read(REPOSITORY / "results" / b / "controller-state.json") + assert previous["state"] == "complete" and not previous["active"] and not previous["queued"] + assert all(gpu_free(g) for g in config["gpus"]) + state = dict( + state="preflight", + started_utc=utc(), + completed=[], + failed=[], + active={}, + queued=[s["name"] for s in config["specs"]], + gpus=config["gpus"], + ) + write_json(RESULTS / "controller-state.json", state) + + def check(gpu): + job = container( + config, gpu, next(s for s in config["specs"] if s["arm"] == "aligned"), engineering=True + ) + code = job[0].wait() + job[1].close() + return code == 0 and read(job[2] / "audit.json")["passed"] + + with ThreadPoolExecutor(max_workers=8) as pool: + checks = list(pool.map(check, config["gpus"])) + write_json( + RESULTS / "preflight.json", dict(passed=all(checks), checks=checks, gpus=config["gpus"]) + ) + if not all(checks): + state.update(state="finished_with_failures", reason="engineering_preflight") + write_json(RESULTS / "controller-state.json", state) + return + 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", + ] + with (RESULTS / "tracking.log").open("a") as log: + tracker = subprocess.Popen( + cmd, stdout=log, stderr=subprocess.STDOUT, env=environment(config) + ) + write_json(RESULTS / "tracking-process.json", dict(pid=tracker.pid, command=cmd)) + allocated = 0.0 + for phase in ["development", "confirmation"]: + pending = [s for s in config["specs"] if s["phase"] == phase] + active = {} + state.update(state="running", phase=phase) + while pending or active: + for gpu, (p, log, out, _cname, spec) in list(active.items()): + if p.poll() is None: + continue + 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"]) + if ok: + allocated += read(out / "worker-completion.json")["allocated_seconds"] / 3600 + 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): + spec = pending.pop(0) + active[gpu] = container(config, gpu, 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] + + ( + [s["name"] for s in config["specs"] if s["phase"] == "confirmation"] + if phase == "development" + else [] + ), + updated_utc=utc(), + completed_allocated_gpu_hours=allocated, + ) + write_json(RESULTS / "controller-state.json", state) + time.sleep(2) + if state["failed"]: + break + if phase == "development" and not prerequisite(config): + state.update(state="development_prerequisite_not_met", active={}, finished_utc=utc()) + write_json(RESULTS / "controller-state.json", state) + return + report = subprocess.run( + [ + sys.executable, + config["source_root"] + "/scripts/report_independent_alignment.py", + "--config", + str(ARTIFACT / "frozen-config.json"), + ], + env=environment(config), + ) + state.update( + state="finished_with_failures" if state["failed"] or report.returncode else "complete", + active={}, + queued=[], + 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") + cmd = [ + sys.executable, + "-u", + config["source_root"] + "/" + SCRIPT, + "controller", + "--config", + str(args.config), + ] + with (RESULTS / "controller.log").open("a") as log: + p = subprocess.Popen( + cmd, + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + env=environment(config), + ) + write_json(RESULTS / "controller-process.json", dict(pid=p.pid, command=cmd, 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) + else: + train_or_audit(config, args.name, args.out, args.mode, args.engineering) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/independent-alignment-v1/source/scripts/run_shared_cache_branch.py b/docs/development-artifacts/independent-alignment-v1/source/scripts/run_shared_cache_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..fd33eb97319d8da67952a81c5a976946e33f81fa --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/__init__.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c606cfd654948ec99bedce5244b7c6608a801a1d --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/__main__.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..860f4f8babf02fc2d6920b26bf4ac11a3e254766 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/alignment_coverage.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/alignment_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..6efacd7bf323dd87ad027292dee80a9f665032fa --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/architecture_bridge.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/architecture_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..3d611f12f7be01721c8f453b8981605455e4b585 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/architecture_bridge_toy.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/architecture_bridge_toy.py new file mode 100644 index 0000000000000000000000000000000000000000..a406337c9f1b455c1c07183ec90de18541f7d03b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_analysis.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae07fb7fccdec9430d5e69bc1b304a9fcebe914 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_branch.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c6ebef8f0f501ac43d2d94de8f4f59b954208b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_capacity.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_capacity.py new file mode 100644 index 0000000000000000000000000000000000000000..d07d84eb1c19bc5055e15255b0de00799b8713c5 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_causal_paths.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_causal_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2d8963ce2c5db80362fdd38cc80e83c8415b53 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_confirmation_stats.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_confirmation_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..27d0d82cc96b250b88771946b569218a090bee50 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_context_control.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_context_control.py new file mode 100644 index 0000000000000000000000000000000000000000..26c20f349951ff08ba251e2e61c158ad8f4c0f85 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_context_gradient.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_context_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..89f78f244a71569026fd75d76ac6b10b702fed9d --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_cross.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..960ef7e03dd29b834df68149d8aca7cbcd077a10 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_cross_continue.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_cross_continue.py new file mode 100644 index 0000000000000000000000000000000000000000..df0a21278c640164306e05b7465e24cc0e6d0df8 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_cross_scale.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_cross_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..af5c92edca554475a9bdf9dee9b46438455b1f96 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_cross_train.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_cross_train.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5f3f45a169e643c408f1044eaa766b79a595fd --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_data.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3acf9b51a11985eb747a2c2565bc551ae803fd9b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_direction.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_direction.py new file mode 100644 index 0000000000000000000000000000000000000000..15e8d1db07bd56a73048608a8d9dfb99e5737a7a --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_direction_cross.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_direction_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..27051c00db64d66676d95dc16a1351dff5d797a6 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_direction_formation.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_direction_formation.py new file mode 100644 index 0000000000000000000000000000000000000000..96a3aa141c344b0fea47995c861792eb5d95398a --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_direction_refresh.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_direction_refresh.py new file mode 100644 index 0000000000000000000000000000000000000000..5f48462e2c66886ef8e483fa7e48986d075ad3fb --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_edit.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..685a33d6157d090f0afdfaa38b5c2d731eda4d0e --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_followup.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..c90b76331ad0bbd37276b4a9fe14b865360e7a60 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_measure.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_measure.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf7c45f10b2be179635d21d0f3a7fde2ee6ca6c --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_mechanism_causal.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_mechanism_causal.py new file mode 100644 index 0000000000000000000000000000000000000000..8ac824d1ef628725bf1ee9ca778d381516508a80 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..322ecd4a965475d9878cbb14cb7a3eee131cf9ca --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_mechanism_edit.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_mechanism_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..6e51c693528d73250f62b70686f96b42b7eb9e4f --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py new file mode 100644 index 0000000000000000000000000000000000000000..4d87971e01bb7f679239d58f88ea4ac1b054eb88 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_model.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7190d562883dec0d900e7ac14e894975f76499fb --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_organization.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_organization.py new file mode 100644 index 0000000000000000000000000000000000000000..a64a674326bdc2e7202a987e0ac941b40640d912 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_organization_train.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_organization_train.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5d2bba261629aecc04944afd599bb827c634a8 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_original_data.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_original_data.py new file mode 100644 index 0000000000000000000000000000000000000000..98352c46d29112ab2ac2be7212204897c13aea18 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_original_diagnostics.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_original_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..dc0de9f1aeb4e6e8a48ea33b265811985ebea4d8 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_original_model.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_original_model.py new file mode 100644 index 0000000000000000000000000000000000000000..039ceaef72cf7fefa38bb094dbefbe9f7e88d651 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_original_report.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_original_report.py new file mode 100644 index 0000000000000000000000000000000000000000..8aace2494390c65045a2d379beb42695d3b84c8e --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_original_train.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_original_train.py new file mode 100644 index 0000000000000000000000000000000000000000..eea8f0449758025224fd3bb37444cc7e54e7ef7c --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_path_diagnostics.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_path_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..219336bcde27c897b81d6c253255dca79eb11d1c --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_path_minimal.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_path_minimal.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2ed53451de1a88abe78ee5e58cb49745597c2b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_path_transfer.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_path_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..0c54e9cfda468b9a153577dd716a037dde1577f1 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_readout_control.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_readout_control.py new file mode 100644 index 0000000000000000000000000000000000000000..877089e7e83d985cfb9e4b5e65920b2db8312d4d --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_relation_response.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_relation_response.py new file mode 100644 index 0000000000000000000000000000000000000000..2e69b15143ef5b90779481035823b06102c3b5ab --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..3943eb3bac42c3c9c13d8b3c40061fc830348860 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py new file mode 100644 index 0000000000000000000000000000000000000000..8535796aba3f18178d69d214c04bc922b0dfa21d --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_shortcut_control.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_shortcut_control.py new file mode 100644 index 0000000000000000000000000000000000000000..60ee531b9c2a08e1cf2cfba210a312300b93480d --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_shortcut_edit.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_shortcut_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..856a9a8a4fd753c498c4b965d5c30a057bdebffd --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..52dd3441331f501688eedfe95286f26462de3625 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..684e672ca551a48aacb2f4bc81db94092282f4cf --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bios_train.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bios_train.py new file mode 100644 index 0000000000000000000000000000000000000000..958bf5b4de4feec20d76d07a5d28016fec584d7a --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bridge_reencoding.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bridge_reencoding.py new file mode 100644 index 0000000000000000000000000000000000000000..1dbbe769879cff4d2b00a6c39164102b50d035e3 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/bridge_workspace.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/bridge_workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3ee68821631607b4922cfce3654cd2784d82ba --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/capacity_controls.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/capacity_controls.py new file mode 100644 index 0000000000000000000000000000000000000000..3806e6b81fda1ae9bc25fd74e38f846ddd3a456d --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/capacity_scaling.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/capacity_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c152e8710de107c8fb2f4ba2275cdea5cbdcf3 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/cli.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..1aec4627fdf91a196893b3a6d47c8188da55d55b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/composition_curves.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/composition_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..13009dcfa856d01722da32842dcc3a7fe078a635 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/curve_tracking.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/curve_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..526a40aecb32ed282e9de766f3162546d80403ac --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/depth_step.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/depth_step.py new file mode 100644 index 0000000000000000000000000000000000000000..8f828c9ccea5c225dd4fc257587afe3c0ff7c6bf --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..fc14c085184dc030670f1eea92655b73d0eec7c8 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/depth_step_mechanism.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/depth_step_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb78cafec65ea5b0a4031d27502f7d0c4b00e16 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/experiment_tracking.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/experiment_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..167c8e1a359008fa8b7c89642273e85c9699643e --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/experiments.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/experiments.py new file mode 100644 index 0000000000000000000000000000000000000000..21513c79efc2f2e137213ca20f5444209e6d313d --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_depth.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grok_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb93ea353cb12f972942a3cf658bc6593f81bb7 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_depth_bridge.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grok_depth_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..ca05be9fcd170cee34075ae1aa2fa0c2bcca1e2c --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_depth_data.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grok_depth_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8696c3ffe204466f57619157a3f47739f899c6c4 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_loop_data.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grok_loop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..18cae2dbd6dfdd997883935619a80811eede27d0 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_loop_mechanism.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grok_loop_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd1ad614952efa432b820d8f26f1e282657a947 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_loop_model.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grok_loop_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed46483cb7277c172f8848cefb9e2d085d67c0b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f3cac329831b303c1dc9ca05c270837de0614eec --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py b/docs/development-artifacts/independent-alignment-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/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_loop_supervision.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grok_loop_supervision.py new file mode 100644 index 0000000000000000000000000000000000000000..104364e93299229e1a8216acabb046e5fae1dde4 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_loop_train.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grok_loop_train.py new file mode 100644 index 0000000000000000000000000000000000000000..ffee809fcc7335c7b68e3321427ffcc0342c3086 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_multihop.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grok_multihop.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0824b5e038658e91c3cbc5e521a316861f20a4 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_multihop_data.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grok_multihop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d857233765485dc4bf1a210fda171628a20d9817 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_usage_data.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grok_usage_data.py new file mode 100644 index 0000000000000000000000000000000000000000..04e5650b0bdea1e25cfde235045efc9b14e0c769 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grok_usage_train.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grok_usage_train.py new file mode 100644 index 0000000000000000000000000000000000000000..8460dcf149ad8f229cc4c16783e8e7429acd0610 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..9530969731263b69c576f12989a3610ead6036f5 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/grokking_reproduction.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/grokking_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f7ba958ea469d5edea6e98c9941dcc49427a6f --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/hebbian_data.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/hebbian_data.py new file mode 100644 index 0000000000000000000000000000000000000000..b67eee718fd00d44c1de51a2821e24aa7251196b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/hebbian_followup.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/hebbian_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..89afed17153ba18880997b4089ddadb1b997f80b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/hebbian_future.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/hebbian_future.py new file mode 100644 index 0000000000000000000000000000000000000000..24171d0e5bc0c31f7cc4ac32af06d86dd8ec15f4 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/hebbian_interface.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/hebbian_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..0135ee958b76df5e2df2aa4ea0c2c57c40f2b24a --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/hebbian_learning.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/hebbian_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..78155602739f614f369304edc920dbb75b590bea --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/hebbian_model.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/hebbian_model.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8e5da864f18f673c829d8b68db641d728ca437 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/hebbian_statistics.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/hebbian_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..52bcc965886f86bf20041ec40ce6aa95b96a725f --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/hebbian_train.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/hebbian_train.py new file mode 100644 index 0000000000000000000000000000000000000000..f70905fa1648aeba1d7bad8aca55a77bbcadd72f --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/independent_alignment.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/independent_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..88bc143ff025e794e6a5f1ec62e514b99563d88b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/interface_editing.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/interface_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..7065e910e82f4aa54e312af63f4f99925c4e1269 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/interface_tracking.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/interface_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d7812ba16f84199f575a2c6eb88ba64a6bf26d --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/knowledge_change.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/knowledge_change.py new file mode 100644 index 0000000000000000000000000000000000000000..1481d60ac7e43d3617f38f6ca360b241dca20b70 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/latent_scaling.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/latent_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..7abd21f4255e3f7de35ecee337ed09d32da707ff --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/latent_support.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/latent_support.py new file mode 100644 index 0000000000000000000000000000000000000000..4b307c09f7a1fe633c634ae39b3a83e964675355 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/low_rank.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/low_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..3a58bee0d460cb3ae042e17d22b7132b2035bd4b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/memory_reuse.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/memory_reuse.py new file mode 100644 index 0000000000000000000000000000000000000000..89520ed7649557ad7e4cfc2611ac85b8d9db8396 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/multihop_scaling.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/multihop_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..64b5a3d67ef6bab20c60904e626e811876d72279 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/natural_composition_confirmation.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/natural_composition_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9608e59339683c91de69b2f1f392b93b8f0171 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e949ff27eac75a758644d6a7ffd81f2a9477ea --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/neural.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/neural.py new file mode 100644 index 0000000000000000000000000000000000000000..ce1f02e8195f4e583817b3781b044f021a41fbfb --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/neural_data.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/neural_data.py new file mode 100644 index 0000000000000000000000000000000000000000..555b2a06a7db0805d441a3f8f89bc2100deaa72a --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/neural_models.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/neural_models.py new file mode 100644 index 0000000000000000000000000000000000000000..448b3499cdce6fac7d4bcac1e60883f4c383df82 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/parametric_architecture.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/parametric_architecture.py new file mode 100644 index 0000000000000000000000000000000000000000..a254bf6f90931d21d80c57972a6770ad6665c13a --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/parametric_architecture_train.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/parametric_architecture_train.py new file mode 100644 index 0000000000000000000000000000000000000000..55c77a2f48a116b87a2159b90bb2ab76a6730887 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/qwen_constraints.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/qwen_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..6181f6dad22ab1a99443ffddb19f67c7c6ad701b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/qwen_path_learning.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/qwen_path_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..bc113a47da9c9fc22e346812c7f48f5ae7bc8b92 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/qwen_path_train.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/qwen_path_train.py new file mode 100644 index 0000000000000000000000000000000000000000..fabb31112396100c708fafd83993acdb8c46f918 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/realworld_composition.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/realworld_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..a05d1c9d956093315cedab365228e2fce72b6022 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/realworld_composition_data.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/realworld_composition_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e907ece415c9c6e027e965818c1b8e6f82a2462e --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/realworld_confirmation.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/realworld_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..5cfed1010e1cc6f386e54d10c69675d34f4bed4a --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..1b6fcadbe2e7be2944fe6e398e29c0812ca1329f --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/recurrence_use.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/recurrence_use.py new file mode 100644 index 0000000000000000000000000000000000000000..3f2cf4432769a0bc1ea0278bf25468307718877b --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/representation_alignment.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/representation_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..923e412fdf09bfaf85ca6de1fcb11cf4d6e754de --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/residual_cache.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/residual_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..20f4f21ac38bfedf6fa1d48968333c80c07f06ea --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/shared_cache.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/shared_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf5aec02ab0270e60a6c41882c24bdd4b3d34cc --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/small_lm_composition.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/small_lm_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..f7bc9b1ea8e7d825eb5f27c33bb4d7e38bb7bcc1 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/small_lm_followup.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/small_lm_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..4c986ea475b4f0abe83ea3d0411a049344ac0e08 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/storage_composition.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/storage_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..094211c26edecbed2a534bad16c84c42b2cdebd0 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/storage_frontier.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/storage_frontier.py new file mode 100644 index 0000000000000000000000000000000000000000..db36e560aed8b173bb72c836b3d02dc8381bbcc5 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/text_loss_source.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/text_loss_source.py new file mode 100644 index 0000000000000000000000000000000000000000..6f9377848d4673a2937273cf26a33f8e859874d0 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/text_pretrain.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/text_pretrain.py new file mode 100644 index 0000000000000000000000000000000000000000..2682a0925a00e0e8b0eef3781521830d891ef9d7 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/text_structure.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/text_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c74f97848144e288267dedd2df039a1f8c1a52 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/src/llm_memory_editability/twohop_depth.py b/docs/development-artifacts/independent-alignment-v1/source/src/llm_memory_editability/twohop_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..19b9a4b76eadef68acf7603b8434567145244311 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-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/independent-alignment-v1/source/tests/test_independent_alignment.py b/docs/development-artifacts/independent-alignment-v1/source/tests/test_independent_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..769d6c53c3871c44198276cd3b20c16d81d47e76 --- /dev/null +++ b/docs/development-artifacts/independent-alignment-v1/source/tests/test_independent_alignment.py @@ -0,0 +1,126 @@ +"""Contracts that distinguish ordinary-layer replication from shared computation.""" + +import importlib.util +from pathlib import Path + +import numpy as np +import pytest +import torch + +from llm_memory_editability.grok_depth import SmallGPT +from llm_memory_editability.independent_alignment import diagnose, validate_model +from llm_memory_editability.latent_scaling import build_world, model_digest +from llm_memory_editability.representation_alignment import new_model, objective, pack_training + + +def small_spec(): + return dict( + world=107270899, + initialization=107270898, + stream_seed=776101, + 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=32, + heads=4, + layers=2, + repeats=1, + dropout=0.0, + ) + + +def test_independent_storage_and_forward_equal_ordinary_small_gpt(): + spec = small_spec() + model = new_model(spec, "cpu") + validate_model(spec, model) + torch.manual_seed(spec["initialization"]) + reference = SmallGPT(model.config, dropout=0.0) + assert model_digest(model) == model_digest(reference) + tokens = torch.tensor([[2, 21, 3, 13, 3, 17, 4, 65]]) + torch.testing.assert_close(model(tokens), reference(tokens), atol=0, rtol=0) + _, before = model(tokens, return_bridge=True) + with torch.no_grad(): + model.blocks[1].mlp.down.weight.add_(0.1) + _, after = model(tokens, return_bridge=True) + torch.testing.assert_close(before, after, atol=0, rtol=0) + + +def test_shared_model_rejected(): + spec = dict(small_spec(), layers=1, repeats=2) + with pytest.raises(ValueError): + validate_model(spec, new_model(spec, "cpu")) + + +def test_first_layer_state_has_no_future_information(): + model = new_model(small_spec(), "cpu") + a = torch.tensor([[2, 21, 3, 13, 3, 17, 4, 65]]) + b = torch.tensor([[2, 21, 3, 13, 4, 20, 5, 67]]) + _, x = model(a, return_bridge=True) + _, y = model(b, return_bridge=True) + _, prefix = model(a[:, :4], return_bridge=True) + torch.testing.assert_close(x, y, atol=0, rtol=0) + torch.testing.assert_close(x, prefix, atol=2e-7, rtol=2e-6) + + +def test_strict_atoms_have_no_composition_training_and_aux_labels_match(): + world = build_world(small_spec()) + trained = {(int(h), int(r1), int(b)) for h, r1, b, r2, t in world["train_composite"]} + trained |= {(int(b), int(r2), int(t)) for h, r1, b, r2, t in world["train_composite"]} + strict = {(int(h), int(r1), int(b)) for h, r1, b, r2, t in world["strict_test"]} + strict |= {(int(b), int(r2), int(t)) for h, r1, b, r2, t in world["strict_test"]} + assert not strict & trained + assert strict <= set(map(tuple, world["common_atomic"])) + (tokens, labels, targets), sizes = pack_training(world) + first, last = sizes[0], sizes[0] + sizes[1] + np.testing.assert_array_equal(targets[first:last], world["train_composite"][:, 2]) + assert not np.any(tokens[first:last] == targets[first:last, None]) + + +def test_alignment_only_changes_the_specified_geometric_term(): + model = new_model(small_spec(), "cpu") + arrays, _ = pack_training(build_world(small_spec())) + batch = [torch.as_tensor(a[:8]) for a in arrays] + ce, parts = objective(model, *batch, 0.3, 0.0) + aligned, other = objective(model, *batch, 0.3, 0.3) + torch.testing.assert_close(parts, other, atol=0, rtol=0) + torch.testing.assert_close(aligned - ce, 0.3 * parts[2], atol=1e-6, rtol=1e-6) + + +def test_pure_prefix_diagnostic_does_not_use_final_answers(): + model = new_model(small_spec(), "cpu") + world = build_world(small_spec()) + _, prediction = diagnose(model, world, "cpu") + other = {k: v.copy() for k, v in world.items()} + for task in ["familiar_test", "strict_test"]: + other[task][:, 3:] += 1 + _, altered = diagnose(model, other, "cpu") + for key, value in prediction.items(): + np.testing.assert_array_equal(value, altered[key]) + + +def test_matrix_is_two_same_label_arms_on_three_fresh_worlds(): + path = Path(__file__).parents[1] / "scripts/run_independent_alignment.py" + loader = importlib.util.spec_from_file_location("independent_runner", path) + script = importlib.util.module_from_spec(loader) + loader.loader.exec_module(script) + specs = script.specifications() + assert len(specs) == 14 + confirmation = [s for s in specs if s["phase"] == "confirmation"] + assert len(confirmation) == 12 + assert len({s["world"] for s in confirmation}) == 3 + assert not {s["world"] for s in confirmation} & {774101, 774102, 774103, 770011} + for world, initialization in {(s["world"], s["initialization"]) for s in specs}: + pair = [s for s in specs if (s["world"], s["initialization"]) == (world, initialization)] + a, b = pair + for k in a.keys() - {"arm", "name", "alignment_weight"}: + assert a[k] == b[k], k + assert a["layers"] == 2 and a["repeats"] == 1 + assert a["steps"] == 16000 + assert a["bridge_weight"] == 0.3 + assert {a["alignment_weight"], b["alignment_weight"]} == {0.0, 0.3} diff --git a/docs/development-artifacts/knowledge-change-v1/execution-lock.json b/docs/development-artifacts/knowledge-change-v1/execution-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..1c3022d060931bb6a31c8e8cb6a579d33ed2925a --- /dev/null +++ b/docs/development-artifacts/knowledge-change-v1/execution-lock.json @@ -0,0 +1,3 @@ +{ + "config_sha256": "db439eba1d928a39d1cd8bec037a6f30ee64bc2560991666f10995a8bf7c4743" +} diff --git a/docs/development-artifacts/knowledge-change-v1/frozen-config.json b/docs/development-artifacts/knowledge-change-v1/frozen-config.json new file mode 100644 index 0000000000000000000000000000000000000000..2fabe340e3b5dd320b689e9fc6c77141bd860588 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-v1/frozen-config.json @@ -0,0 +1,25268 @@ +{ + "batch": "knowledge-change-v1", + "source_root": "/ossfs/workspace/llm-memory-editability/docs/development-artifacts/knowledge-change-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": "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/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_knowledge_change.py": "8674408e8a4101445bdeb1d28e39299486e7b0ad106af7f57d032348e4c884c0", + "scripts/report_knowledge_change.py": "521828860a1c5dad0fd76e0c0c0944dd2a1c718445727d17d92b8da2360370da", + "tests/test_knowledge_change.py": "02c32ee9bc8d97430743be648db36aa25077bcfdb4411875e75b357f76a23308", + "configs/experiment-tracking-defaults.json": "41d4b73b9d2f57f71fe51dd8500275f2c9fb3476ec24a9eeee3a8deadb5ecaa2", + "docs/development-artifacts/knowledge-change-v1/protocol.md": "1735c6b74cc9505ed01f4afbd2db54efc5e81435a2656bef7cc197386c293e95" + }, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "development", + "memory_arm": "local", + "window": 2, + "name": "base-w730011-local", + "job_type": "base", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9", + "reuse_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w730011-local-r4", + "reuse_checkpoint_sha256": "68c7abcd9d8a1ebe1e0df770d1deba28e376aa79fcdfaf1fd5d210f4111170fb" + }, + { + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "development", + "memory_arm": "local", + "window": 2, + "name": "w730011-local-fixed", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9", + "reuse_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w730011-local-r4", + "reuse_checkpoint_sha256": "68c7abcd9d8a1ebe1e0df770d1deba28e376aa79fcdfaf1fd5d210f4111170fb", + "training_arm": "fixed", + "parent_name": "base-w730011-local", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w730011-local", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "6c3f7498c9167c83aed0f282243f1beb104f16bd74223b43c7b31303e71cc7d9" + }, + { + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "development", + "memory_arm": "local", + "window": 2, + "name": "w730011-local-changed_atomic", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9", + "reuse_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w730011-local-r4", + "reuse_checkpoint_sha256": "68c7abcd9d8a1ebe1e0df770d1deba28e376aa79fcdfaf1fd5d210f4111170fb", + "training_arm": "changed_atomic", + "parent_name": "base-w730011-local", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w730011-local", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "6c3f7498c9167c83aed0f282243f1beb104f16bd74223b43c7b31303e71cc7d9" + }, + { + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "development", + "memory_arm": "local", + "window": 2, + "name": "w730011-local-changed_use", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9", + "reuse_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w730011-local-r4", + "reuse_checkpoint_sha256": "68c7abcd9d8a1ebe1e0df770d1deba28e376aa79fcdfaf1fd5d210f4111170fb", + "training_arm": "changed_use", + "parent_name": "base-w730011-local", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w730011-local", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "6c3f7498c9167c83aed0f282243f1beb104f16bd74223b43c7b31303e71cc7d9" + }, + { + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "development", + "memory_arm": "shared_full", + "window": 2, + "name": "base-w730011-shared_full", + "job_type": "base", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9", + "reuse_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w730011-shared_full-r4", + "reuse_checkpoint_sha256": "362969102b7b13e87ac26f3ae86a3b5039b7c470d98bd8f83c293b6067ef91f5" + }, + { + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "development", + "memory_arm": "shared_full", + "window": 2, + "name": "w730011-shared_full-fixed", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9", + "reuse_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w730011-shared_full-r4", + "reuse_checkpoint_sha256": "362969102b7b13e87ac26f3ae86a3b5039b7c470d98bd8f83c293b6067ef91f5", + "training_arm": "fixed", + "parent_name": "base-w730011-shared_full", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w730011-shared_full", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "6c3f7498c9167c83aed0f282243f1beb104f16bd74223b43c7b31303e71cc7d9" + }, + { + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "development", + "memory_arm": "shared_full", + "window": 2, + "name": "w730011-shared_full-changed_atomic", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9", + "reuse_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w730011-shared_full-r4", + "reuse_checkpoint_sha256": "362969102b7b13e87ac26f3ae86a3b5039b7c470d98bd8f83c293b6067ef91f5", + "training_arm": "changed_atomic", + "parent_name": "base-w730011-shared_full", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w730011-shared_full", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "6c3f7498c9167c83aed0f282243f1beb104f16bd74223b43c7b31303e71cc7d9" + }, + { + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "development", + "memory_arm": "shared_full", + "window": 2, + "name": "w730011-shared_full-changed_use", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "866da959a56c3118a07caf06dcfbc4fd8762409721ba715b31c8eea724168010", + "parameters": 1011072, + "data_sha256": "b1fa824de465372cfd2afef1200f5beaa8ea86c42676e9f1cb4835c32fcdb4c9", + "reuse_dir": "/ossfs/workspace/llm-memory-editability/results/shared-cache-branch-v1/runs/w730011-shared_full-r4", + "reuse_checkpoint_sha256": "362969102b7b13e87ac26f3ae86a3b5039b7c470d98bd8f83c293b6067ef91f5", + "training_arm": "changed_use", + "parent_name": "base-w730011-shared_full", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w730011-shared_full", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "6c3f7498c9167c83aed0f282243f1beb104f16bd74223b43c7b31303e71cc7d9" + }, + { + "world": 107270011, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "base-w107270011-local", + "job_type": "base", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "16032b93c1f2fb66a35d3b8a7cd3c2151cfe0a8a03f8a49fdce6f42d81aad405" + }, + { + "world": 107270011, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "w107270011-local-fixed", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "16032b93c1f2fb66a35d3b8a7cd3c2151cfe0a8a03f8a49fdce6f42d81aad405", + "training_arm": "fixed", + "parent_name": "base-w107270011-local", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270011-local", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "426bed95acdccf92f17b90d3cc02459675ea39987734cb7c9aa3a267f5489b02" + }, + { + "world": 107270011, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "w107270011-local-changed_atomic", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "16032b93c1f2fb66a35d3b8a7cd3c2151cfe0a8a03f8a49fdce6f42d81aad405", + "training_arm": "changed_atomic", + "parent_name": "base-w107270011-local", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270011-local", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "426bed95acdccf92f17b90d3cc02459675ea39987734cb7c9aa3a267f5489b02" + }, + { + "world": 107270011, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "w107270011-local-changed_use", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "16032b93c1f2fb66a35d3b8a7cd3c2151cfe0a8a03f8a49fdce6f42d81aad405", + "training_arm": "changed_use", + "parent_name": "base-w107270011-local", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270011-local", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "426bed95acdccf92f17b90d3cc02459675ea39987734cb7c9aa3a267f5489b02" + }, + { + "world": 107270011, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "base-w107270011-shared_full", + "job_type": "base", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "16032b93c1f2fb66a35d3b8a7cd3c2151cfe0a8a03f8a49fdce6f42d81aad405" + }, + { + "world": 107270011, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "w107270011-shared_full-fixed", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "16032b93c1f2fb66a35d3b8a7cd3c2151cfe0a8a03f8a49fdce6f42d81aad405", + "training_arm": "fixed", + "parent_name": "base-w107270011-shared_full", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270011-shared_full", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "426bed95acdccf92f17b90d3cc02459675ea39987734cb7c9aa3a267f5489b02" + }, + { + "world": 107270011, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "w107270011-shared_full-changed_atomic", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "16032b93c1f2fb66a35d3b8a7cd3c2151cfe0a8a03f8a49fdce6f42d81aad405", + "training_arm": "changed_atomic", + "parent_name": "base-w107270011-shared_full", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270011-shared_full", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "426bed95acdccf92f17b90d3cc02459675ea39987734cb7c9aa3a267f5489b02" + }, + { + "world": 107270011, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "w107270011-shared_full-changed_use", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "16032b93c1f2fb66a35d3b8a7cd3c2151cfe0a8a03f8a49fdce6f42d81aad405", + "training_arm": "changed_use", + "parent_name": "base-w107270011-shared_full", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270011-shared_full", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "426bed95acdccf92f17b90d3cc02459675ea39987734cb7c9aa3a267f5489b02" + }, + { + "world": 107270012, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "base-w107270012-local", + "job_type": "base", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "a8b1fb5ec7043d4916d1979ab818db4fcf075ef0bd0108db0ee8e399a826bf66" + }, + { + "world": 107270012, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "w107270012-local-fixed", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "a8b1fb5ec7043d4916d1979ab818db4fcf075ef0bd0108db0ee8e399a826bf66", + "training_arm": "fixed", + "parent_name": "base-w107270012-local", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270012-local", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "330ac41fa8d9e6742daaf1487bd1bf0efc0226479d78e398fbc19f3ce11f5b82" + }, + { + "world": 107270012, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "w107270012-local-changed_atomic", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "a8b1fb5ec7043d4916d1979ab818db4fcf075ef0bd0108db0ee8e399a826bf66", + "training_arm": "changed_atomic", + "parent_name": "base-w107270012-local", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270012-local", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "330ac41fa8d9e6742daaf1487bd1bf0efc0226479d78e398fbc19f3ce11f5b82" + }, + { + "world": 107270012, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "w107270012-local-changed_use", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "a8b1fb5ec7043d4916d1979ab818db4fcf075ef0bd0108db0ee8e399a826bf66", + "training_arm": "changed_use", + "parent_name": "base-w107270012-local", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270012-local", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "330ac41fa8d9e6742daaf1487bd1bf0efc0226479d78e398fbc19f3ce11f5b82" + }, + { + "world": 107270012, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "base-w107270012-shared_full", + "job_type": "base", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "a8b1fb5ec7043d4916d1979ab818db4fcf075ef0bd0108db0ee8e399a826bf66" + }, + { + "world": 107270012, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "w107270012-shared_full-fixed", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "a8b1fb5ec7043d4916d1979ab818db4fcf075ef0bd0108db0ee8e399a826bf66", + "training_arm": "fixed", + "parent_name": "base-w107270012-shared_full", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270012-shared_full", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "330ac41fa8d9e6742daaf1487bd1bf0efc0226479d78e398fbc19f3ce11f5b82" + }, + { + "world": 107270012, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "w107270012-shared_full-changed_atomic", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "a8b1fb5ec7043d4916d1979ab818db4fcf075ef0bd0108db0ee8e399a826bf66", + "training_arm": "changed_atomic", + "parent_name": "base-w107270012-shared_full", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270012-shared_full", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "330ac41fa8d9e6742daaf1487bd1bf0efc0226479d78e398fbc19f3ce11f5b82" + }, + { + "world": 107270012, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "w107270012-shared_full-changed_use", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "a8b1fb5ec7043d4916d1979ab818db4fcf075ef0bd0108db0ee8e399a826bf66", + "training_arm": "changed_use", + "parent_name": "base-w107270012-shared_full", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270012-shared_full", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "330ac41fa8d9e6742daaf1487bd1bf0efc0226479d78e398fbc19f3ce11f5b82" + }, + { + "world": 107270013, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "base-w107270013-local", + "job_type": "base", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "39bd3cae652d3229dd0e89875c0c0c5868567cfa6a5df37d694e4c737a9b85d0" + }, + { + "world": 107270013, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "w107270013-local-fixed", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "39bd3cae652d3229dd0e89875c0c0c5868567cfa6a5df37d694e4c737a9b85d0", + "training_arm": "fixed", + "parent_name": "base-w107270013-local", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270013-local", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "3514be23bd5bcb1421a7a84b6b2f4fb55abf0b8b1e2050af68c9d00c10baabb4" + }, + { + "world": 107270013, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "w107270013-local-changed_atomic", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "39bd3cae652d3229dd0e89875c0c0c5868567cfa6a5df37d694e4c737a9b85d0", + "training_arm": "changed_atomic", + "parent_name": "base-w107270013-local", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270013-local", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "3514be23bd5bcb1421a7a84b6b2f4fb55abf0b8b1e2050af68c9d00c10baabb4" + }, + { + "world": 107270013, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "local", + "window": 2, + "name": "w107270013-local-changed_use", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "39bd3cae652d3229dd0e89875c0c0c5868567cfa6a5df37d694e4c737a9b85d0", + "training_arm": "changed_use", + "parent_name": "base-w107270013-local", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270013-local", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "3514be23bd5bcb1421a7a84b6b2f4fb55abf0b8b1e2050af68c9d00c10baabb4" + }, + { + "world": 107270013, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "base-w107270013-shared_full", + "job_type": "base", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "39bd3cae652d3229dd0e89875c0c0c5868567cfa6a5df37d694e4c737a9b85d0" + }, + { + "world": 107270013, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "w107270013-shared_full-fixed", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "39bd3cae652d3229dd0e89875c0c0c5868567cfa6a5df37d694e4c737a9b85d0", + "training_arm": "fixed", + "parent_name": "base-w107270013-shared_full", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270013-shared_full", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "3514be23bd5bcb1421a7a84b6b2f4fb55abf0b8b1e2050af68c9d00c10baabb4" + }, + { + "world": 107270013, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "w107270013-shared_full-changed_atomic", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "39bd3cae652d3229dd0e89875c0c0c5868567cfa6a5df37d694e4c737a9b85d0", + "training_arm": "changed_atomic", + "parent_name": "base-w107270013-shared_full", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270013-shared_full", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "3514be23bd5bcb1421a7a84b6b2f4fb55abf0b8b1e2050af68c9d00c10baabb4" + }, + { + "world": 107270013, + "initialization": 107270021, + "stream_seed": 107270031, + "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, + 32000, + 64000, + 96000, + 128000 + ], + "repeat_nodes": [], + "checkpoint_nodes": [ + 0, + 128000 + ], + "width": 128, + "layers": 4, + "repeats": 4, + "composition_count": "all", + "test_repeats": [], + "phase": "confirmation", + "memory_arm": "shared_full", + "window": 2, + "name": "w107270013-shared_full-changed_use", + "job_type": "reader", + "reference_compute_budget": 4509860364288000, + "per_step_flops": 35233284096, + "initial_model_sha256": "8135e30e84f2dbfdf13bf48af45e275d6d5b12e4252796470abd9766bec061b3", + "parameters": 1011072, + "data_sha256": "39bd3cae652d3229dd0e89875c0c0c5868567cfa6a5df37d694e4c737a9b85d0", + "training_arm": "changed_use", + "parent_name": "base-w107270013-shared_full", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/base-w107270013-shared_full", + "episodes": 32, + "inner_steps": 512, + "reader_steps": 512, + "inner_lr": 0.0001, + "reader_lr": 0.0001, + "panel_sha256": "3514be23bd5bcb1421a7a84b6b2f4fb55abf0b8b1e2050af68c9d00c10baabb4" + } + ], + "editing_specs": [ + { + "name": "edit-w730011-local-fixed", + "job_type": "editing", + "phase": "development", + "world": 730011, + "memory_arm": "local", + "training_arm": "fixed", + "parent_name": "w730011-local-fixed", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w730011-local-fixed", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 29, + 14, + 1049 + ], + "new_fact": [ + 29, + 14, + 1045 + ], + "replay_indices": [ + 40, + 65, + 90, + 123, + 142, + 156, + 170, + 193, + 257, + 275, + 306, + 323, + 328, + 331, + 380, + 500, + 614, + 623, + 648, + 707, + 752, + 766, + 800, + 811, + 850, + 909, + 919, + 926, + 978, + 985, + 1008, + 1015 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 16, + 1071 + ], + "new_fact": [ + 57, + 16, + 1089 + ], + "replay_indices": [ + 47, + 56, + 91, + 100, + 131, + 156, + 300, + 307, + 342, + 354, + 360, + 365, + 405, + 428, + 512, + 525, + 532, + 534, + 548, + 583, + 655, + 719, + 753, + 783, + 787, + 803, + 809, + 842, + 878, + 907, + 959, + 1006 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 63, + 13, + 1082 + ], + "new_fact": [ + 63, + 13, + 1097 + ], + "replay_indices": [ + 19, + 60, + 75, + 93, + 112, + 189, + 192, + 202, + 235, + 247, + 305, + 322, + 333, + 392, + 461, + 490, + 527, + 542, + 622, + 654, + 710, + 730, + 733, + 757, + 770, + 776, + 784, + 796, + 865, + 906, + 995, + 1009 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 52, + 13, + 1093 + ], + "new_fact": [ + 52, + 13, + 1087 + ], + "replay_indices": [ + 19, + 26, + 33, + 66, + 97, + 102, + 113, + 145, + 153, + 178, + 248, + 283, + 302, + 332, + 394, + 431, + 453, + 497, + 519, + 520, + 560, + 601, + 636, + 661, + 687, + 764, + 855, + 873, + 879, + 893, + 987, + 994 + ], + "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": [ + 102, + 15, + 1111 + ], + "new_fact": [ + 102, + 15, + 1117 + ], + "replay_indices": [ + 22, + 29, + 101, + 199, + 206, + 235, + 294, + 352, + 420, + 422, + 441, + 474, + 565, + 577, + 598, + 632, + 646, + 689, + 748, + 759, + 818, + 828, + 852, + 868, + 876, + 892, + 900, + 907, + 914, + 949, + 974, + 994 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1124 + ], + "new_fact": [ + 89, + 16, + 1136 + ], + "replay_indices": [ + 45, + 205, + 235, + 245, + 257, + 314, + 320, + 328, + 334, + 346, + 356, + 388, + 480, + 518, + 522, + 540, + 546, + 551, + 555, + 652, + 667, + 672, + 765, + 773, + 811, + 841, + 898, + 905, + 980, + 986, + 987, + 1018 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 108, + 14, + 1124 + ], + "new_fact": [ + 108, + 14, + 1129 + ], + "replay_indices": [ + 41, + 90, + 93, + 157, + 171, + 209, + 281, + 302, + 370, + 419, + 471, + 481, + 494, + 523, + 602, + 604, + 642, + 666, + 669, + 720, + 721, + 787, + 820, + 891, + 904, + 916, + 917, + 977, + 991, + 993, + 996, + 1016 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 14, + 1125 + ], + "new_fact": [ + 89, + 14, + 1114 + ], + "replay_indices": [ + 25, + 33, + 44, + 60, + 62, + 66, + 89, + 121, + 237, + 308, + 350, + 380, + 412, + 458, + 465, + 470, + 473, + 491, + 516, + 525, + 535, + 584, + 630, + 711, + 718, + 785, + 802, + 803, + 851, + 878, + 1001, + 1007 + ], + "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, + 20, + 1595 + ], + "new_fact": [ + 1085, + 20, + 1585 + ], + "replay_indices": [ + 1, + 60, + 93, + 99, + 111, + 167, + 170, + 177, + 263, + 286, + 288, + 313, + 329, + 340, + 385, + 439, + 541, + 585, + 595, + 598, + 611, + 662, + 691, + 700, + 710, + 726, + 749, + 756, + 789, + 852, + 885, + 996 + ], + "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": 6 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1072, + 20, + 1630 + ], + "new_fact": [ + 1072, + 20, + 1651 + ], + "replay_indices": [ + 8, + 20, + 25, + 58, + 79, + 83, + 157, + 185, + 285, + 370, + 408, + 480, + 509, + 510, + 535, + 551, + 675, + 696, + 724, + 729, + 755, + 773, + 780, + 821, + 853, + 887, + 925, + 942, + 968, + 970, + 993, + 997 + ], + "affected_untrained_n": { + "D_second_familiar": 3, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 3, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1073, + 20, + 1594 + ], + "new_fact": [ + 1073, + 20, + 1677 + ], + "replay_indices": [ + 2, + 53, + 74, + 120, + 130, + 210, + 267, + 286, + 289, + 296, + 297, + 306, + 311, + 341, + 343, + 391, + 399, + 436, + 487, + 496, + 551, + 556, + 591, + 600, + 698, + 708, + 757, + 827, + 864, + 871, + 884, + 990 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1082, + 20, + 1624 + ], + "new_fact": [ + 1082, + 20, + 1605 + ], + "replay_indices": [ + 29, + 70, + 139, + 179, + 182, + 226, + 289, + 344, + 382, + 450, + 454, + 522, + 531, + 564, + 566, + 592, + 608, + 627, + 651, + 693, + 698, + 731, + 761, + 816, + 861, + 865, + 907, + 935, + 970, + 985, + 1002, + 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": 6 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1129, + 17, + 1637 + ], + "new_fact": [ + 1129, + 17, + 1565 + ], + "replay_indices": [ + 30, + 61, + 66, + 146, + 236, + 326, + 356, + 367, + 372, + 503, + 512, + 540, + 629, + 634, + 691, + 716, + 751, + 782, + 806, + 824, + 829, + 832, + 871, + 883, + 885, + 890, + 904, + 908, + 916, + 939, + 978, + 1017 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1119, + 17, + 1599 + ], + "new_fact": [ + 1119, + 17, + 1608 + ], + "replay_indices": [ + 23, + 86, + 129, + 139, + 149, + 188, + 198, + 223, + 288, + 318, + 340, + 354, + 402, + 419, + 471, + 475, + 478, + 618, + 632, + 668, + 715, + 721, + 729, + 750, + 768, + 848, + 881, + 905, + 935, + 956, + 986, + 1002 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1111, + 17, + 1586 + ], + "new_fact": [ + 1111, + 17, + 1656 + ], + "replay_indices": [ + 28, + 74, + 207, + 208, + 222, + 294, + 302, + 318, + 346, + 412, + 471, + 480, + 494, + 502, + 580, + 604, + 630, + 650, + 680, + 691, + 708, + 813, + 826, + 832, + 850, + 857, + 860, + 865, + 883, + 926, + 975, + 1001 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1122, + 19, + 1603 + ], + "new_fact": [ + 1122, + 19, + 1680 + ], + "replay_indices": [ + 18, + 30, + 64, + 147, + 160, + 186, + 239, + 283, + 301, + 358, + 366, + 503, + 532, + 571, + 577, + 603, + 672, + 693, + 696, + 725, + 741, + 749, + 786, + 826, + 840, + 881, + 882, + 894, + 906, + 949, + 976, + 993 + ], + "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 + } + } + ], + "case_sha256": "0dfd828f3d407bbd056cf9784a561c6a67d656e1945e7b28ae18188b62191fcf", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w730011-local-changed_atomic", + "job_type": "editing", + "phase": "development", + "world": 730011, + "memory_arm": "local", + "training_arm": "changed_atomic", + "parent_name": "w730011-local-changed_atomic", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w730011-local-changed_atomic", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 29, + 14, + 1049 + ], + "new_fact": [ + 29, + 14, + 1045 + ], + "replay_indices": [ + 40, + 65, + 90, + 123, + 142, + 156, + 170, + 193, + 257, + 275, + 306, + 323, + 328, + 331, + 380, + 500, + 614, + 623, + 648, + 707, + 752, + 766, + 800, + 811, + 850, + 909, + 919, + 926, + 978, + 985, + 1008, + 1015 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 16, + 1071 + ], + "new_fact": [ + 57, + 16, + 1089 + ], + "replay_indices": [ + 47, + 56, + 91, + 100, + 131, + 156, + 300, + 307, + 342, + 354, + 360, + 365, + 405, + 428, + 512, + 525, + 532, + 534, + 548, + 583, + 655, + 719, + 753, + 783, + 787, + 803, + 809, + 842, + 878, + 907, + 959, + 1006 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 63, + 13, + 1082 + ], + "new_fact": [ + 63, + 13, + 1097 + ], + "replay_indices": [ + 19, + 60, + 75, + 93, + 112, + 189, + 192, + 202, + 235, + 247, + 305, + 322, + 333, + 392, + 461, + 490, + 527, + 542, + 622, + 654, + 710, + 730, + 733, + 757, + 770, + 776, + 784, + 796, + 865, + 906, + 995, + 1009 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 52, + 13, + 1093 + ], + "new_fact": [ + 52, + 13, + 1087 + ], + "replay_indices": [ + 19, + 26, + 33, + 66, + 97, + 102, + 113, + 145, + 153, + 178, + 248, + 283, + 302, + 332, + 394, + 431, + 453, + 497, + 519, + 520, + 560, + 601, + 636, + 661, + 687, + 764, + 855, + 873, + 879, + 893, + 987, + 994 + ], + "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": [ + 102, + 15, + 1111 + ], + "new_fact": [ + 102, + 15, + 1117 + ], + "replay_indices": [ + 22, + 29, + 101, + 199, + 206, + 235, + 294, + 352, + 420, + 422, + 441, + 474, + 565, + 577, + 598, + 632, + 646, + 689, + 748, + 759, + 818, + 828, + 852, + 868, + 876, + 892, + 900, + 907, + 914, + 949, + 974, + 994 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1124 + ], + "new_fact": [ + 89, + 16, + 1136 + ], + "replay_indices": [ + 45, + 205, + 235, + 245, + 257, + 314, + 320, + 328, + 334, + 346, + 356, + 388, + 480, + 518, + 522, + 540, + 546, + 551, + 555, + 652, + 667, + 672, + 765, + 773, + 811, + 841, + 898, + 905, + 980, + 986, + 987, + 1018 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 108, + 14, + 1124 + ], + "new_fact": [ + 108, + 14, + 1129 + ], + "replay_indices": [ + 41, + 90, + 93, + 157, + 171, + 209, + 281, + 302, + 370, + 419, + 471, + 481, + 494, + 523, + 602, + 604, + 642, + 666, + 669, + 720, + 721, + 787, + 820, + 891, + 904, + 916, + 917, + 977, + 991, + 993, + 996, + 1016 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 14, + 1125 + ], + "new_fact": [ + 89, + 14, + 1114 + ], + "replay_indices": [ + 25, + 33, + 44, + 60, + 62, + 66, + 89, + 121, + 237, + 308, + 350, + 380, + 412, + 458, + 465, + 470, + 473, + 491, + 516, + 525, + 535, + 584, + 630, + 711, + 718, + 785, + 802, + 803, + 851, + 878, + 1001, + 1007 + ], + "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, + 20, + 1595 + ], + "new_fact": [ + 1085, + 20, + 1585 + ], + "replay_indices": [ + 1, + 60, + 93, + 99, + 111, + 167, + 170, + 177, + 263, + 286, + 288, + 313, + 329, + 340, + 385, + 439, + 541, + 585, + 595, + 598, + 611, + 662, + 691, + 700, + 710, + 726, + 749, + 756, + 789, + 852, + 885, + 996 + ], + "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": 6 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1072, + 20, + 1630 + ], + "new_fact": [ + 1072, + 20, + 1651 + ], + "replay_indices": [ + 8, + 20, + 25, + 58, + 79, + 83, + 157, + 185, + 285, + 370, + 408, + 480, + 509, + 510, + 535, + 551, + 675, + 696, + 724, + 729, + 755, + 773, + 780, + 821, + 853, + 887, + 925, + 942, + 968, + 970, + 993, + 997 + ], + "affected_untrained_n": { + "D_second_familiar": 3, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 3, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1073, + 20, + 1594 + ], + "new_fact": [ + 1073, + 20, + 1677 + ], + "replay_indices": [ + 2, + 53, + 74, + 120, + 130, + 210, + 267, + 286, + 289, + 296, + 297, + 306, + 311, + 341, + 343, + 391, + 399, + 436, + 487, + 496, + 551, + 556, + 591, + 600, + 698, + 708, + 757, + 827, + 864, + 871, + 884, + 990 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1082, + 20, + 1624 + ], + "new_fact": [ + 1082, + 20, + 1605 + ], + "replay_indices": [ + 29, + 70, + 139, + 179, + 182, + 226, + 289, + 344, + 382, + 450, + 454, + 522, + 531, + 564, + 566, + 592, + 608, + 627, + 651, + 693, + 698, + 731, + 761, + 816, + 861, + 865, + 907, + 935, + 970, + 985, + 1002, + 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": 6 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1129, + 17, + 1637 + ], + "new_fact": [ + 1129, + 17, + 1565 + ], + "replay_indices": [ + 30, + 61, + 66, + 146, + 236, + 326, + 356, + 367, + 372, + 503, + 512, + 540, + 629, + 634, + 691, + 716, + 751, + 782, + 806, + 824, + 829, + 832, + 871, + 883, + 885, + 890, + 904, + 908, + 916, + 939, + 978, + 1017 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1119, + 17, + 1599 + ], + "new_fact": [ + 1119, + 17, + 1608 + ], + "replay_indices": [ + 23, + 86, + 129, + 139, + 149, + 188, + 198, + 223, + 288, + 318, + 340, + 354, + 402, + 419, + 471, + 475, + 478, + 618, + 632, + 668, + 715, + 721, + 729, + 750, + 768, + 848, + 881, + 905, + 935, + 956, + 986, + 1002 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1111, + 17, + 1586 + ], + "new_fact": [ + 1111, + 17, + 1656 + ], + "replay_indices": [ + 28, + 74, + 207, + 208, + 222, + 294, + 302, + 318, + 346, + 412, + 471, + 480, + 494, + 502, + 580, + 604, + 630, + 650, + 680, + 691, + 708, + 813, + 826, + 832, + 850, + 857, + 860, + 865, + 883, + 926, + 975, + 1001 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1122, + 19, + 1603 + ], + "new_fact": [ + 1122, + 19, + 1680 + ], + "replay_indices": [ + 18, + 30, + 64, + 147, + 160, + 186, + 239, + 283, + 301, + 358, + 366, + 503, + 532, + 571, + 577, + 603, + 672, + 693, + 696, + 725, + 741, + 749, + 786, + 826, + 840, + 881, + 882, + 894, + 906, + 949, + 976, + 993 + ], + "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 + } + } + ], + "case_sha256": "0dfd828f3d407bbd056cf9784a561c6a67d656e1945e7b28ae18188b62191fcf", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w730011-local-changed_use", + "job_type": "editing", + "phase": "development", + "world": 730011, + "memory_arm": "local", + "training_arm": "changed_use", + "parent_name": "w730011-local-changed_use", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w730011-local-changed_use", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 29, + 14, + 1049 + ], + "new_fact": [ + 29, + 14, + 1045 + ], + "replay_indices": [ + 40, + 65, + 90, + 123, + 142, + 156, + 170, + 193, + 257, + 275, + 306, + 323, + 328, + 331, + 380, + 500, + 614, + 623, + 648, + 707, + 752, + 766, + 800, + 811, + 850, + 909, + 919, + 926, + 978, + 985, + 1008, + 1015 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 16, + 1071 + ], + "new_fact": [ + 57, + 16, + 1089 + ], + "replay_indices": [ + 47, + 56, + 91, + 100, + 131, + 156, + 300, + 307, + 342, + 354, + 360, + 365, + 405, + 428, + 512, + 525, + 532, + 534, + 548, + 583, + 655, + 719, + 753, + 783, + 787, + 803, + 809, + 842, + 878, + 907, + 959, + 1006 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 63, + 13, + 1082 + ], + "new_fact": [ + 63, + 13, + 1097 + ], + "replay_indices": [ + 19, + 60, + 75, + 93, + 112, + 189, + 192, + 202, + 235, + 247, + 305, + 322, + 333, + 392, + 461, + 490, + 527, + 542, + 622, + 654, + 710, + 730, + 733, + 757, + 770, + 776, + 784, + 796, + 865, + 906, + 995, + 1009 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 52, + 13, + 1093 + ], + "new_fact": [ + 52, + 13, + 1087 + ], + "replay_indices": [ + 19, + 26, + 33, + 66, + 97, + 102, + 113, + 145, + 153, + 178, + 248, + 283, + 302, + 332, + 394, + 431, + 453, + 497, + 519, + 520, + 560, + 601, + 636, + 661, + 687, + 764, + 855, + 873, + 879, + 893, + 987, + 994 + ], + "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": [ + 102, + 15, + 1111 + ], + "new_fact": [ + 102, + 15, + 1117 + ], + "replay_indices": [ + 22, + 29, + 101, + 199, + 206, + 235, + 294, + 352, + 420, + 422, + 441, + 474, + 565, + 577, + 598, + 632, + 646, + 689, + 748, + 759, + 818, + 828, + 852, + 868, + 876, + 892, + 900, + 907, + 914, + 949, + 974, + 994 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1124 + ], + "new_fact": [ + 89, + 16, + 1136 + ], + "replay_indices": [ + 45, + 205, + 235, + 245, + 257, + 314, + 320, + 328, + 334, + 346, + 356, + 388, + 480, + 518, + 522, + 540, + 546, + 551, + 555, + 652, + 667, + 672, + 765, + 773, + 811, + 841, + 898, + 905, + 980, + 986, + 987, + 1018 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 108, + 14, + 1124 + ], + "new_fact": [ + 108, + 14, + 1129 + ], + "replay_indices": [ + 41, + 90, + 93, + 157, + 171, + 209, + 281, + 302, + 370, + 419, + 471, + 481, + 494, + 523, + 602, + 604, + 642, + 666, + 669, + 720, + 721, + 787, + 820, + 891, + 904, + 916, + 917, + 977, + 991, + 993, + 996, + 1016 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 14, + 1125 + ], + "new_fact": [ + 89, + 14, + 1114 + ], + "replay_indices": [ + 25, + 33, + 44, + 60, + 62, + 66, + 89, + 121, + 237, + 308, + 350, + 380, + 412, + 458, + 465, + 470, + 473, + 491, + 516, + 525, + 535, + 584, + 630, + 711, + 718, + 785, + 802, + 803, + 851, + 878, + 1001, + 1007 + ], + "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, + 20, + 1595 + ], + "new_fact": [ + 1085, + 20, + 1585 + ], + "replay_indices": [ + 1, + 60, + 93, + 99, + 111, + 167, + 170, + 177, + 263, + 286, + 288, + 313, + 329, + 340, + 385, + 439, + 541, + 585, + 595, + 598, + 611, + 662, + 691, + 700, + 710, + 726, + 749, + 756, + 789, + 852, + 885, + 996 + ], + "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": 6 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1072, + 20, + 1630 + ], + "new_fact": [ + 1072, + 20, + 1651 + ], + "replay_indices": [ + 8, + 20, + 25, + 58, + 79, + 83, + 157, + 185, + 285, + 370, + 408, + 480, + 509, + 510, + 535, + 551, + 675, + 696, + 724, + 729, + 755, + 773, + 780, + 821, + 853, + 887, + 925, + 942, + 968, + 970, + 993, + 997 + ], + "affected_untrained_n": { + "D_second_familiar": 3, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 3, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1073, + 20, + 1594 + ], + "new_fact": [ + 1073, + 20, + 1677 + ], + "replay_indices": [ + 2, + 53, + 74, + 120, + 130, + 210, + 267, + 286, + 289, + 296, + 297, + 306, + 311, + 341, + 343, + 391, + 399, + 436, + 487, + 496, + 551, + 556, + 591, + 600, + 698, + 708, + 757, + 827, + 864, + 871, + 884, + 990 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1082, + 20, + 1624 + ], + "new_fact": [ + 1082, + 20, + 1605 + ], + "replay_indices": [ + 29, + 70, + 139, + 179, + 182, + 226, + 289, + 344, + 382, + 450, + 454, + 522, + 531, + 564, + 566, + 592, + 608, + 627, + 651, + 693, + 698, + 731, + 761, + 816, + 861, + 865, + 907, + 935, + 970, + 985, + 1002, + 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": 6 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1129, + 17, + 1637 + ], + "new_fact": [ + 1129, + 17, + 1565 + ], + "replay_indices": [ + 30, + 61, + 66, + 146, + 236, + 326, + 356, + 367, + 372, + 503, + 512, + 540, + 629, + 634, + 691, + 716, + 751, + 782, + 806, + 824, + 829, + 832, + 871, + 883, + 885, + 890, + 904, + 908, + 916, + 939, + 978, + 1017 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1119, + 17, + 1599 + ], + "new_fact": [ + 1119, + 17, + 1608 + ], + "replay_indices": [ + 23, + 86, + 129, + 139, + 149, + 188, + 198, + 223, + 288, + 318, + 340, + 354, + 402, + 419, + 471, + 475, + 478, + 618, + 632, + 668, + 715, + 721, + 729, + 750, + 768, + 848, + 881, + 905, + 935, + 956, + 986, + 1002 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1111, + 17, + 1586 + ], + "new_fact": [ + 1111, + 17, + 1656 + ], + "replay_indices": [ + 28, + 74, + 207, + 208, + 222, + 294, + 302, + 318, + 346, + 412, + 471, + 480, + 494, + 502, + 580, + 604, + 630, + 650, + 680, + 691, + 708, + 813, + 826, + 832, + 850, + 857, + 860, + 865, + 883, + 926, + 975, + 1001 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1122, + 19, + 1603 + ], + "new_fact": [ + 1122, + 19, + 1680 + ], + "replay_indices": [ + 18, + 30, + 64, + 147, + 160, + 186, + 239, + 283, + 301, + 358, + 366, + 503, + 532, + 571, + 577, + 603, + 672, + 693, + 696, + 725, + 741, + 749, + 786, + 826, + 840, + 881, + 882, + 894, + 906, + 949, + 976, + 993 + ], + "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 + } + } + ], + "case_sha256": "0dfd828f3d407bbd056cf9784a561c6a67d656e1945e7b28ae18188b62191fcf", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w730011-shared_full-fixed", + "job_type": "editing", + "phase": "development", + "world": 730011, + "memory_arm": "shared_full", + "training_arm": "fixed", + "parent_name": "w730011-shared_full-fixed", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w730011-shared_full-fixed", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 29, + 14, + 1049 + ], + "new_fact": [ + 29, + 14, + 1045 + ], + "replay_indices": [ + 40, + 65, + 90, + 123, + 142, + 156, + 170, + 193, + 257, + 275, + 306, + 323, + 328, + 331, + 380, + 500, + 614, + 623, + 648, + 707, + 752, + 766, + 800, + 811, + 850, + 909, + 919, + 926, + 978, + 985, + 1008, + 1015 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 16, + 1071 + ], + "new_fact": [ + 57, + 16, + 1089 + ], + "replay_indices": [ + 47, + 56, + 91, + 100, + 131, + 156, + 300, + 307, + 342, + 354, + 360, + 365, + 405, + 428, + 512, + 525, + 532, + 534, + 548, + 583, + 655, + 719, + 753, + 783, + 787, + 803, + 809, + 842, + 878, + 907, + 959, + 1006 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 63, + 13, + 1082 + ], + "new_fact": [ + 63, + 13, + 1097 + ], + "replay_indices": [ + 19, + 60, + 75, + 93, + 112, + 189, + 192, + 202, + 235, + 247, + 305, + 322, + 333, + 392, + 461, + 490, + 527, + 542, + 622, + 654, + 710, + 730, + 733, + 757, + 770, + 776, + 784, + 796, + 865, + 906, + 995, + 1009 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 52, + 13, + 1093 + ], + "new_fact": [ + 52, + 13, + 1087 + ], + "replay_indices": [ + 19, + 26, + 33, + 66, + 97, + 102, + 113, + 145, + 153, + 178, + 248, + 283, + 302, + 332, + 394, + 431, + 453, + 497, + 519, + 520, + 560, + 601, + 636, + 661, + 687, + 764, + 855, + 873, + 879, + 893, + 987, + 994 + ], + "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": [ + 102, + 15, + 1111 + ], + "new_fact": [ + 102, + 15, + 1117 + ], + "replay_indices": [ + 22, + 29, + 101, + 199, + 206, + 235, + 294, + 352, + 420, + 422, + 441, + 474, + 565, + 577, + 598, + 632, + 646, + 689, + 748, + 759, + 818, + 828, + 852, + 868, + 876, + 892, + 900, + 907, + 914, + 949, + 974, + 994 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1124 + ], + "new_fact": [ + 89, + 16, + 1136 + ], + "replay_indices": [ + 45, + 205, + 235, + 245, + 257, + 314, + 320, + 328, + 334, + 346, + 356, + 388, + 480, + 518, + 522, + 540, + 546, + 551, + 555, + 652, + 667, + 672, + 765, + 773, + 811, + 841, + 898, + 905, + 980, + 986, + 987, + 1018 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 108, + 14, + 1124 + ], + "new_fact": [ + 108, + 14, + 1129 + ], + "replay_indices": [ + 41, + 90, + 93, + 157, + 171, + 209, + 281, + 302, + 370, + 419, + 471, + 481, + 494, + 523, + 602, + 604, + 642, + 666, + 669, + 720, + 721, + 787, + 820, + 891, + 904, + 916, + 917, + 977, + 991, + 993, + 996, + 1016 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 14, + 1125 + ], + "new_fact": [ + 89, + 14, + 1114 + ], + "replay_indices": [ + 25, + 33, + 44, + 60, + 62, + 66, + 89, + 121, + 237, + 308, + 350, + 380, + 412, + 458, + 465, + 470, + 473, + 491, + 516, + 525, + 535, + 584, + 630, + 711, + 718, + 785, + 802, + 803, + 851, + 878, + 1001, + 1007 + ], + "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, + 20, + 1595 + ], + "new_fact": [ + 1085, + 20, + 1585 + ], + "replay_indices": [ + 1, + 60, + 93, + 99, + 111, + 167, + 170, + 177, + 263, + 286, + 288, + 313, + 329, + 340, + 385, + 439, + 541, + 585, + 595, + 598, + 611, + 662, + 691, + 700, + 710, + 726, + 749, + 756, + 789, + 852, + 885, + 996 + ], + "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": 6 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1072, + 20, + 1630 + ], + "new_fact": [ + 1072, + 20, + 1651 + ], + "replay_indices": [ + 8, + 20, + 25, + 58, + 79, + 83, + 157, + 185, + 285, + 370, + 408, + 480, + 509, + 510, + 535, + 551, + 675, + 696, + 724, + 729, + 755, + 773, + 780, + 821, + 853, + 887, + 925, + 942, + 968, + 970, + 993, + 997 + ], + "affected_untrained_n": { + "D_second_familiar": 3, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 3, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1073, + 20, + 1594 + ], + "new_fact": [ + 1073, + 20, + 1677 + ], + "replay_indices": [ + 2, + 53, + 74, + 120, + 130, + 210, + 267, + 286, + 289, + 296, + 297, + 306, + 311, + 341, + 343, + 391, + 399, + 436, + 487, + 496, + 551, + 556, + 591, + 600, + 698, + 708, + 757, + 827, + 864, + 871, + 884, + 990 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1082, + 20, + 1624 + ], + "new_fact": [ + 1082, + 20, + 1605 + ], + "replay_indices": [ + 29, + 70, + 139, + 179, + 182, + 226, + 289, + 344, + 382, + 450, + 454, + 522, + 531, + 564, + 566, + 592, + 608, + 627, + 651, + 693, + 698, + 731, + 761, + 816, + 861, + 865, + 907, + 935, + 970, + 985, + 1002, + 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": 6 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1129, + 17, + 1637 + ], + "new_fact": [ + 1129, + 17, + 1565 + ], + "replay_indices": [ + 30, + 61, + 66, + 146, + 236, + 326, + 356, + 367, + 372, + 503, + 512, + 540, + 629, + 634, + 691, + 716, + 751, + 782, + 806, + 824, + 829, + 832, + 871, + 883, + 885, + 890, + 904, + 908, + 916, + 939, + 978, + 1017 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1119, + 17, + 1599 + ], + "new_fact": [ + 1119, + 17, + 1608 + ], + "replay_indices": [ + 23, + 86, + 129, + 139, + 149, + 188, + 198, + 223, + 288, + 318, + 340, + 354, + 402, + 419, + 471, + 475, + 478, + 618, + 632, + 668, + 715, + 721, + 729, + 750, + 768, + 848, + 881, + 905, + 935, + 956, + 986, + 1002 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1111, + 17, + 1586 + ], + "new_fact": [ + 1111, + 17, + 1656 + ], + "replay_indices": [ + 28, + 74, + 207, + 208, + 222, + 294, + 302, + 318, + 346, + 412, + 471, + 480, + 494, + 502, + 580, + 604, + 630, + 650, + 680, + 691, + 708, + 813, + 826, + 832, + 850, + 857, + 860, + 865, + 883, + 926, + 975, + 1001 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1122, + 19, + 1603 + ], + "new_fact": [ + 1122, + 19, + 1680 + ], + "replay_indices": [ + 18, + 30, + 64, + 147, + 160, + 186, + 239, + 283, + 301, + 358, + 366, + 503, + 532, + 571, + 577, + 603, + 672, + 693, + 696, + 725, + 741, + 749, + 786, + 826, + 840, + 881, + 882, + 894, + 906, + 949, + 976, + 993 + ], + "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 + } + } + ], + "case_sha256": "0dfd828f3d407bbd056cf9784a561c6a67d656e1945e7b28ae18188b62191fcf", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w730011-shared_full-changed_atomic", + "job_type": "editing", + "phase": "development", + "world": 730011, + "memory_arm": "shared_full", + "training_arm": "changed_atomic", + "parent_name": "w730011-shared_full-changed_atomic", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w730011-shared_full-changed_atomic", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 29, + 14, + 1049 + ], + "new_fact": [ + 29, + 14, + 1045 + ], + "replay_indices": [ + 40, + 65, + 90, + 123, + 142, + 156, + 170, + 193, + 257, + 275, + 306, + 323, + 328, + 331, + 380, + 500, + 614, + 623, + 648, + 707, + 752, + 766, + 800, + 811, + 850, + 909, + 919, + 926, + 978, + 985, + 1008, + 1015 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 16, + 1071 + ], + "new_fact": [ + 57, + 16, + 1089 + ], + "replay_indices": [ + 47, + 56, + 91, + 100, + 131, + 156, + 300, + 307, + 342, + 354, + 360, + 365, + 405, + 428, + 512, + 525, + 532, + 534, + 548, + 583, + 655, + 719, + 753, + 783, + 787, + 803, + 809, + 842, + 878, + 907, + 959, + 1006 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 63, + 13, + 1082 + ], + "new_fact": [ + 63, + 13, + 1097 + ], + "replay_indices": [ + 19, + 60, + 75, + 93, + 112, + 189, + 192, + 202, + 235, + 247, + 305, + 322, + 333, + 392, + 461, + 490, + 527, + 542, + 622, + 654, + 710, + 730, + 733, + 757, + 770, + 776, + 784, + 796, + 865, + 906, + 995, + 1009 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 52, + 13, + 1093 + ], + "new_fact": [ + 52, + 13, + 1087 + ], + "replay_indices": [ + 19, + 26, + 33, + 66, + 97, + 102, + 113, + 145, + 153, + 178, + 248, + 283, + 302, + 332, + 394, + 431, + 453, + 497, + 519, + 520, + 560, + 601, + 636, + 661, + 687, + 764, + 855, + 873, + 879, + 893, + 987, + 994 + ], + "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": [ + 102, + 15, + 1111 + ], + "new_fact": [ + 102, + 15, + 1117 + ], + "replay_indices": [ + 22, + 29, + 101, + 199, + 206, + 235, + 294, + 352, + 420, + 422, + 441, + 474, + 565, + 577, + 598, + 632, + 646, + 689, + 748, + 759, + 818, + 828, + 852, + 868, + 876, + 892, + 900, + 907, + 914, + 949, + 974, + 994 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1124 + ], + "new_fact": [ + 89, + 16, + 1136 + ], + "replay_indices": [ + 45, + 205, + 235, + 245, + 257, + 314, + 320, + 328, + 334, + 346, + 356, + 388, + 480, + 518, + 522, + 540, + 546, + 551, + 555, + 652, + 667, + 672, + 765, + 773, + 811, + 841, + 898, + 905, + 980, + 986, + 987, + 1018 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 108, + 14, + 1124 + ], + "new_fact": [ + 108, + 14, + 1129 + ], + "replay_indices": [ + 41, + 90, + 93, + 157, + 171, + 209, + 281, + 302, + 370, + 419, + 471, + 481, + 494, + 523, + 602, + 604, + 642, + 666, + 669, + 720, + 721, + 787, + 820, + 891, + 904, + 916, + 917, + 977, + 991, + 993, + 996, + 1016 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 14, + 1125 + ], + "new_fact": [ + 89, + 14, + 1114 + ], + "replay_indices": [ + 25, + 33, + 44, + 60, + 62, + 66, + 89, + 121, + 237, + 308, + 350, + 380, + 412, + 458, + 465, + 470, + 473, + 491, + 516, + 525, + 535, + 584, + 630, + 711, + 718, + 785, + 802, + 803, + 851, + 878, + 1001, + 1007 + ], + "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, + 20, + 1595 + ], + "new_fact": [ + 1085, + 20, + 1585 + ], + "replay_indices": [ + 1, + 60, + 93, + 99, + 111, + 167, + 170, + 177, + 263, + 286, + 288, + 313, + 329, + 340, + 385, + 439, + 541, + 585, + 595, + 598, + 611, + 662, + 691, + 700, + 710, + 726, + 749, + 756, + 789, + 852, + 885, + 996 + ], + "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": 6 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1072, + 20, + 1630 + ], + "new_fact": [ + 1072, + 20, + 1651 + ], + "replay_indices": [ + 8, + 20, + 25, + 58, + 79, + 83, + 157, + 185, + 285, + 370, + 408, + 480, + 509, + 510, + 535, + 551, + 675, + 696, + 724, + 729, + 755, + 773, + 780, + 821, + 853, + 887, + 925, + 942, + 968, + 970, + 993, + 997 + ], + "affected_untrained_n": { + "D_second_familiar": 3, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 3, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1073, + 20, + 1594 + ], + "new_fact": [ + 1073, + 20, + 1677 + ], + "replay_indices": [ + 2, + 53, + 74, + 120, + 130, + 210, + 267, + 286, + 289, + 296, + 297, + 306, + 311, + 341, + 343, + 391, + 399, + 436, + 487, + 496, + 551, + 556, + 591, + 600, + 698, + 708, + 757, + 827, + 864, + 871, + 884, + 990 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1082, + 20, + 1624 + ], + "new_fact": [ + 1082, + 20, + 1605 + ], + "replay_indices": [ + 29, + 70, + 139, + 179, + 182, + 226, + 289, + 344, + 382, + 450, + 454, + 522, + 531, + 564, + 566, + 592, + 608, + 627, + 651, + 693, + 698, + 731, + 761, + 816, + 861, + 865, + 907, + 935, + 970, + 985, + 1002, + 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": 6 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1129, + 17, + 1637 + ], + "new_fact": [ + 1129, + 17, + 1565 + ], + "replay_indices": [ + 30, + 61, + 66, + 146, + 236, + 326, + 356, + 367, + 372, + 503, + 512, + 540, + 629, + 634, + 691, + 716, + 751, + 782, + 806, + 824, + 829, + 832, + 871, + 883, + 885, + 890, + 904, + 908, + 916, + 939, + 978, + 1017 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1119, + 17, + 1599 + ], + "new_fact": [ + 1119, + 17, + 1608 + ], + "replay_indices": [ + 23, + 86, + 129, + 139, + 149, + 188, + 198, + 223, + 288, + 318, + 340, + 354, + 402, + 419, + 471, + 475, + 478, + 618, + 632, + 668, + 715, + 721, + 729, + 750, + 768, + 848, + 881, + 905, + 935, + 956, + 986, + 1002 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1111, + 17, + 1586 + ], + "new_fact": [ + 1111, + 17, + 1656 + ], + "replay_indices": [ + 28, + 74, + 207, + 208, + 222, + 294, + 302, + 318, + 346, + 412, + 471, + 480, + 494, + 502, + 580, + 604, + 630, + 650, + 680, + 691, + 708, + 813, + 826, + 832, + 850, + 857, + 860, + 865, + 883, + 926, + 975, + 1001 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1122, + 19, + 1603 + ], + "new_fact": [ + 1122, + 19, + 1680 + ], + "replay_indices": [ + 18, + 30, + 64, + 147, + 160, + 186, + 239, + 283, + 301, + 358, + 366, + 503, + 532, + 571, + 577, + 603, + 672, + 693, + 696, + 725, + 741, + 749, + 786, + 826, + 840, + 881, + 882, + 894, + 906, + 949, + 976, + 993 + ], + "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 + } + } + ], + "case_sha256": "0dfd828f3d407bbd056cf9784a561c6a67d656e1945e7b28ae18188b62191fcf", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w730011-shared_full-changed_use", + "job_type": "editing", + "phase": "development", + "world": 730011, + "memory_arm": "shared_full", + "training_arm": "changed_use", + "parent_name": "w730011-shared_full-changed_use", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w730011-shared_full-changed_use", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 29, + 14, + 1049 + ], + "new_fact": [ + 29, + 14, + 1045 + ], + "replay_indices": [ + 40, + 65, + 90, + 123, + 142, + 156, + 170, + 193, + 257, + 275, + 306, + 323, + 328, + 331, + 380, + 500, + 614, + 623, + 648, + 707, + 752, + 766, + 800, + 811, + 850, + 909, + 919, + 926, + 978, + 985, + 1008, + 1015 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 16, + 1071 + ], + "new_fact": [ + 57, + 16, + 1089 + ], + "replay_indices": [ + 47, + 56, + 91, + 100, + 131, + 156, + 300, + 307, + 342, + 354, + 360, + 365, + 405, + 428, + 512, + 525, + 532, + 534, + 548, + 583, + 655, + 719, + 753, + 783, + 787, + 803, + 809, + 842, + 878, + 907, + 959, + 1006 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 63, + 13, + 1082 + ], + "new_fact": [ + 63, + 13, + 1097 + ], + "replay_indices": [ + 19, + 60, + 75, + 93, + 112, + 189, + 192, + 202, + 235, + 247, + 305, + 322, + 333, + 392, + 461, + 490, + 527, + 542, + 622, + 654, + 710, + 730, + 733, + 757, + 770, + 776, + 784, + 796, + 865, + 906, + 995, + 1009 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 52, + 13, + 1093 + ], + "new_fact": [ + 52, + 13, + 1087 + ], + "replay_indices": [ + 19, + 26, + 33, + 66, + 97, + 102, + 113, + 145, + 153, + 178, + 248, + 283, + 302, + 332, + 394, + 431, + 453, + 497, + 519, + 520, + 560, + 601, + 636, + 661, + 687, + 764, + 855, + 873, + 879, + 893, + 987, + 994 + ], + "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": [ + 102, + 15, + 1111 + ], + "new_fact": [ + 102, + 15, + 1117 + ], + "replay_indices": [ + 22, + 29, + 101, + 199, + 206, + 235, + 294, + 352, + 420, + 422, + 441, + 474, + 565, + 577, + 598, + 632, + 646, + 689, + 748, + 759, + 818, + 828, + 852, + 868, + 876, + 892, + 900, + 907, + 914, + 949, + 974, + 994 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1124 + ], + "new_fact": [ + 89, + 16, + 1136 + ], + "replay_indices": [ + 45, + 205, + 235, + 245, + 257, + 314, + 320, + 328, + 334, + 346, + 356, + 388, + 480, + 518, + 522, + 540, + 546, + 551, + 555, + 652, + 667, + 672, + 765, + 773, + 811, + 841, + 898, + 905, + 980, + 986, + 987, + 1018 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 108, + 14, + 1124 + ], + "new_fact": [ + 108, + 14, + 1129 + ], + "replay_indices": [ + 41, + 90, + 93, + 157, + 171, + 209, + 281, + 302, + 370, + 419, + 471, + 481, + 494, + 523, + 602, + 604, + 642, + 666, + 669, + 720, + 721, + 787, + 820, + 891, + 904, + 916, + 917, + 977, + 991, + 993, + 996, + 1016 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 14, + 1125 + ], + "new_fact": [ + 89, + 14, + 1114 + ], + "replay_indices": [ + 25, + 33, + 44, + 60, + 62, + 66, + 89, + 121, + 237, + 308, + 350, + 380, + 412, + 458, + 465, + 470, + 473, + 491, + 516, + 525, + 535, + 584, + 630, + 711, + 718, + 785, + 802, + 803, + 851, + 878, + 1001, + 1007 + ], + "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, + 20, + 1595 + ], + "new_fact": [ + 1085, + 20, + 1585 + ], + "replay_indices": [ + 1, + 60, + 93, + 99, + 111, + 167, + 170, + 177, + 263, + 286, + 288, + 313, + 329, + 340, + 385, + 439, + 541, + 585, + 595, + 598, + 611, + 662, + 691, + 700, + 710, + 726, + 749, + 756, + 789, + 852, + 885, + 996 + ], + "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": 6 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1072, + 20, + 1630 + ], + "new_fact": [ + 1072, + 20, + 1651 + ], + "replay_indices": [ + 8, + 20, + 25, + 58, + 79, + 83, + 157, + 185, + 285, + 370, + 408, + 480, + 509, + 510, + 535, + 551, + 675, + 696, + 724, + 729, + 755, + 773, + 780, + 821, + 853, + 887, + 925, + 942, + 968, + 970, + 993, + 997 + ], + "affected_untrained_n": { + "D_second_familiar": 3, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 3, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 1 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1073, + 20, + 1594 + ], + "new_fact": [ + 1073, + 20, + 1677 + ], + "replay_indices": [ + 2, + 53, + 74, + 120, + 130, + 210, + 267, + 286, + 289, + 296, + 297, + 306, + 311, + 341, + 343, + 391, + 399, + 436, + 487, + 496, + 551, + 556, + 591, + 600, + 698, + 708, + 757, + 827, + 864, + 871, + 884, + 990 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1082, + 20, + 1624 + ], + "new_fact": [ + 1082, + 20, + 1605 + ], + "replay_indices": [ + 29, + 70, + 139, + 179, + 182, + 226, + 289, + 344, + 382, + 450, + 454, + 522, + 531, + 564, + 566, + 592, + 608, + 627, + 651, + 693, + 698, + 731, + 761, + 816, + 861, + 865, + 907, + 935, + 970, + 985, + 1002, + 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": 6 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1129, + 17, + 1637 + ], + "new_fact": [ + 1129, + 17, + 1565 + ], + "replay_indices": [ + 30, + 61, + 66, + 146, + 236, + 326, + 356, + 367, + 372, + 503, + 512, + 540, + 629, + 634, + 691, + 716, + 751, + 782, + 806, + 824, + 829, + 832, + 871, + 883, + 885, + 890, + 904, + 908, + 916, + 939, + 978, + 1017 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1119, + 17, + 1599 + ], + "new_fact": [ + 1119, + 17, + 1608 + ], + "replay_indices": [ + 23, + 86, + 129, + 139, + 149, + 188, + 198, + 223, + 288, + 318, + 340, + 354, + 402, + 419, + 471, + 475, + 478, + 618, + 632, + 668, + 715, + 721, + 729, + 750, + 768, + 848, + 881, + 905, + 935, + 956, + 986, + 1002 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1111, + 17, + 1586 + ], + "new_fact": [ + 1111, + 17, + 1656 + ], + "replay_indices": [ + 28, + 74, + 207, + 208, + 222, + 294, + 302, + 318, + 346, + 412, + 471, + 480, + 494, + 502, + 580, + 604, + 630, + 650, + 680, + 691, + 708, + 813, + 826, + 832, + 850, + 857, + 860, + 865, + 883, + 926, + 975, + 1001 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1122, + 19, + 1603 + ], + "new_fact": [ + 1122, + 19, + 1680 + ], + "replay_indices": [ + 18, + 30, + 64, + 147, + 160, + 186, + 239, + 283, + 301, + 358, + 366, + 503, + 532, + 571, + 577, + 603, + 672, + 693, + 696, + 725, + 741, + 749, + 786, + 826, + 840, + 881, + 882, + 894, + 906, + 949, + 976, + 993 + ], + "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 + } + } + ], + "case_sha256": "0dfd828f3d407bbd056cf9784a561c6a67d656e1945e7b28ae18188b62191fcf", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270011-local-fixed", + "job_type": "editing", + "phase": "confirmation", + "world": 107270011, + "memory_arm": "local", + "training_arm": "fixed", + "parent_name": "w107270011-local-fixed", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270011-local-fixed", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 36, + 16, + 1107 + ], + "new_fact": [ + 36, + 16, + 1071 + ], + "replay_indices": [ + 43, + 75, + 92, + 98, + 134, + 179, + 255, + 301, + 372, + 378, + 421, + 472, + 545, + 576, + 600, + 608, + 625, + 634, + 715, + 727, + 742, + 790, + 811, + 859, + 871, + 880, + 918, + 962, + 965, + 968, + 974, + 977 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 54, + 15, + 1074 + ], + "new_fact": [ + 54, + 15, + 1097 + ], + "replay_indices": [ + 31, + 39, + 74, + 211, + 240, + 264, + 270, + 294, + 295, + 310, + 328, + 330, + 354, + 360, + 369, + 442, + 482, + 582, + 693, + 712, + 761, + 764, + 770, + 788, + 799, + 800, + 801, + 811, + 826, + 901, + 949, + 982 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 15, + 1084 + ], + "new_fact": [ + 57, + 15, + 1052 + ], + "replay_indices": [ + 42, + 88, + 125, + 128, + 215, + 285, + 298, + 315, + 333, + 384, + 425, + 469, + 502, + 520, + 578, + 585, + 588, + 590, + 625, + 667, + 712, + 715, + 770, + 781, + 809, + 827, + 857, + 861, + 910, + 913, + 980, + 1009 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 70, + 14, + 1083 + ], + "new_fact": [ + 70, + 14, + 1085 + ], + "replay_indices": [ + 6, + 23, + 66, + 96, + 116, + 141, + 153, + 155, + 160, + 182, + 190, + 196, + 286, + 296, + 301, + 323, + 359, + 420, + 491, + 497, + 543, + 544, + 607, + 624, + 702, + 808, + 847, + 888, + 971, + 994, + 1003, + 1008 + ], + "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": [ + 100, + 13, + 1126 + ], + "new_fact": [ + 100, + 13, + 1138 + ], + "replay_indices": [ + 15, + 23, + 65, + 72, + 76, + 104, + 126, + 175, + 189, + 192, + 272, + 299, + 481, + 537, + 540, + 580, + 597, + 686, + 704, + 724, + 799, + 863, + 896, + 899, + 945, + 949, + 963, + 967, + 975, + 989, + 1020, + 1023 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 105, + 15, + 1110 + ], + "new_fact": [ + 105, + 15, + 1123 + ], + "replay_indices": [ + 36, + 71, + 103, + 114, + 144, + 152, + 160, + 193, + 200, + 240, + 244, + 276, + 300, + 342, + 372, + 408, + 495, + 510, + 515, + 528, + 569, + 660, + 678, + 713, + 764, + 798, + 847, + 879, + 933, + 934, + 961, + 1011 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 100, + 15, + 1131 + ], + "new_fact": [ + 100, + 15, + 1126 + ], + "replay_indices": [ + 38, + 48, + 117, + 151, + 191, + 222, + 258, + 264, + 321, + 365, + 366, + 411, + 420, + 426, + 478, + 510, + 551, + 573, + 575, + 591, + 635, + 653, + 682, + 710, + 747, + 758, + 785, + 826, + 871, + 887, + 896, + 967 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 108, + 14, + 1109 + ], + "new_fact": [ + 108, + 14, + 1130 + ], + "replay_indices": [ + 25, + 26, + 70, + 139, + 144, + 209, + 210, + 220, + 246, + 313, + 383, + 385, + 419, + 435, + 444, + 490, + 508, + 572, + 577, + 637, + 654, + 704, + 712, + 734, + 824, + 827, + 896, + 898, + 915, + 940, + 949, + 1007 + ], + "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": [ + 1100, + 18, + 1665 + ], + "new_fact": [ + 1100, + 18, + 1669 + ], + "replay_indices": [ + 0, + 9, + 22, + 25, + 26, + 42, + 67, + 86, + 88, + 94, + 150, + 167, + 273, + 362, + 395, + 440, + 453, + 557, + 573, + 617, + 619, + 643, + 657, + 684, + 711, + 840, + 844, + 858, + 874, + 904, + 907, + 931 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1086, + 19, + 1606 + ], + "new_fact": [ + 1086, + 19, + 1653 + ], + "replay_indices": [ + 0, + 41, + 60, + 120, + 122, + 132, + 144, + 152, + 179, + 216, + 231, + 242, + 247, + 288, + 312, + 339, + 341, + 365, + 398, + 406, + 457, + 538, + 574, + 576, + 637, + 673, + 680, + 694, + 710, + 829, + 849, + 879 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1049, + 18, + 1678 + ], + "new_fact": [ + 1049, + 18, + 1626 + ], + "replay_indices": [ + 2, + 12, + 48, + 80, + 81, + 104, + 161, + 165, + 197, + 219, + 248, + 271, + 294, + 296, + 359, + 367, + 464, + 489, + 545, + 564, + 677, + 678, + 704, + 754, + 775, + 811, + 829, + 853, + 854, + 923, + 1008, + 1009 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1070, + 19, + 1585 + ], + "new_fact": [ + 1070, + 19, + 1663 + ], + "replay_indices": [ + 52, + 114, + 128, + 137, + 151, + 162, + 190, + 208, + 214, + 252, + 253, + 268, + 326, + 430, + 472, + 478, + 481, + 548, + 603, + 618, + 696, + 783, + 791, + 796, + 829, + 860, + 920, + 932, + 950, + 971, + 996, + 1023 + ], + "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": 3 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1123, + 20, + 1674 + ], + "new_fact": [ + 1123, + 20, + 1632 + ], + "replay_indices": [ + 45, + 53, + 63, + 68, + 70, + 130, + 157, + 171, + 184, + 189, + 277, + 302, + 326, + 343, + 426, + 436, + 519, + 552, + 586, + 612, + 630, + 653, + 667, + 688, + 701, + 711, + 756, + 792, + 804, + 829, + 979, + 1019 + ], + "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 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1119, + 20, + 1623 + ], + "new_fact": [ + 1119, + 20, + 1626 + ], + "replay_indices": [ + 27, + 68, + 69, + 79, + 85, + 185, + 213, + 269, + 306, + 407, + 422, + 449, + 461, + 528, + 598, + 600, + 633, + 634, + 660, + 674, + 691, + 707, + 708, + 748, + 790, + 833, + 886, + 915, + 937, + 973, + 985, + 1013 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1123, + 18, + 1656 + ], + "new_fact": [ + 1123, + 18, + 1622 + ], + "replay_indices": [ + 1, + 55, + 90, + 164, + 165, + 263, + 301, + 328, + 362, + 365, + 381, + 424, + 512, + 589, + 598, + 622, + 631, + 633, + 677, + 710, + 728, + 730, + 772, + 774, + 790, + 800, + 806, + 861, + 880, + 910, + 927, + 993 + ], + "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 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1130, + 18, + 1598 + ], + "new_fact": [ + 1130, + 18, + 1559 + ], + "replay_indices": [ + 21, + 37, + 43, + 165, + 167, + 194, + 261, + 317, + 329, + 340, + 400, + 429, + 434, + 477, + 479, + 481, + 512, + 528, + 553, + 592, + 611, + 637, + 648, + 672, + 774, + 798, + 832, + 914, + 954, + 957, + 969, + 987 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "case_sha256": "ed23961b5d5fccd1cceefaf8cffaf2cd316988d7f2b8affae04fe45b77f03e1f", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270011-local-changed_atomic", + "job_type": "editing", + "phase": "confirmation", + "world": 107270011, + "memory_arm": "local", + "training_arm": "changed_atomic", + "parent_name": "w107270011-local-changed_atomic", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270011-local-changed_atomic", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 36, + 16, + 1107 + ], + "new_fact": [ + 36, + 16, + 1071 + ], + "replay_indices": [ + 43, + 75, + 92, + 98, + 134, + 179, + 255, + 301, + 372, + 378, + 421, + 472, + 545, + 576, + 600, + 608, + 625, + 634, + 715, + 727, + 742, + 790, + 811, + 859, + 871, + 880, + 918, + 962, + 965, + 968, + 974, + 977 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 54, + 15, + 1074 + ], + "new_fact": [ + 54, + 15, + 1097 + ], + "replay_indices": [ + 31, + 39, + 74, + 211, + 240, + 264, + 270, + 294, + 295, + 310, + 328, + 330, + 354, + 360, + 369, + 442, + 482, + 582, + 693, + 712, + 761, + 764, + 770, + 788, + 799, + 800, + 801, + 811, + 826, + 901, + 949, + 982 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 15, + 1084 + ], + "new_fact": [ + 57, + 15, + 1052 + ], + "replay_indices": [ + 42, + 88, + 125, + 128, + 215, + 285, + 298, + 315, + 333, + 384, + 425, + 469, + 502, + 520, + 578, + 585, + 588, + 590, + 625, + 667, + 712, + 715, + 770, + 781, + 809, + 827, + 857, + 861, + 910, + 913, + 980, + 1009 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 70, + 14, + 1083 + ], + "new_fact": [ + 70, + 14, + 1085 + ], + "replay_indices": [ + 6, + 23, + 66, + 96, + 116, + 141, + 153, + 155, + 160, + 182, + 190, + 196, + 286, + 296, + 301, + 323, + 359, + 420, + 491, + 497, + 543, + 544, + 607, + 624, + 702, + 808, + 847, + 888, + 971, + 994, + 1003, + 1008 + ], + "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": [ + 100, + 13, + 1126 + ], + "new_fact": [ + 100, + 13, + 1138 + ], + "replay_indices": [ + 15, + 23, + 65, + 72, + 76, + 104, + 126, + 175, + 189, + 192, + 272, + 299, + 481, + 537, + 540, + 580, + 597, + 686, + 704, + 724, + 799, + 863, + 896, + 899, + 945, + 949, + 963, + 967, + 975, + 989, + 1020, + 1023 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 105, + 15, + 1110 + ], + "new_fact": [ + 105, + 15, + 1123 + ], + "replay_indices": [ + 36, + 71, + 103, + 114, + 144, + 152, + 160, + 193, + 200, + 240, + 244, + 276, + 300, + 342, + 372, + 408, + 495, + 510, + 515, + 528, + 569, + 660, + 678, + 713, + 764, + 798, + 847, + 879, + 933, + 934, + 961, + 1011 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 100, + 15, + 1131 + ], + "new_fact": [ + 100, + 15, + 1126 + ], + "replay_indices": [ + 38, + 48, + 117, + 151, + 191, + 222, + 258, + 264, + 321, + 365, + 366, + 411, + 420, + 426, + 478, + 510, + 551, + 573, + 575, + 591, + 635, + 653, + 682, + 710, + 747, + 758, + 785, + 826, + 871, + 887, + 896, + 967 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 108, + 14, + 1109 + ], + "new_fact": [ + 108, + 14, + 1130 + ], + "replay_indices": [ + 25, + 26, + 70, + 139, + 144, + 209, + 210, + 220, + 246, + 313, + 383, + 385, + 419, + 435, + 444, + 490, + 508, + 572, + 577, + 637, + 654, + 704, + 712, + 734, + 824, + 827, + 896, + 898, + 915, + 940, + 949, + 1007 + ], + "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": [ + 1100, + 18, + 1665 + ], + "new_fact": [ + 1100, + 18, + 1669 + ], + "replay_indices": [ + 0, + 9, + 22, + 25, + 26, + 42, + 67, + 86, + 88, + 94, + 150, + 167, + 273, + 362, + 395, + 440, + 453, + 557, + 573, + 617, + 619, + 643, + 657, + 684, + 711, + 840, + 844, + 858, + 874, + 904, + 907, + 931 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1086, + 19, + 1606 + ], + "new_fact": [ + 1086, + 19, + 1653 + ], + "replay_indices": [ + 0, + 41, + 60, + 120, + 122, + 132, + 144, + 152, + 179, + 216, + 231, + 242, + 247, + 288, + 312, + 339, + 341, + 365, + 398, + 406, + 457, + 538, + 574, + 576, + 637, + 673, + 680, + 694, + 710, + 829, + 849, + 879 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1049, + 18, + 1678 + ], + "new_fact": [ + 1049, + 18, + 1626 + ], + "replay_indices": [ + 2, + 12, + 48, + 80, + 81, + 104, + 161, + 165, + 197, + 219, + 248, + 271, + 294, + 296, + 359, + 367, + 464, + 489, + 545, + 564, + 677, + 678, + 704, + 754, + 775, + 811, + 829, + 853, + 854, + 923, + 1008, + 1009 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1070, + 19, + 1585 + ], + "new_fact": [ + 1070, + 19, + 1663 + ], + "replay_indices": [ + 52, + 114, + 128, + 137, + 151, + 162, + 190, + 208, + 214, + 252, + 253, + 268, + 326, + 430, + 472, + 478, + 481, + 548, + 603, + 618, + 696, + 783, + 791, + 796, + 829, + 860, + 920, + 932, + 950, + 971, + 996, + 1023 + ], + "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": 3 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1123, + 20, + 1674 + ], + "new_fact": [ + 1123, + 20, + 1632 + ], + "replay_indices": [ + 45, + 53, + 63, + 68, + 70, + 130, + 157, + 171, + 184, + 189, + 277, + 302, + 326, + 343, + 426, + 436, + 519, + 552, + 586, + 612, + 630, + 653, + 667, + 688, + 701, + 711, + 756, + 792, + 804, + 829, + 979, + 1019 + ], + "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 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1119, + 20, + 1623 + ], + "new_fact": [ + 1119, + 20, + 1626 + ], + "replay_indices": [ + 27, + 68, + 69, + 79, + 85, + 185, + 213, + 269, + 306, + 407, + 422, + 449, + 461, + 528, + 598, + 600, + 633, + 634, + 660, + 674, + 691, + 707, + 708, + 748, + 790, + 833, + 886, + 915, + 937, + 973, + 985, + 1013 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1123, + 18, + 1656 + ], + "new_fact": [ + 1123, + 18, + 1622 + ], + "replay_indices": [ + 1, + 55, + 90, + 164, + 165, + 263, + 301, + 328, + 362, + 365, + 381, + 424, + 512, + 589, + 598, + 622, + 631, + 633, + 677, + 710, + 728, + 730, + 772, + 774, + 790, + 800, + 806, + 861, + 880, + 910, + 927, + 993 + ], + "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 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1130, + 18, + 1598 + ], + "new_fact": [ + 1130, + 18, + 1559 + ], + "replay_indices": [ + 21, + 37, + 43, + 165, + 167, + 194, + 261, + 317, + 329, + 340, + 400, + 429, + 434, + 477, + 479, + 481, + 512, + 528, + 553, + 592, + 611, + 637, + 648, + 672, + 774, + 798, + 832, + 914, + 954, + 957, + 969, + 987 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "case_sha256": "ed23961b5d5fccd1cceefaf8cffaf2cd316988d7f2b8affae04fe45b77f03e1f", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270011-local-changed_use", + "job_type": "editing", + "phase": "confirmation", + "world": 107270011, + "memory_arm": "local", + "training_arm": "changed_use", + "parent_name": "w107270011-local-changed_use", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270011-local-changed_use", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 36, + 16, + 1107 + ], + "new_fact": [ + 36, + 16, + 1071 + ], + "replay_indices": [ + 43, + 75, + 92, + 98, + 134, + 179, + 255, + 301, + 372, + 378, + 421, + 472, + 545, + 576, + 600, + 608, + 625, + 634, + 715, + 727, + 742, + 790, + 811, + 859, + 871, + 880, + 918, + 962, + 965, + 968, + 974, + 977 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 54, + 15, + 1074 + ], + "new_fact": [ + 54, + 15, + 1097 + ], + "replay_indices": [ + 31, + 39, + 74, + 211, + 240, + 264, + 270, + 294, + 295, + 310, + 328, + 330, + 354, + 360, + 369, + 442, + 482, + 582, + 693, + 712, + 761, + 764, + 770, + 788, + 799, + 800, + 801, + 811, + 826, + 901, + 949, + 982 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 15, + 1084 + ], + "new_fact": [ + 57, + 15, + 1052 + ], + "replay_indices": [ + 42, + 88, + 125, + 128, + 215, + 285, + 298, + 315, + 333, + 384, + 425, + 469, + 502, + 520, + 578, + 585, + 588, + 590, + 625, + 667, + 712, + 715, + 770, + 781, + 809, + 827, + 857, + 861, + 910, + 913, + 980, + 1009 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 70, + 14, + 1083 + ], + "new_fact": [ + 70, + 14, + 1085 + ], + "replay_indices": [ + 6, + 23, + 66, + 96, + 116, + 141, + 153, + 155, + 160, + 182, + 190, + 196, + 286, + 296, + 301, + 323, + 359, + 420, + 491, + 497, + 543, + 544, + 607, + 624, + 702, + 808, + 847, + 888, + 971, + 994, + 1003, + 1008 + ], + "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": [ + 100, + 13, + 1126 + ], + "new_fact": [ + 100, + 13, + 1138 + ], + "replay_indices": [ + 15, + 23, + 65, + 72, + 76, + 104, + 126, + 175, + 189, + 192, + 272, + 299, + 481, + 537, + 540, + 580, + 597, + 686, + 704, + 724, + 799, + 863, + 896, + 899, + 945, + 949, + 963, + 967, + 975, + 989, + 1020, + 1023 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 105, + 15, + 1110 + ], + "new_fact": [ + 105, + 15, + 1123 + ], + "replay_indices": [ + 36, + 71, + 103, + 114, + 144, + 152, + 160, + 193, + 200, + 240, + 244, + 276, + 300, + 342, + 372, + 408, + 495, + 510, + 515, + 528, + 569, + 660, + 678, + 713, + 764, + 798, + 847, + 879, + 933, + 934, + 961, + 1011 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 100, + 15, + 1131 + ], + "new_fact": [ + 100, + 15, + 1126 + ], + "replay_indices": [ + 38, + 48, + 117, + 151, + 191, + 222, + 258, + 264, + 321, + 365, + 366, + 411, + 420, + 426, + 478, + 510, + 551, + 573, + 575, + 591, + 635, + 653, + 682, + 710, + 747, + 758, + 785, + 826, + 871, + 887, + 896, + 967 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 108, + 14, + 1109 + ], + "new_fact": [ + 108, + 14, + 1130 + ], + "replay_indices": [ + 25, + 26, + 70, + 139, + 144, + 209, + 210, + 220, + 246, + 313, + 383, + 385, + 419, + 435, + 444, + 490, + 508, + 572, + 577, + 637, + 654, + 704, + 712, + 734, + 824, + 827, + 896, + 898, + 915, + 940, + 949, + 1007 + ], + "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": [ + 1100, + 18, + 1665 + ], + "new_fact": [ + 1100, + 18, + 1669 + ], + "replay_indices": [ + 0, + 9, + 22, + 25, + 26, + 42, + 67, + 86, + 88, + 94, + 150, + 167, + 273, + 362, + 395, + 440, + 453, + 557, + 573, + 617, + 619, + 643, + 657, + 684, + 711, + 840, + 844, + 858, + 874, + 904, + 907, + 931 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1086, + 19, + 1606 + ], + "new_fact": [ + 1086, + 19, + 1653 + ], + "replay_indices": [ + 0, + 41, + 60, + 120, + 122, + 132, + 144, + 152, + 179, + 216, + 231, + 242, + 247, + 288, + 312, + 339, + 341, + 365, + 398, + 406, + 457, + 538, + 574, + 576, + 637, + 673, + 680, + 694, + 710, + 829, + 849, + 879 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1049, + 18, + 1678 + ], + "new_fact": [ + 1049, + 18, + 1626 + ], + "replay_indices": [ + 2, + 12, + 48, + 80, + 81, + 104, + 161, + 165, + 197, + 219, + 248, + 271, + 294, + 296, + 359, + 367, + 464, + 489, + 545, + 564, + 677, + 678, + 704, + 754, + 775, + 811, + 829, + 853, + 854, + 923, + 1008, + 1009 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1070, + 19, + 1585 + ], + "new_fact": [ + 1070, + 19, + 1663 + ], + "replay_indices": [ + 52, + 114, + 128, + 137, + 151, + 162, + 190, + 208, + 214, + 252, + 253, + 268, + 326, + 430, + 472, + 478, + 481, + 548, + 603, + 618, + 696, + 783, + 791, + 796, + 829, + 860, + 920, + 932, + 950, + 971, + 996, + 1023 + ], + "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": 3 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1123, + 20, + 1674 + ], + "new_fact": [ + 1123, + 20, + 1632 + ], + "replay_indices": [ + 45, + 53, + 63, + 68, + 70, + 130, + 157, + 171, + 184, + 189, + 277, + 302, + 326, + 343, + 426, + 436, + 519, + 552, + 586, + 612, + 630, + 653, + 667, + 688, + 701, + 711, + 756, + 792, + 804, + 829, + 979, + 1019 + ], + "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 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1119, + 20, + 1623 + ], + "new_fact": [ + 1119, + 20, + 1626 + ], + "replay_indices": [ + 27, + 68, + 69, + 79, + 85, + 185, + 213, + 269, + 306, + 407, + 422, + 449, + 461, + 528, + 598, + 600, + 633, + 634, + 660, + 674, + 691, + 707, + 708, + 748, + 790, + 833, + 886, + 915, + 937, + 973, + 985, + 1013 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1123, + 18, + 1656 + ], + "new_fact": [ + 1123, + 18, + 1622 + ], + "replay_indices": [ + 1, + 55, + 90, + 164, + 165, + 263, + 301, + 328, + 362, + 365, + 381, + 424, + 512, + 589, + 598, + 622, + 631, + 633, + 677, + 710, + 728, + 730, + 772, + 774, + 790, + 800, + 806, + 861, + 880, + 910, + 927, + 993 + ], + "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 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1130, + 18, + 1598 + ], + "new_fact": [ + 1130, + 18, + 1559 + ], + "replay_indices": [ + 21, + 37, + 43, + 165, + 167, + 194, + 261, + 317, + 329, + 340, + 400, + 429, + 434, + 477, + 479, + 481, + 512, + 528, + 553, + 592, + 611, + 637, + 648, + 672, + 774, + 798, + 832, + 914, + 954, + 957, + 969, + 987 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "case_sha256": "ed23961b5d5fccd1cceefaf8cffaf2cd316988d7f2b8affae04fe45b77f03e1f", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270011-shared_full-fixed", + "job_type": "editing", + "phase": "confirmation", + "world": 107270011, + "memory_arm": "shared_full", + "training_arm": "fixed", + "parent_name": "w107270011-shared_full-fixed", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270011-shared_full-fixed", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 36, + 16, + 1107 + ], + "new_fact": [ + 36, + 16, + 1071 + ], + "replay_indices": [ + 43, + 75, + 92, + 98, + 134, + 179, + 255, + 301, + 372, + 378, + 421, + 472, + 545, + 576, + 600, + 608, + 625, + 634, + 715, + 727, + 742, + 790, + 811, + 859, + 871, + 880, + 918, + 962, + 965, + 968, + 974, + 977 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 54, + 15, + 1074 + ], + "new_fact": [ + 54, + 15, + 1097 + ], + "replay_indices": [ + 31, + 39, + 74, + 211, + 240, + 264, + 270, + 294, + 295, + 310, + 328, + 330, + 354, + 360, + 369, + 442, + 482, + 582, + 693, + 712, + 761, + 764, + 770, + 788, + 799, + 800, + 801, + 811, + 826, + 901, + 949, + 982 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 15, + 1084 + ], + "new_fact": [ + 57, + 15, + 1052 + ], + "replay_indices": [ + 42, + 88, + 125, + 128, + 215, + 285, + 298, + 315, + 333, + 384, + 425, + 469, + 502, + 520, + 578, + 585, + 588, + 590, + 625, + 667, + 712, + 715, + 770, + 781, + 809, + 827, + 857, + 861, + 910, + 913, + 980, + 1009 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 70, + 14, + 1083 + ], + "new_fact": [ + 70, + 14, + 1085 + ], + "replay_indices": [ + 6, + 23, + 66, + 96, + 116, + 141, + 153, + 155, + 160, + 182, + 190, + 196, + 286, + 296, + 301, + 323, + 359, + 420, + 491, + 497, + 543, + 544, + 607, + 624, + 702, + 808, + 847, + 888, + 971, + 994, + 1003, + 1008 + ], + "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": [ + 100, + 13, + 1126 + ], + "new_fact": [ + 100, + 13, + 1138 + ], + "replay_indices": [ + 15, + 23, + 65, + 72, + 76, + 104, + 126, + 175, + 189, + 192, + 272, + 299, + 481, + 537, + 540, + 580, + 597, + 686, + 704, + 724, + 799, + 863, + 896, + 899, + 945, + 949, + 963, + 967, + 975, + 989, + 1020, + 1023 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 105, + 15, + 1110 + ], + "new_fact": [ + 105, + 15, + 1123 + ], + "replay_indices": [ + 36, + 71, + 103, + 114, + 144, + 152, + 160, + 193, + 200, + 240, + 244, + 276, + 300, + 342, + 372, + 408, + 495, + 510, + 515, + 528, + 569, + 660, + 678, + 713, + 764, + 798, + 847, + 879, + 933, + 934, + 961, + 1011 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 100, + 15, + 1131 + ], + "new_fact": [ + 100, + 15, + 1126 + ], + "replay_indices": [ + 38, + 48, + 117, + 151, + 191, + 222, + 258, + 264, + 321, + 365, + 366, + 411, + 420, + 426, + 478, + 510, + 551, + 573, + 575, + 591, + 635, + 653, + 682, + 710, + 747, + 758, + 785, + 826, + 871, + 887, + 896, + 967 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 108, + 14, + 1109 + ], + "new_fact": [ + 108, + 14, + 1130 + ], + "replay_indices": [ + 25, + 26, + 70, + 139, + 144, + 209, + 210, + 220, + 246, + 313, + 383, + 385, + 419, + 435, + 444, + 490, + 508, + 572, + 577, + 637, + 654, + 704, + 712, + 734, + 824, + 827, + 896, + 898, + 915, + 940, + 949, + 1007 + ], + "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": [ + 1100, + 18, + 1665 + ], + "new_fact": [ + 1100, + 18, + 1669 + ], + "replay_indices": [ + 0, + 9, + 22, + 25, + 26, + 42, + 67, + 86, + 88, + 94, + 150, + 167, + 273, + 362, + 395, + 440, + 453, + 557, + 573, + 617, + 619, + 643, + 657, + 684, + 711, + 840, + 844, + 858, + 874, + 904, + 907, + 931 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1086, + 19, + 1606 + ], + "new_fact": [ + 1086, + 19, + 1653 + ], + "replay_indices": [ + 0, + 41, + 60, + 120, + 122, + 132, + 144, + 152, + 179, + 216, + 231, + 242, + 247, + 288, + 312, + 339, + 341, + 365, + 398, + 406, + 457, + 538, + 574, + 576, + 637, + 673, + 680, + 694, + 710, + 829, + 849, + 879 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1049, + 18, + 1678 + ], + "new_fact": [ + 1049, + 18, + 1626 + ], + "replay_indices": [ + 2, + 12, + 48, + 80, + 81, + 104, + 161, + 165, + 197, + 219, + 248, + 271, + 294, + 296, + 359, + 367, + 464, + 489, + 545, + 564, + 677, + 678, + 704, + 754, + 775, + 811, + 829, + 853, + 854, + 923, + 1008, + 1009 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1070, + 19, + 1585 + ], + "new_fact": [ + 1070, + 19, + 1663 + ], + "replay_indices": [ + 52, + 114, + 128, + 137, + 151, + 162, + 190, + 208, + 214, + 252, + 253, + 268, + 326, + 430, + 472, + 478, + 481, + 548, + 603, + 618, + 696, + 783, + 791, + 796, + 829, + 860, + 920, + 932, + 950, + 971, + 996, + 1023 + ], + "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": 3 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1123, + 20, + 1674 + ], + "new_fact": [ + 1123, + 20, + 1632 + ], + "replay_indices": [ + 45, + 53, + 63, + 68, + 70, + 130, + 157, + 171, + 184, + 189, + 277, + 302, + 326, + 343, + 426, + 436, + 519, + 552, + 586, + 612, + 630, + 653, + 667, + 688, + 701, + 711, + 756, + 792, + 804, + 829, + 979, + 1019 + ], + "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 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1119, + 20, + 1623 + ], + "new_fact": [ + 1119, + 20, + 1626 + ], + "replay_indices": [ + 27, + 68, + 69, + 79, + 85, + 185, + 213, + 269, + 306, + 407, + 422, + 449, + 461, + 528, + 598, + 600, + 633, + 634, + 660, + 674, + 691, + 707, + 708, + 748, + 790, + 833, + 886, + 915, + 937, + 973, + 985, + 1013 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1123, + 18, + 1656 + ], + "new_fact": [ + 1123, + 18, + 1622 + ], + "replay_indices": [ + 1, + 55, + 90, + 164, + 165, + 263, + 301, + 328, + 362, + 365, + 381, + 424, + 512, + 589, + 598, + 622, + 631, + 633, + 677, + 710, + 728, + 730, + 772, + 774, + 790, + 800, + 806, + 861, + 880, + 910, + 927, + 993 + ], + "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 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1130, + 18, + 1598 + ], + "new_fact": [ + 1130, + 18, + 1559 + ], + "replay_indices": [ + 21, + 37, + 43, + 165, + 167, + 194, + 261, + 317, + 329, + 340, + 400, + 429, + 434, + 477, + 479, + 481, + 512, + 528, + 553, + 592, + 611, + 637, + 648, + 672, + 774, + 798, + 832, + 914, + 954, + 957, + 969, + 987 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "case_sha256": "ed23961b5d5fccd1cceefaf8cffaf2cd316988d7f2b8affae04fe45b77f03e1f", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270011-shared_full-changed_atomic", + "job_type": "editing", + "phase": "confirmation", + "world": 107270011, + "memory_arm": "shared_full", + "training_arm": "changed_atomic", + "parent_name": "w107270011-shared_full-changed_atomic", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270011-shared_full-changed_atomic", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 36, + 16, + 1107 + ], + "new_fact": [ + 36, + 16, + 1071 + ], + "replay_indices": [ + 43, + 75, + 92, + 98, + 134, + 179, + 255, + 301, + 372, + 378, + 421, + 472, + 545, + 576, + 600, + 608, + 625, + 634, + 715, + 727, + 742, + 790, + 811, + 859, + 871, + 880, + 918, + 962, + 965, + 968, + 974, + 977 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 54, + 15, + 1074 + ], + "new_fact": [ + 54, + 15, + 1097 + ], + "replay_indices": [ + 31, + 39, + 74, + 211, + 240, + 264, + 270, + 294, + 295, + 310, + 328, + 330, + 354, + 360, + 369, + 442, + 482, + 582, + 693, + 712, + 761, + 764, + 770, + 788, + 799, + 800, + 801, + 811, + 826, + 901, + 949, + 982 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 15, + 1084 + ], + "new_fact": [ + 57, + 15, + 1052 + ], + "replay_indices": [ + 42, + 88, + 125, + 128, + 215, + 285, + 298, + 315, + 333, + 384, + 425, + 469, + 502, + 520, + 578, + 585, + 588, + 590, + 625, + 667, + 712, + 715, + 770, + 781, + 809, + 827, + 857, + 861, + 910, + 913, + 980, + 1009 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 70, + 14, + 1083 + ], + "new_fact": [ + 70, + 14, + 1085 + ], + "replay_indices": [ + 6, + 23, + 66, + 96, + 116, + 141, + 153, + 155, + 160, + 182, + 190, + 196, + 286, + 296, + 301, + 323, + 359, + 420, + 491, + 497, + 543, + 544, + 607, + 624, + 702, + 808, + 847, + 888, + 971, + 994, + 1003, + 1008 + ], + "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": [ + 100, + 13, + 1126 + ], + "new_fact": [ + 100, + 13, + 1138 + ], + "replay_indices": [ + 15, + 23, + 65, + 72, + 76, + 104, + 126, + 175, + 189, + 192, + 272, + 299, + 481, + 537, + 540, + 580, + 597, + 686, + 704, + 724, + 799, + 863, + 896, + 899, + 945, + 949, + 963, + 967, + 975, + 989, + 1020, + 1023 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 105, + 15, + 1110 + ], + "new_fact": [ + 105, + 15, + 1123 + ], + "replay_indices": [ + 36, + 71, + 103, + 114, + 144, + 152, + 160, + 193, + 200, + 240, + 244, + 276, + 300, + 342, + 372, + 408, + 495, + 510, + 515, + 528, + 569, + 660, + 678, + 713, + 764, + 798, + 847, + 879, + 933, + 934, + 961, + 1011 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 100, + 15, + 1131 + ], + "new_fact": [ + 100, + 15, + 1126 + ], + "replay_indices": [ + 38, + 48, + 117, + 151, + 191, + 222, + 258, + 264, + 321, + 365, + 366, + 411, + 420, + 426, + 478, + 510, + 551, + 573, + 575, + 591, + 635, + 653, + 682, + 710, + 747, + 758, + 785, + 826, + 871, + 887, + 896, + 967 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 108, + 14, + 1109 + ], + "new_fact": [ + 108, + 14, + 1130 + ], + "replay_indices": [ + 25, + 26, + 70, + 139, + 144, + 209, + 210, + 220, + 246, + 313, + 383, + 385, + 419, + 435, + 444, + 490, + 508, + 572, + 577, + 637, + 654, + 704, + 712, + 734, + 824, + 827, + 896, + 898, + 915, + 940, + 949, + 1007 + ], + "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": [ + 1100, + 18, + 1665 + ], + "new_fact": [ + 1100, + 18, + 1669 + ], + "replay_indices": [ + 0, + 9, + 22, + 25, + 26, + 42, + 67, + 86, + 88, + 94, + 150, + 167, + 273, + 362, + 395, + 440, + 453, + 557, + 573, + 617, + 619, + 643, + 657, + 684, + 711, + 840, + 844, + 858, + 874, + 904, + 907, + 931 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1086, + 19, + 1606 + ], + "new_fact": [ + 1086, + 19, + 1653 + ], + "replay_indices": [ + 0, + 41, + 60, + 120, + 122, + 132, + 144, + 152, + 179, + 216, + 231, + 242, + 247, + 288, + 312, + 339, + 341, + 365, + 398, + 406, + 457, + 538, + 574, + 576, + 637, + 673, + 680, + 694, + 710, + 829, + 849, + 879 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1049, + 18, + 1678 + ], + "new_fact": [ + 1049, + 18, + 1626 + ], + "replay_indices": [ + 2, + 12, + 48, + 80, + 81, + 104, + 161, + 165, + 197, + 219, + 248, + 271, + 294, + 296, + 359, + 367, + 464, + 489, + 545, + 564, + 677, + 678, + 704, + 754, + 775, + 811, + 829, + 853, + 854, + 923, + 1008, + 1009 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1070, + 19, + 1585 + ], + "new_fact": [ + 1070, + 19, + 1663 + ], + "replay_indices": [ + 52, + 114, + 128, + 137, + 151, + 162, + 190, + 208, + 214, + 252, + 253, + 268, + 326, + 430, + 472, + 478, + 481, + 548, + 603, + 618, + 696, + 783, + 791, + 796, + 829, + 860, + 920, + 932, + 950, + 971, + 996, + 1023 + ], + "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": 3 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1123, + 20, + 1674 + ], + "new_fact": [ + 1123, + 20, + 1632 + ], + "replay_indices": [ + 45, + 53, + 63, + 68, + 70, + 130, + 157, + 171, + 184, + 189, + 277, + 302, + 326, + 343, + 426, + 436, + 519, + 552, + 586, + 612, + 630, + 653, + 667, + 688, + 701, + 711, + 756, + 792, + 804, + 829, + 979, + 1019 + ], + "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 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1119, + 20, + 1623 + ], + "new_fact": [ + 1119, + 20, + 1626 + ], + "replay_indices": [ + 27, + 68, + 69, + 79, + 85, + 185, + 213, + 269, + 306, + 407, + 422, + 449, + 461, + 528, + 598, + 600, + 633, + 634, + 660, + 674, + 691, + 707, + 708, + 748, + 790, + 833, + 886, + 915, + 937, + 973, + 985, + 1013 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1123, + 18, + 1656 + ], + "new_fact": [ + 1123, + 18, + 1622 + ], + "replay_indices": [ + 1, + 55, + 90, + 164, + 165, + 263, + 301, + 328, + 362, + 365, + 381, + 424, + 512, + 589, + 598, + 622, + 631, + 633, + 677, + 710, + 728, + 730, + 772, + 774, + 790, + 800, + 806, + 861, + 880, + 910, + 927, + 993 + ], + "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 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1130, + 18, + 1598 + ], + "new_fact": [ + 1130, + 18, + 1559 + ], + "replay_indices": [ + 21, + 37, + 43, + 165, + 167, + 194, + 261, + 317, + 329, + 340, + 400, + 429, + 434, + 477, + 479, + 481, + 512, + 528, + 553, + 592, + 611, + 637, + 648, + 672, + 774, + 798, + 832, + 914, + 954, + 957, + 969, + 987 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "case_sha256": "ed23961b5d5fccd1cceefaf8cffaf2cd316988d7f2b8affae04fe45b77f03e1f", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270011-shared_full-changed_use", + "job_type": "editing", + "phase": "confirmation", + "world": 107270011, + "memory_arm": "shared_full", + "training_arm": "changed_use", + "parent_name": "w107270011-shared_full-changed_use", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270011-shared_full-changed_use", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 36, + 16, + 1107 + ], + "new_fact": [ + 36, + 16, + 1071 + ], + "replay_indices": [ + 43, + 75, + 92, + 98, + 134, + 179, + 255, + 301, + 372, + 378, + 421, + 472, + 545, + 576, + 600, + 608, + 625, + 634, + 715, + 727, + 742, + 790, + 811, + 859, + 871, + 880, + 918, + 962, + 965, + 968, + 974, + 977 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 54, + 15, + 1074 + ], + "new_fact": [ + 54, + 15, + 1097 + ], + "replay_indices": [ + 31, + 39, + 74, + 211, + 240, + 264, + 270, + 294, + 295, + 310, + 328, + 330, + 354, + 360, + 369, + 442, + 482, + 582, + 693, + 712, + 761, + 764, + 770, + 788, + 799, + 800, + 801, + 811, + 826, + 901, + 949, + 982 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 15, + 1084 + ], + "new_fact": [ + 57, + 15, + 1052 + ], + "replay_indices": [ + 42, + 88, + 125, + 128, + 215, + 285, + 298, + 315, + 333, + 384, + 425, + 469, + 502, + 520, + 578, + 585, + 588, + 590, + 625, + 667, + 712, + 715, + 770, + 781, + 809, + 827, + 857, + 861, + 910, + 913, + 980, + 1009 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 70, + 14, + 1083 + ], + "new_fact": [ + 70, + 14, + 1085 + ], + "replay_indices": [ + 6, + 23, + 66, + 96, + 116, + 141, + 153, + 155, + 160, + 182, + 190, + 196, + 286, + 296, + 301, + 323, + 359, + 420, + 491, + 497, + 543, + 544, + 607, + 624, + 702, + 808, + 847, + 888, + 971, + 994, + 1003, + 1008 + ], + "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": [ + 100, + 13, + 1126 + ], + "new_fact": [ + 100, + 13, + 1138 + ], + "replay_indices": [ + 15, + 23, + 65, + 72, + 76, + 104, + 126, + 175, + 189, + 192, + 272, + 299, + 481, + 537, + 540, + 580, + 597, + 686, + 704, + 724, + 799, + 863, + 896, + 899, + 945, + 949, + 963, + 967, + 975, + 989, + 1020, + 1023 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 105, + 15, + 1110 + ], + "new_fact": [ + 105, + 15, + 1123 + ], + "replay_indices": [ + 36, + 71, + 103, + 114, + 144, + 152, + 160, + 193, + 200, + 240, + 244, + 276, + 300, + 342, + 372, + 408, + 495, + 510, + 515, + 528, + 569, + 660, + 678, + 713, + 764, + 798, + 847, + 879, + 933, + 934, + 961, + 1011 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 100, + 15, + 1131 + ], + "new_fact": [ + 100, + 15, + 1126 + ], + "replay_indices": [ + 38, + 48, + 117, + 151, + 191, + 222, + 258, + 264, + 321, + 365, + 366, + 411, + 420, + 426, + 478, + 510, + 551, + 573, + 575, + 591, + 635, + 653, + 682, + 710, + 747, + 758, + 785, + 826, + 871, + 887, + 896, + 967 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 108, + 14, + 1109 + ], + "new_fact": [ + 108, + 14, + 1130 + ], + "replay_indices": [ + 25, + 26, + 70, + 139, + 144, + 209, + 210, + 220, + 246, + 313, + 383, + 385, + 419, + 435, + 444, + 490, + 508, + 572, + 577, + 637, + 654, + 704, + 712, + 734, + 824, + 827, + 896, + 898, + 915, + 940, + 949, + 1007 + ], + "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": [ + 1100, + 18, + 1665 + ], + "new_fact": [ + 1100, + 18, + 1669 + ], + "replay_indices": [ + 0, + 9, + 22, + 25, + 26, + 42, + 67, + 86, + 88, + 94, + 150, + 167, + 273, + 362, + 395, + 440, + 453, + 557, + 573, + 617, + 619, + 643, + 657, + 684, + 711, + 840, + 844, + 858, + 874, + 904, + 907, + 931 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1086, + 19, + 1606 + ], + "new_fact": [ + 1086, + 19, + 1653 + ], + "replay_indices": [ + 0, + 41, + 60, + 120, + 122, + 132, + 144, + 152, + 179, + 216, + 231, + 242, + 247, + 288, + 312, + 339, + 341, + 365, + 398, + 406, + 457, + 538, + 574, + 576, + 637, + 673, + 680, + 694, + 710, + 829, + 849, + 879 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1049, + 18, + 1678 + ], + "new_fact": [ + 1049, + 18, + 1626 + ], + "replay_indices": [ + 2, + 12, + 48, + 80, + 81, + 104, + 161, + 165, + 197, + 219, + 248, + 271, + 294, + 296, + 359, + 367, + 464, + 489, + 545, + 564, + 677, + 678, + 704, + 754, + 775, + 811, + 829, + 853, + 854, + 923, + 1008, + 1009 + ], + "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": 5 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1070, + 19, + 1585 + ], + "new_fact": [ + 1070, + 19, + 1663 + ], + "replay_indices": [ + 52, + 114, + 128, + 137, + 151, + 162, + 190, + 208, + 214, + 252, + 253, + 268, + 326, + 430, + 472, + 478, + 481, + 548, + 603, + 618, + 696, + 783, + 791, + 796, + 829, + 860, + 920, + 932, + 950, + 971, + 996, + 1023 + ], + "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": 3 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1123, + 20, + 1674 + ], + "new_fact": [ + 1123, + 20, + 1632 + ], + "replay_indices": [ + 45, + 53, + 63, + 68, + 70, + 130, + 157, + 171, + 184, + 189, + 277, + 302, + 326, + 343, + 426, + 436, + 519, + 552, + 586, + 612, + 630, + 653, + 667, + 688, + 701, + 711, + 756, + 792, + 804, + 829, + 979, + 1019 + ], + "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 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1119, + 20, + 1623 + ], + "new_fact": [ + 1119, + 20, + 1626 + ], + "replay_indices": [ + 27, + 68, + 69, + 79, + 85, + 185, + 213, + 269, + 306, + 407, + 422, + 449, + 461, + 528, + 598, + 600, + 633, + 634, + 660, + 674, + 691, + 707, + 708, + 748, + 790, + 833, + 886, + 915, + 937, + 973, + 985, + 1013 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1123, + 18, + 1656 + ], + "new_fact": [ + 1123, + 18, + 1622 + ], + "replay_indices": [ + 1, + 55, + 90, + 164, + 165, + 263, + 301, + 328, + 362, + 365, + 381, + 424, + 512, + 589, + 598, + 622, + 631, + 633, + 677, + 710, + 728, + 730, + 772, + 774, + 790, + 800, + 806, + 861, + 880, + 910, + 927, + 993 + ], + "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 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1130, + 18, + 1598 + ], + "new_fact": [ + 1130, + 18, + 1559 + ], + "replay_indices": [ + 21, + 37, + 43, + 165, + 167, + 194, + 261, + 317, + 329, + 340, + 400, + 429, + 434, + 477, + 479, + 481, + 512, + 528, + 553, + 592, + 611, + 637, + 648, + 672, + 774, + 798, + 832, + 914, + 954, + 957, + 969, + 987 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "case_sha256": "ed23961b5d5fccd1cceefaf8cffaf2cd316988d7f2b8affae04fe45b77f03e1f", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270012-local-fixed", + "job_type": "editing", + "phase": "confirmation", + "world": 107270012, + "memory_arm": "local", + "training_arm": "fixed", + "parent_name": "w107270012-local-fixed", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270012-local-fixed", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 28, + 13, + 1064 + ], + "new_fact": [ + 28, + 13, + 1105 + ], + "replay_indices": [ + 31, + 35, + 57, + 87, + 154, + 167, + 189, + 192, + 208, + 238, + 267, + 303, + 315, + 328, + 329, + 347, + 372, + 404, + 501, + 513, + 552, + 587, + 719, + 720, + 807, + 810, + 833, + 853, + 954, + 963, + 966, + 999 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 49, + 14, + 1082 + ], + "new_fact": [ + 49, + 14, + 1045 + ], + "replay_indices": [ + 30, + 59, + 62, + 97, + 162, + 183, + 184, + 249, + 304, + 374, + 397, + 459, + 475, + 480, + 488, + 524, + 532, + 580, + 592, + 647, + 679, + 680, + 686, + 716, + 728, + 761, + 844, + 858, + 925, + 948, + 962, + 1005 + ], + "affected_untrained_n": { + "D_first_familiar": 4, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 4, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "first_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 78, + 16, + 1070 + ], + "new_fact": [ + 78, + 16, + 1093 + ], + "replay_indices": [ + 38, + 57, + 142, + 167, + 200, + 308, + 316, + 340, + 345, + 411, + 414, + 416, + 418, + 422, + 438, + 471, + 500, + 508, + 516, + 615, + 645, + 652, + 676, + 684, + 744, + 756, + 795, + 892, + 904, + 915, + 926, + 983 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 15, + 1085 + ], + "new_fact": [ + 57, + 15, + 1081 + ], + "replay_indices": [ + 57, + 69, + 148, + 161, + 177, + 212, + 216, + 226, + 230, + 273, + 289, + 298, + 332, + 413, + 450, + 539, + 547, + 572, + 631, + 660, + 708, + 724, + 747, + 840, + 864, + 875, + 904, + 954, + 966, + 983, + 1006, + 1008 + ], + "affected_untrained_n": { + "D_first_familiar": 4, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 4, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1128 + ], + "new_fact": [ + 89, + 16, + 1123 + ], + "replay_indices": [ + 81, + 90, + 204, + 212, + 274, + 334, + 337, + 371, + 453, + 469, + 491, + 503, + 545, + 583, + 612, + 613, + 615, + 619, + 677, + 703, + 783, + 829, + 848, + 858, + 863, + 895, + 924, + 930, + 945, + 993, + 1013, + 1022 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 110, + 13, + 1134 + ], + "new_fact": [ + 110, + 13, + 1130 + ], + "replay_indices": [ + 13, + 90, + 93, + 102, + 147, + 155, + 179, + 182, + 194, + 212, + 228, + 287, + 313, + 331, + 459, + 469, + 476, + 543, + 567, + 569, + 630, + 655, + 673, + 721, + 732, + 741, + 760, + 789, + 938, + 1000, + 1003, + 1015 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 107, + 14, + 1124 + ], + "new_fact": [ + 107, + 14, + 1109 + ], + "replay_indices": [ + 35, + 109, + 125, + 146, + 164, + 170, + 209, + 247, + 350, + 362, + 378, + 412, + 452, + 471, + 519, + 559, + 568, + 584, + 600, + 608, + 632, + 633, + 680, + 774, + 829, + 831, + 834, + 852, + 880, + 886, + 907, + 992 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 91, + 16, + 1116 + ], + "new_fact": [ + 91, + 16, + 1139 + ], + "replay_indices": [ + 45, + 47, + 84, + 155, + 171, + 192, + 195, + 208, + 236, + 243, + 295, + 327, + 328, + 404, + 406, + 427, + 501, + 508, + 565, + 580, + 583, + 647, + 688, + 773, + 783, + 806, + 851, + 855, + 909, + 927, + 935, + 989 + ], + "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": [ + 1063, + 20, + 1631 + ], + "new_fact": [ + 1063, + 20, + 1648 + ], + "replay_indices": [ + 19, + 23, + 31, + 62, + 73, + 81, + 161, + 182, + 192, + 300, + 303, + 372, + 544, + 548, + 556, + 597, + 632, + 649, + 689, + 736, + 750, + 781, + 828, + 854, + 870, + 904, + 908, + 943, + 964, + 968, + 973, + 1021 + ], + "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": 6 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1073, + 18, + 1679 + ], + "new_fact": [ + 1073, + 18, + 1583 + ], + "replay_indices": [ + 26, + 91, + 94, + 121, + 146, + 156, + 172, + 176, + 180, + 211, + 223, + 233, + 244, + 301, + 305, + 313, + 334, + 417, + 465, + 497, + 583, + 594, + 664, + 669, + 694, + 711, + 807, + 819, + 824, + 877, + 958, + 985 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1101, + 19, + 1626 + ], + "new_fact": [ + 1101, + 19, + 1664 + ], + "replay_indices": [ + 19, + 83, + 105, + 124, + 152, + 164, + 249, + 260, + 314, + 318, + 348, + 354, + 366, + 390, + 448, + 464, + 506, + 509, + 530, + 557, + 598, + 675, + 687, + 730, + 757, + 772, + 854, + 941, + 975, + 1001, + 1002, + 1007 + ], + "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": 1 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1060, + 17, + 1656 + ], + "new_fact": [ + 1060, + 17, + 1620 + ], + "replay_indices": [ + 16, + 33, + 42, + 80, + 89, + 116, + 118, + 207, + 213, + 263, + 280, + 283, + 333, + 342, + 413, + 473, + 496, + 519, + 535, + 563, + 565, + 619, + 671, + 682, + 716, + 724, + 828, + 851, + 852, + 876, + 1001, + 1003 + ], + "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": 3 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1115, + 17, + 1669 + ], + "new_fact": [ + 1115, + 17, + 1581 + ], + "replay_indices": [ + 32, + 48, + 98, + 161, + 182, + 186, + 212, + 217, + 268, + 302, + 316, + 317, + 324, + 374, + 404, + 419, + 455, + 470, + 507, + 514, + 531, + 534, + 624, + 679, + 706, + 736, + 761, + 778, + 789, + 837, + 879, + 931 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1118, + 17, + 1625 + ], + "new_fact": [ + 1118, + 17, + 1608 + ], + "replay_indices": [ + 26, + 59, + 80, + 86, + 96, + 154, + 189, + 218, + 265, + 290, + 318, + 390, + 401, + 467, + 502, + 628, + 658, + 664, + 678, + 756, + 760, + 791, + 794, + 808, + 853, + 854, + 906, + 925, + 941, + 947, + 990, + 992 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1135, + 18, + 1575 + ], + "new_fact": [ + 1135, + 18, + 1663 + ], + "replay_indices": [ + 29, + 55, + 78, + 162, + 194, + 199, + 210, + 247, + 266, + 273, + 343, + 382, + 392, + 408, + 413, + 462, + 473, + 564, + 625, + 644, + 697, + 737, + 745, + 863, + 890, + 903, + 941, + 961, + 974, + 999, + 1009, + 1013 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1124, + 20, + 1678 + ], + "new_fact": [ + 1124, + 20, + 1602 + ], + "replay_indices": [ + 54, + 95, + 100, + 103, + 156, + 201, + 242, + 249, + 387, + 397, + 408, + 460, + 478, + 510, + 568, + 569, + 573, + 593, + 605, + 608, + 616, + 637, + 758, + 796, + 807, + 832, + 858, + 871, + 899, + 915, + 946, + 1015 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "case_sha256": "cc5e29e398ff05cc74287b1d5d79a42507471bd60acdb9d6d8fc4fa3d2731d1d", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270012-local-changed_atomic", + "job_type": "editing", + "phase": "confirmation", + "world": 107270012, + "memory_arm": "local", + "training_arm": "changed_atomic", + "parent_name": "w107270012-local-changed_atomic", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270012-local-changed_atomic", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 28, + 13, + 1064 + ], + "new_fact": [ + 28, + 13, + 1105 + ], + "replay_indices": [ + 31, + 35, + 57, + 87, + 154, + 167, + 189, + 192, + 208, + 238, + 267, + 303, + 315, + 328, + 329, + 347, + 372, + 404, + 501, + 513, + 552, + 587, + 719, + 720, + 807, + 810, + 833, + 853, + 954, + 963, + 966, + 999 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 49, + 14, + 1082 + ], + "new_fact": [ + 49, + 14, + 1045 + ], + "replay_indices": [ + 30, + 59, + 62, + 97, + 162, + 183, + 184, + 249, + 304, + 374, + 397, + 459, + 475, + 480, + 488, + 524, + 532, + 580, + 592, + 647, + 679, + 680, + 686, + 716, + 728, + 761, + 844, + 858, + 925, + 948, + 962, + 1005 + ], + "affected_untrained_n": { + "D_first_familiar": 4, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 4, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "first_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 78, + 16, + 1070 + ], + "new_fact": [ + 78, + 16, + 1093 + ], + "replay_indices": [ + 38, + 57, + 142, + 167, + 200, + 308, + 316, + 340, + 345, + 411, + 414, + 416, + 418, + 422, + 438, + 471, + 500, + 508, + 516, + 615, + 645, + 652, + 676, + 684, + 744, + 756, + 795, + 892, + 904, + 915, + 926, + 983 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 15, + 1085 + ], + "new_fact": [ + 57, + 15, + 1081 + ], + "replay_indices": [ + 57, + 69, + 148, + 161, + 177, + 212, + 216, + 226, + 230, + 273, + 289, + 298, + 332, + 413, + 450, + 539, + 547, + 572, + 631, + 660, + 708, + 724, + 747, + 840, + 864, + 875, + 904, + 954, + 966, + 983, + 1006, + 1008 + ], + "affected_untrained_n": { + "D_first_familiar": 4, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 4, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1128 + ], + "new_fact": [ + 89, + 16, + 1123 + ], + "replay_indices": [ + 81, + 90, + 204, + 212, + 274, + 334, + 337, + 371, + 453, + 469, + 491, + 503, + 545, + 583, + 612, + 613, + 615, + 619, + 677, + 703, + 783, + 829, + 848, + 858, + 863, + 895, + 924, + 930, + 945, + 993, + 1013, + 1022 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 110, + 13, + 1134 + ], + "new_fact": [ + 110, + 13, + 1130 + ], + "replay_indices": [ + 13, + 90, + 93, + 102, + 147, + 155, + 179, + 182, + 194, + 212, + 228, + 287, + 313, + 331, + 459, + 469, + 476, + 543, + 567, + 569, + 630, + 655, + 673, + 721, + 732, + 741, + 760, + 789, + 938, + 1000, + 1003, + 1015 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 107, + 14, + 1124 + ], + "new_fact": [ + 107, + 14, + 1109 + ], + "replay_indices": [ + 35, + 109, + 125, + 146, + 164, + 170, + 209, + 247, + 350, + 362, + 378, + 412, + 452, + 471, + 519, + 559, + 568, + 584, + 600, + 608, + 632, + 633, + 680, + 774, + 829, + 831, + 834, + 852, + 880, + 886, + 907, + 992 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 91, + 16, + 1116 + ], + "new_fact": [ + 91, + 16, + 1139 + ], + "replay_indices": [ + 45, + 47, + 84, + 155, + 171, + 192, + 195, + 208, + 236, + 243, + 295, + 327, + 328, + 404, + 406, + 427, + 501, + 508, + 565, + 580, + 583, + 647, + 688, + 773, + 783, + 806, + 851, + 855, + 909, + 927, + 935, + 989 + ], + "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": [ + 1063, + 20, + 1631 + ], + "new_fact": [ + 1063, + 20, + 1648 + ], + "replay_indices": [ + 19, + 23, + 31, + 62, + 73, + 81, + 161, + 182, + 192, + 300, + 303, + 372, + 544, + 548, + 556, + 597, + 632, + 649, + 689, + 736, + 750, + 781, + 828, + 854, + 870, + 904, + 908, + 943, + 964, + 968, + 973, + 1021 + ], + "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": 6 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1073, + 18, + 1679 + ], + "new_fact": [ + 1073, + 18, + 1583 + ], + "replay_indices": [ + 26, + 91, + 94, + 121, + 146, + 156, + 172, + 176, + 180, + 211, + 223, + 233, + 244, + 301, + 305, + 313, + 334, + 417, + 465, + 497, + 583, + 594, + 664, + 669, + 694, + 711, + 807, + 819, + 824, + 877, + 958, + 985 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1101, + 19, + 1626 + ], + "new_fact": [ + 1101, + 19, + 1664 + ], + "replay_indices": [ + 19, + 83, + 105, + 124, + 152, + 164, + 249, + 260, + 314, + 318, + 348, + 354, + 366, + 390, + 448, + 464, + 506, + 509, + 530, + 557, + 598, + 675, + 687, + 730, + 757, + 772, + 854, + 941, + 975, + 1001, + 1002, + 1007 + ], + "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": 1 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1060, + 17, + 1656 + ], + "new_fact": [ + 1060, + 17, + 1620 + ], + "replay_indices": [ + 16, + 33, + 42, + 80, + 89, + 116, + 118, + 207, + 213, + 263, + 280, + 283, + 333, + 342, + 413, + 473, + 496, + 519, + 535, + 563, + 565, + 619, + 671, + 682, + 716, + 724, + 828, + 851, + 852, + 876, + 1001, + 1003 + ], + "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": 3 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1115, + 17, + 1669 + ], + "new_fact": [ + 1115, + 17, + 1581 + ], + "replay_indices": [ + 32, + 48, + 98, + 161, + 182, + 186, + 212, + 217, + 268, + 302, + 316, + 317, + 324, + 374, + 404, + 419, + 455, + 470, + 507, + 514, + 531, + 534, + 624, + 679, + 706, + 736, + 761, + 778, + 789, + 837, + 879, + 931 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1118, + 17, + 1625 + ], + "new_fact": [ + 1118, + 17, + 1608 + ], + "replay_indices": [ + 26, + 59, + 80, + 86, + 96, + 154, + 189, + 218, + 265, + 290, + 318, + 390, + 401, + 467, + 502, + 628, + 658, + 664, + 678, + 756, + 760, + 791, + 794, + 808, + 853, + 854, + 906, + 925, + 941, + 947, + 990, + 992 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1135, + 18, + 1575 + ], + "new_fact": [ + 1135, + 18, + 1663 + ], + "replay_indices": [ + 29, + 55, + 78, + 162, + 194, + 199, + 210, + 247, + 266, + 273, + 343, + 382, + 392, + 408, + 413, + 462, + 473, + 564, + 625, + 644, + 697, + 737, + 745, + 863, + 890, + 903, + 941, + 961, + 974, + 999, + 1009, + 1013 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1124, + 20, + 1678 + ], + "new_fact": [ + 1124, + 20, + 1602 + ], + "replay_indices": [ + 54, + 95, + 100, + 103, + 156, + 201, + 242, + 249, + 387, + 397, + 408, + 460, + 478, + 510, + 568, + 569, + 573, + 593, + 605, + 608, + 616, + 637, + 758, + 796, + 807, + 832, + 858, + 871, + 899, + 915, + 946, + 1015 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "case_sha256": "cc5e29e398ff05cc74287b1d5d79a42507471bd60acdb9d6d8fc4fa3d2731d1d", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270012-local-changed_use", + "job_type": "editing", + "phase": "confirmation", + "world": 107270012, + "memory_arm": "local", + "training_arm": "changed_use", + "parent_name": "w107270012-local-changed_use", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270012-local-changed_use", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 28, + 13, + 1064 + ], + "new_fact": [ + 28, + 13, + 1105 + ], + "replay_indices": [ + 31, + 35, + 57, + 87, + 154, + 167, + 189, + 192, + 208, + 238, + 267, + 303, + 315, + 328, + 329, + 347, + 372, + 404, + 501, + 513, + 552, + 587, + 719, + 720, + 807, + 810, + 833, + 853, + 954, + 963, + 966, + 999 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 49, + 14, + 1082 + ], + "new_fact": [ + 49, + 14, + 1045 + ], + "replay_indices": [ + 30, + 59, + 62, + 97, + 162, + 183, + 184, + 249, + 304, + 374, + 397, + 459, + 475, + 480, + 488, + 524, + 532, + 580, + 592, + 647, + 679, + 680, + 686, + 716, + 728, + 761, + 844, + 858, + 925, + 948, + 962, + 1005 + ], + "affected_untrained_n": { + "D_first_familiar": 4, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 4, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "first_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 78, + 16, + 1070 + ], + "new_fact": [ + 78, + 16, + 1093 + ], + "replay_indices": [ + 38, + 57, + 142, + 167, + 200, + 308, + 316, + 340, + 345, + 411, + 414, + 416, + 418, + 422, + 438, + 471, + 500, + 508, + 516, + 615, + 645, + 652, + 676, + 684, + 744, + 756, + 795, + 892, + 904, + 915, + 926, + 983 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 15, + 1085 + ], + "new_fact": [ + 57, + 15, + 1081 + ], + "replay_indices": [ + 57, + 69, + 148, + 161, + 177, + 212, + 216, + 226, + 230, + 273, + 289, + 298, + 332, + 413, + 450, + 539, + 547, + 572, + 631, + 660, + 708, + 724, + 747, + 840, + 864, + 875, + 904, + 954, + 966, + 983, + 1006, + 1008 + ], + "affected_untrained_n": { + "D_first_familiar": 4, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 4, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1128 + ], + "new_fact": [ + 89, + 16, + 1123 + ], + "replay_indices": [ + 81, + 90, + 204, + 212, + 274, + 334, + 337, + 371, + 453, + 469, + 491, + 503, + 545, + 583, + 612, + 613, + 615, + 619, + 677, + 703, + 783, + 829, + 848, + 858, + 863, + 895, + 924, + 930, + 945, + 993, + 1013, + 1022 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 110, + 13, + 1134 + ], + "new_fact": [ + 110, + 13, + 1130 + ], + "replay_indices": [ + 13, + 90, + 93, + 102, + 147, + 155, + 179, + 182, + 194, + 212, + 228, + 287, + 313, + 331, + 459, + 469, + 476, + 543, + 567, + 569, + 630, + 655, + 673, + 721, + 732, + 741, + 760, + 789, + 938, + 1000, + 1003, + 1015 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 107, + 14, + 1124 + ], + "new_fact": [ + 107, + 14, + 1109 + ], + "replay_indices": [ + 35, + 109, + 125, + 146, + 164, + 170, + 209, + 247, + 350, + 362, + 378, + 412, + 452, + 471, + 519, + 559, + 568, + 584, + 600, + 608, + 632, + 633, + 680, + 774, + 829, + 831, + 834, + 852, + 880, + 886, + 907, + 992 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 91, + 16, + 1116 + ], + "new_fact": [ + 91, + 16, + 1139 + ], + "replay_indices": [ + 45, + 47, + 84, + 155, + 171, + 192, + 195, + 208, + 236, + 243, + 295, + 327, + 328, + 404, + 406, + 427, + 501, + 508, + 565, + 580, + 583, + 647, + 688, + 773, + 783, + 806, + 851, + 855, + 909, + 927, + 935, + 989 + ], + "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": [ + 1063, + 20, + 1631 + ], + "new_fact": [ + 1063, + 20, + 1648 + ], + "replay_indices": [ + 19, + 23, + 31, + 62, + 73, + 81, + 161, + 182, + 192, + 300, + 303, + 372, + 544, + 548, + 556, + 597, + 632, + 649, + 689, + 736, + 750, + 781, + 828, + 854, + 870, + 904, + 908, + 943, + 964, + 968, + 973, + 1021 + ], + "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": 6 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1073, + 18, + 1679 + ], + "new_fact": [ + 1073, + 18, + 1583 + ], + "replay_indices": [ + 26, + 91, + 94, + 121, + 146, + 156, + 172, + 176, + 180, + 211, + 223, + 233, + 244, + 301, + 305, + 313, + 334, + 417, + 465, + 497, + 583, + 594, + 664, + 669, + 694, + 711, + 807, + 819, + 824, + 877, + 958, + 985 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1101, + 19, + 1626 + ], + "new_fact": [ + 1101, + 19, + 1664 + ], + "replay_indices": [ + 19, + 83, + 105, + 124, + 152, + 164, + 249, + 260, + 314, + 318, + 348, + 354, + 366, + 390, + 448, + 464, + 506, + 509, + 530, + 557, + 598, + 675, + 687, + 730, + 757, + 772, + 854, + 941, + 975, + 1001, + 1002, + 1007 + ], + "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": 1 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1060, + 17, + 1656 + ], + "new_fact": [ + 1060, + 17, + 1620 + ], + "replay_indices": [ + 16, + 33, + 42, + 80, + 89, + 116, + 118, + 207, + 213, + 263, + 280, + 283, + 333, + 342, + 413, + 473, + 496, + 519, + 535, + 563, + 565, + 619, + 671, + 682, + 716, + 724, + 828, + 851, + 852, + 876, + 1001, + 1003 + ], + "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": 3 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1115, + 17, + 1669 + ], + "new_fact": [ + 1115, + 17, + 1581 + ], + "replay_indices": [ + 32, + 48, + 98, + 161, + 182, + 186, + 212, + 217, + 268, + 302, + 316, + 317, + 324, + 374, + 404, + 419, + 455, + 470, + 507, + 514, + 531, + 534, + 624, + 679, + 706, + 736, + 761, + 778, + 789, + 837, + 879, + 931 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1118, + 17, + 1625 + ], + "new_fact": [ + 1118, + 17, + 1608 + ], + "replay_indices": [ + 26, + 59, + 80, + 86, + 96, + 154, + 189, + 218, + 265, + 290, + 318, + 390, + 401, + 467, + 502, + 628, + 658, + 664, + 678, + 756, + 760, + 791, + 794, + 808, + 853, + 854, + 906, + 925, + 941, + 947, + 990, + 992 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1135, + 18, + 1575 + ], + "new_fact": [ + 1135, + 18, + 1663 + ], + "replay_indices": [ + 29, + 55, + 78, + 162, + 194, + 199, + 210, + 247, + 266, + 273, + 343, + 382, + 392, + 408, + 413, + 462, + 473, + 564, + 625, + 644, + 697, + 737, + 745, + 863, + 890, + 903, + 941, + 961, + 974, + 999, + 1009, + 1013 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1124, + 20, + 1678 + ], + "new_fact": [ + 1124, + 20, + 1602 + ], + "replay_indices": [ + 54, + 95, + 100, + 103, + 156, + 201, + 242, + 249, + 387, + 397, + 408, + 460, + 478, + 510, + 568, + 569, + 573, + 593, + 605, + 608, + 616, + 637, + 758, + 796, + 807, + 832, + 858, + 871, + 899, + 915, + 946, + 1015 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "case_sha256": "cc5e29e398ff05cc74287b1d5d79a42507471bd60acdb9d6d8fc4fa3d2731d1d", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270012-shared_full-fixed", + "job_type": "editing", + "phase": "confirmation", + "world": 107270012, + "memory_arm": "shared_full", + "training_arm": "fixed", + "parent_name": "w107270012-shared_full-fixed", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270012-shared_full-fixed", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 28, + 13, + 1064 + ], + "new_fact": [ + 28, + 13, + 1105 + ], + "replay_indices": [ + 31, + 35, + 57, + 87, + 154, + 167, + 189, + 192, + 208, + 238, + 267, + 303, + 315, + 328, + 329, + 347, + 372, + 404, + 501, + 513, + 552, + 587, + 719, + 720, + 807, + 810, + 833, + 853, + 954, + 963, + 966, + 999 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 49, + 14, + 1082 + ], + "new_fact": [ + 49, + 14, + 1045 + ], + "replay_indices": [ + 30, + 59, + 62, + 97, + 162, + 183, + 184, + 249, + 304, + 374, + 397, + 459, + 475, + 480, + 488, + 524, + 532, + 580, + 592, + 647, + 679, + 680, + 686, + 716, + 728, + 761, + 844, + 858, + 925, + 948, + 962, + 1005 + ], + "affected_untrained_n": { + "D_first_familiar": 4, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 4, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "first_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 78, + 16, + 1070 + ], + "new_fact": [ + 78, + 16, + 1093 + ], + "replay_indices": [ + 38, + 57, + 142, + 167, + 200, + 308, + 316, + 340, + 345, + 411, + 414, + 416, + 418, + 422, + 438, + 471, + 500, + 508, + 516, + 615, + 645, + 652, + 676, + 684, + 744, + 756, + 795, + 892, + 904, + 915, + 926, + 983 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 15, + 1085 + ], + "new_fact": [ + 57, + 15, + 1081 + ], + "replay_indices": [ + 57, + 69, + 148, + 161, + 177, + 212, + 216, + 226, + 230, + 273, + 289, + 298, + 332, + 413, + 450, + 539, + 547, + 572, + 631, + 660, + 708, + 724, + 747, + 840, + 864, + 875, + 904, + 954, + 966, + 983, + 1006, + 1008 + ], + "affected_untrained_n": { + "D_first_familiar": 4, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 4, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1128 + ], + "new_fact": [ + 89, + 16, + 1123 + ], + "replay_indices": [ + 81, + 90, + 204, + 212, + 274, + 334, + 337, + 371, + 453, + 469, + 491, + 503, + 545, + 583, + 612, + 613, + 615, + 619, + 677, + 703, + 783, + 829, + 848, + 858, + 863, + 895, + 924, + 930, + 945, + 993, + 1013, + 1022 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 110, + 13, + 1134 + ], + "new_fact": [ + 110, + 13, + 1130 + ], + "replay_indices": [ + 13, + 90, + 93, + 102, + 147, + 155, + 179, + 182, + 194, + 212, + 228, + 287, + 313, + 331, + 459, + 469, + 476, + 543, + 567, + 569, + 630, + 655, + 673, + 721, + 732, + 741, + 760, + 789, + 938, + 1000, + 1003, + 1015 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 107, + 14, + 1124 + ], + "new_fact": [ + 107, + 14, + 1109 + ], + "replay_indices": [ + 35, + 109, + 125, + 146, + 164, + 170, + 209, + 247, + 350, + 362, + 378, + 412, + 452, + 471, + 519, + 559, + 568, + 584, + 600, + 608, + 632, + 633, + 680, + 774, + 829, + 831, + 834, + 852, + 880, + 886, + 907, + 992 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 91, + 16, + 1116 + ], + "new_fact": [ + 91, + 16, + 1139 + ], + "replay_indices": [ + 45, + 47, + 84, + 155, + 171, + 192, + 195, + 208, + 236, + 243, + 295, + 327, + 328, + 404, + 406, + 427, + 501, + 508, + 565, + 580, + 583, + 647, + 688, + 773, + 783, + 806, + 851, + 855, + 909, + 927, + 935, + 989 + ], + "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": [ + 1063, + 20, + 1631 + ], + "new_fact": [ + 1063, + 20, + 1648 + ], + "replay_indices": [ + 19, + 23, + 31, + 62, + 73, + 81, + 161, + 182, + 192, + 300, + 303, + 372, + 544, + 548, + 556, + 597, + 632, + 649, + 689, + 736, + 750, + 781, + 828, + 854, + 870, + 904, + 908, + 943, + 964, + 968, + 973, + 1021 + ], + "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": 6 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1073, + 18, + 1679 + ], + "new_fact": [ + 1073, + 18, + 1583 + ], + "replay_indices": [ + 26, + 91, + 94, + 121, + 146, + 156, + 172, + 176, + 180, + 211, + 223, + 233, + 244, + 301, + 305, + 313, + 334, + 417, + 465, + 497, + 583, + 594, + 664, + 669, + 694, + 711, + 807, + 819, + 824, + 877, + 958, + 985 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1101, + 19, + 1626 + ], + "new_fact": [ + 1101, + 19, + 1664 + ], + "replay_indices": [ + 19, + 83, + 105, + 124, + 152, + 164, + 249, + 260, + 314, + 318, + 348, + 354, + 366, + 390, + 448, + 464, + 506, + 509, + 530, + 557, + 598, + 675, + 687, + 730, + 757, + 772, + 854, + 941, + 975, + 1001, + 1002, + 1007 + ], + "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": 1 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1060, + 17, + 1656 + ], + "new_fact": [ + 1060, + 17, + 1620 + ], + "replay_indices": [ + 16, + 33, + 42, + 80, + 89, + 116, + 118, + 207, + 213, + 263, + 280, + 283, + 333, + 342, + 413, + 473, + 496, + 519, + 535, + 563, + 565, + 619, + 671, + 682, + 716, + 724, + 828, + 851, + 852, + 876, + 1001, + 1003 + ], + "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": 3 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1115, + 17, + 1669 + ], + "new_fact": [ + 1115, + 17, + 1581 + ], + "replay_indices": [ + 32, + 48, + 98, + 161, + 182, + 186, + 212, + 217, + 268, + 302, + 316, + 317, + 324, + 374, + 404, + 419, + 455, + 470, + 507, + 514, + 531, + 534, + 624, + 679, + 706, + 736, + 761, + 778, + 789, + 837, + 879, + 931 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1118, + 17, + 1625 + ], + "new_fact": [ + 1118, + 17, + 1608 + ], + "replay_indices": [ + 26, + 59, + 80, + 86, + 96, + 154, + 189, + 218, + 265, + 290, + 318, + 390, + 401, + 467, + 502, + 628, + 658, + 664, + 678, + 756, + 760, + 791, + 794, + 808, + 853, + 854, + 906, + 925, + 941, + 947, + 990, + 992 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1135, + 18, + 1575 + ], + "new_fact": [ + 1135, + 18, + 1663 + ], + "replay_indices": [ + 29, + 55, + 78, + 162, + 194, + 199, + 210, + 247, + 266, + 273, + 343, + 382, + 392, + 408, + 413, + 462, + 473, + 564, + 625, + 644, + 697, + 737, + 745, + 863, + 890, + 903, + 941, + 961, + 974, + 999, + 1009, + 1013 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1124, + 20, + 1678 + ], + "new_fact": [ + 1124, + 20, + 1602 + ], + "replay_indices": [ + 54, + 95, + 100, + 103, + 156, + 201, + 242, + 249, + 387, + 397, + 408, + 460, + 478, + 510, + 568, + 569, + 573, + 593, + 605, + 608, + 616, + 637, + 758, + 796, + 807, + 832, + 858, + 871, + 899, + 915, + 946, + 1015 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "case_sha256": "cc5e29e398ff05cc74287b1d5d79a42507471bd60acdb9d6d8fc4fa3d2731d1d", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270012-shared_full-changed_atomic", + "job_type": "editing", + "phase": "confirmation", + "world": 107270012, + "memory_arm": "shared_full", + "training_arm": "changed_atomic", + "parent_name": "w107270012-shared_full-changed_atomic", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270012-shared_full-changed_atomic", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 28, + 13, + 1064 + ], + "new_fact": [ + 28, + 13, + 1105 + ], + "replay_indices": [ + 31, + 35, + 57, + 87, + 154, + 167, + 189, + 192, + 208, + 238, + 267, + 303, + 315, + 328, + 329, + 347, + 372, + 404, + 501, + 513, + 552, + 587, + 719, + 720, + 807, + 810, + 833, + 853, + 954, + 963, + 966, + 999 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 49, + 14, + 1082 + ], + "new_fact": [ + 49, + 14, + 1045 + ], + "replay_indices": [ + 30, + 59, + 62, + 97, + 162, + 183, + 184, + 249, + 304, + 374, + 397, + 459, + 475, + 480, + 488, + 524, + 532, + 580, + 592, + 647, + 679, + 680, + 686, + 716, + 728, + 761, + 844, + 858, + 925, + 948, + 962, + 1005 + ], + "affected_untrained_n": { + "D_first_familiar": 4, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 4, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "first_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 78, + 16, + 1070 + ], + "new_fact": [ + 78, + 16, + 1093 + ], + "replay_indices": [ + 38, + 57, + 142, + 167, + 200, + 308, + 316, + 340, + 345, + 411, + 414, + 416, + 418, + 422, + 438, + 471, + 500, + 508, + 516, + 615, + 645, + 652, + 676, + 684, + 744, + 756, + 795, + 892, + 904, + 915, + 926, + 983 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 15, + 1085 + ], + "new_fact": [ + 57, + 15, + 1081 + ], + "replay_indices": [ + 57, + 69, + 148, + 161, + 177, + 212, + 216, + 226, + 230, + 273, + 289, + 298, + 332, + 413, + 450, + 539, + 547, + 572, + 631, + 660, + 708, + 724, + 747, + 840, + 864, + 875, + 904, + 954, + 966, + 983, + 1006, + 1008 + ], + "affected_untrained_n": { + "D_first_familiar": 4, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 4, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1128 + ], + "new_fact": [ + 89, + 16, + 1123 + ], + "replay_indices": [ + 81, + 90, + 204, + 212, + 274, + 334, + 337, + 371, + 453, + 469, + 491, + 503, + 545, + 583, + 612, + 613, + 615, + 619, + 677, + 703, + 783, + 829, + 848, + 858, + 863, + 895, + 924, + 930, + 945, + 993, + 1013, + 1022 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 110, + 13, + 1134 + ], + "new_fact": [ + 110, + 13, + 1130 + ], + "replay_indices": [ + 13, + 90, + 93, + 102, + 147, + 155, + 179, + 182, + 194, + 212, + 228, + 287, + 313, + 331, + 459, + 469, + 476, + 543, + 567, + 569, + 630, + 655, + 673, + 721, + 732, + 741, + 760, + 789, + 938, + 1000, + 1003, + 1015 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 107, + 14, + 1124 + ], + "new_fact": [ + 107, + 14, + 1109 + ], + "replay_indices": [ + 35, + 109, + 125, + 146, + 164, + 170, + 209, + 247, + 350, + 362, + 378, + 412, + 452, + 471, + 519, + 559, + 568, + 584, + 600, + 608, + 632, + 633, + 680, + 774, + 829, + 831, + 834, + 852, + 880, + 886, + 907, + 992 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 91, + 16, + 1116 + ], + "new_fact": [ + 91, + 16, + 1139 + ], + "replay_indices": [ + 45, + 47, + 84, + 155, + 171, + 192, + 195, + 208, + 236, + 243, + 295, + 327, + 328, + 404, + 406, + 427, + 501, + 508, + 565, + 580, + 583, + 647, + 688, + 773, + 783, + 806, + 851, + 855, + 909, + 927, + 935, + 989 + ], + "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": [ + 1063, + 20, + 1631 + ], + "new_fact": [ + 1063, + 20, + 1648 + ], + "replay_indices": [ + 19, + 23, + 31, + 62, + 73, + 81, + 161, + 182, + 192, + 300, + 303, + 372, + 544, + 548, + 556, + 597, + 632, + 649, + 689, + 736, + 750, + 781, + 828, + 854, + 870, + 904, + 908, + 943, + 964, + 968, + 973, + 1021 + ], + "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": 6 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1073, + 18, + 1679 + ], + "new_fact": [ + 1073, + 18, + 1583 + ], + "replay_indices": [ + 26, + 91, + 94, + 121, + 146, + 156, + 172, + 176, + 180, + 211, + 223, + 233, + 244, + 301, + 305, + 313, + 334, + 417, + 465, + 497, + 583, + 594, + 664, + 669, + 694, + 711, + 807, + 819, + 824, + 877, + 958, + 985 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1101, + 19, + 1626 + ], + "new_fact": [ + 1101, + 19, + 1664 + ], + "replay_indices": [ + 19, + 83, + 105, + 124, + 152, + 164, + 249, + 260, + 314, + 318, + 348, + 354, + 366, + 390, + 448, + 464, + 506, + 509, + 530, + 557, + 598, + 675, + 687, + 730, + 757, + 772, + 854, + 941, + 975, + 1001, + 1002, + 1007 + ], + "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": 1 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1060, + 17, + 1656 + ], + "new_fact": [ + 1060, + 17, + 1620 + ], + "replay_indices": [ + 16, + 33, + 42, + 80, + 89, + 116, + 118, + 207, + 213, + 263, + 280, + 283, + 333, + 342, + 413, + 473, + 496, + 519, + 535, + 563, + 565, + 619, + 671, + 682, + 716, + 724, + 828, + 851, + 852, + 876, + 1001, + 1003 + ], + "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": 3 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1115, + 17, + 1669 + ], + "new_fact": [ + 1115, + 17, + 1581 + ], + "replay_indices": [ + 32, + 48, + 98, + 161, + 182, + 186, + 212, + 217, + 268, + 302, + 316, + 317, + 324, + 374, + 404, + 419, + 455, + 470, + 507, + 514, + 531, + 534, + 624, + 679, + 706, + 736, + 761, + 778, + 789, + 837, + 879, + 931 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1118, + 17, + 1625 + ], + "new_fact": [ + 1118, + 17, + 1608 + ], + "replay_indices": [ + 26, + 59, + 80, + 86, + 96, + 154, + 189, + 218, + 265, + 290, + 318, + 390, + 401, + 467, + 502, + 628, + 658, + 664, + 678, + 756, + 760, + 791, + 794, + 808, + 853, + 854, + 906, + 925, + 941, + 947, + 990, + 992 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1135, + 18, + 1575 + ], + "new_fact": [ + 1135, + 18, + 1663 + ], + "replay_indices": [ + 29, + 55, + 78, + 162, + 194, + 199, + 210, + 247, + 266, + 273, + 343, + 382, + 392, + 408, + 413, + 462, + 473, + 564, + 625, + 644, + 697, + 737, + 745, + 863, + 890, + 903, + 941, + 961, + 974, + 999, + 1009, + 1013 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1124, + 20, + 1678 + ], + "new_fact": [ + 1124, + 20, + 1602 + ], + "replay_indices": [ + 54, + 95, + 100, + 103, + 156, + 201, + 242, + 249, + 387, + 397, + 408, + 460, + 478, + 510, + 568, + 569, + 573, + 593, + 605, + 608, + 616, + 637, + 758, + 796, + 807, + 832, + 858, + 871, + 899, + 915, + 946, + 1015 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "case_sha256": "cc5e29e398ff05cc74287b1d5d79a42507471bd60acdb9d6d8fc4fa3d2731d1d", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270012-shared_full-changed_use", + "job_type": "editing", + "phase": "confirmation", + "world": 107270012, + "memory_arm": "shared_full", + "training_arm": "changed_use", + "parent_name": "w107270012-shared_full-changed_use", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270012-shared_full-changed_use", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 28, + 13, + 1064 + ], + "new_fact": [ + 28, + 13, + 1105 + ], + "replay_indices": [ + 31, + 35, + 57, + 87, + 154, + 167, + 189, + 192, + 208, + 238, + 267, + 303, + 315, + 328, + 329, + 347, + 372, + 404, + 501, + 513, + 552, + 587, + 719, + 720, + 807, + 810, + 833, + 853, + 954, + 963, + 966, + 999 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 49, + 14, + 1082 + ], + "new_fact": [ + 49, + 14, + 1045 + ], + "replay_indices": [ + 30, + 59, + 62, + 97, + 162, + 183, + 184, + 249, + 304, + 374, + 397, + 459, + 475, + 480, + 488, + 524, + 532, + 580, + 592, + 647, + 679, + 680, + 686, + 716, + 728, + 761, + 844, + 858, + 925, + 948, + 962, + 1005 + ], + "affected_untrained_n": { + "D_first_familiar": 4, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 4, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "first_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 78, + 16, + 1070 + ], + "new_fact": [ + 78, + 16, + 1093 + ], + "replay_indices": [ + 38, + 57, + 142, + 167, + 200, + 308, + 316, + 340, + 345, + 411, + 414, + 416, + 418, + 422, + 438, + 471, + 500, + 508, + 516, + 615, + 645, + 652, + 676, + 684, + 744, + 756, + 795, + 892, + 904, + 915, + 926, + 983 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 57, + 15, + 1085 + ], + "new_fact": [ + 57, + 15, + 1081 + ], + "replay_indices": [ + 57, + 69, + 148, + 161, + 177, + 212, + 216, + 226, + 230, + 273, + 289, + 298, + 332, + 413, + 450, + 539, + 547, + 572, + 631, + 660, + 708, + 724, + 747, + 840, + 864, + 875, + 904, + 954, + 966, + 983, + 1006, + 1008 + ], + "affected_untrained_n": { + "D_first_familiar": 4, + "S_same_answer_first_familiar": 0, + "D_first_strict": 0, + "S_same_answer_first_strict": 0, + "D_first_registered_familiar": 4, + "S_same_answer_first_registered_familiar": 0, + "T_first_train": 0 + } + }, + { + "case_id": "first_strict-00", + "role": "first", + "stratum": "strict", + "old_fact": [ + 89, + 16, + 1128 + ], + "new_fact": [ + 89, + 16, + 1123 + ], + "replay_indices": [ + 81, + 90, + 204, + 212, + 274, + 334, + 337, + 371, + 453, + 469, + 491, + 503, + 545, + 583, + 612, + 613, + 615, + 619, + 677, + 703, + 783, + 829, + 848, + 858, + 863, + 895, + 924, + 930, + 945, + 993, + 1013, + 1022 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 110, + 13, + 1134 + ], + "new_fact": [ + 110, + 13, + 1130 + ], + "replay_indices": [ + 13, + 90, + 93, + 102, + 147, + 155, + 179, + 182, + 194, + 212, + 228, + 287, + 313, + 331, + 459, + 469, + 476, + 543, + 567, + 569, + 630, + 655, + 673, + 721, + 732, + 741, + 760, + 789, + 938, + 1000, + 1003, + 1015 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 107, + 14, + 1124 + ], + "new_fact": [ + 107, + 14, + 1109 + ], + "replay_indices": [ + 35, + 109, + 125, + 146, + 164, + 170, + 209, + 247, + 350, + 362, + 378, + 412, + 452, + 471, + 519, + 559, + 568, + 584, + 600, + 608, + 632, + 633, + 680, + 774, + 829, + 831, + 834, + 852, + 880, + 886, + 907, + 992 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 91, + 16, + 1116 + ], + "new_fact": [ + 91, + 16, + 1139 + ], + "replay_indices": [ + 45, + 47, + 84, + 155, + 171, + 192, + 195, + 208, + 236, + 243, + 295, + 327, + 328, + 404, + 406, + 427, + 501, + 508, + 565, + 580, + 583, + 647, + 688, + 773, + 783, + 806, + 851, + 855, + 909, + 927, + 935, + 989 + ], + "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": [ + 1063, + 20, + 1631 + ], + "new_fact": [ + 1063, + 20, + 1648 + ], + "replay_indices": [ + 19, + 23, + 31, + 62, + 73, + 81, + 161, + 182, + 192, + 300, + 303, + 372, + 544, + 548, + 556, + 597, + 632, + 649, + 689, + 736, + 750, + 781, + 828, + 854, + 870, + 904, + 908, + 943, + 964, + 968, + 973, + 1021 + ], + "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": 6 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1073, + 18, + 1679 + ], + "new_fact": [ + 1073, + 18, + 1583 + ], + "replay_indices": [ + 26, + 91, + 94, + 121, + 146, + 156, + 172, + 176, + 180, + 211, + 223, + 233, + 244, + 301, + 305, + 313, + 334, + 417, + 465, + 497, + 583, + 594, + 664, + 669, + 694, + 711, + 807, + 819, + 824, + 877, + 958, + 985 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1101, + 19, + 1626 + ], + "new_fact": [ + 1101, + 19, + 1664 + ], + "replay_indices": [ + 19, + 83, + 105, + 124, + 152, + 164, + 249, + 260, + 314, + 318, + 348, + 354, + 366, + 390, + 448, + 464, + 506, + 509, + 530, + 557, + 598, + 675, + 687, + 730, + 757, + 772, + 854, + 941, + 975, + 1001, + 1002, + 1007 + ], + "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": 1 + } + }, + { + "case_id": "second_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1060, + 17, + 1656 + ], + "new_fact": [ + 1060, + 17, + 1620 + ], + "replay_indices": [ + 16, + 33, + 42, + 80, + 89, + 116, + 118, + 207, + 213, + 263, + 280, + 283, + 333, + 342, + 413, + 473, + 496, + 519, + 535, + 563, + 565, + 619, + 671, + 682, + 716, + 724, + 828, + 851, + 852, + 876, + 1001, + 1003 + ], + "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": 3 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1115, + 17, + 1669 + ], + "new_fact": [ + 1115, + 17, + 1581 + ], + "replay_indices": [ + 32, + 48, + 98, + 161, + 182, + 186, + 212, + 217, + 268, + 302, + 316, + 317, + 324, + 374, + 404, + 419, + 455, + 470, + 507, + 514, + 531, + 534, + 624, + 679, + 706, + 736, + 761, + 778, + 789, + 837, + 879, + 931 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1118, + 17, + 1625 + ], + "new_fact": [ + 1118, + 17, + 1608 + ], + "replay_indices": [ + 26, + 59, + 80, + 86, + 96, + 154, + 189, + 218, + 265, + 290, + 318, + 390, + 401, + 467, + 502, + 628, + 658, + 664, + 678, + 756, + 760, + 791, + 794, + 808, + 853, + 854, + 906, + 925, + 941, + 947, + 990, + 992 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1135, + 18, + 1575 + ], + "new_fact": [ + 1135, + 18, + 1663 + ], + "replay_indices": [ + 29, + 55, + 78, + 162, + 194, + 199, + 210, + 247, + 266, + 273, + 343, + 382, + 392, + 408, + 413, + 462, + 473, + 564, + 625, + 644, + 697, + 737, + 745, + 863, + 890, + 903, + 941, + 961, + 974, + 999, + 1009, + 1013 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1124, + 20, + 1678 + ], + "new_fact": [ + 1124, + 20, + 1602 + ], + "replay_indices": [ + 54, + 95, + 100, + 103, + 156, + 201, + 242, + 249, + 387, + 397, + 408, + 460, + 478, + 510, + 568, + 569, + 573, + 593, + 605, + 608, + 616, + 637, + 758, + 796, + 807, + 832, + 858, + 871, + 899, + 915, + 946, + 1015 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + } + ], + "case_sha256": "cc5e29e398ff05cc74287b1d5d79a42507471bd60acdb9d6d8fc4fa3d2731d1d", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270013-local-fixed", + "job_type": "editing", + "phase": "confirmation", + "world": 107270013, + "memory_arm": "local", + "training_arm": "fixed", + "parent_name": "w107270013-local-fixed", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270013-local-fixed", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 61, + 16, + 1096 + ], + "new_fact": [ + 61, + 16, + 1064 + ], + "replay_indices": [ + 16, + 98, + 134, + 156, + 270, + 331, + 397, + 443, + 452, + 473, + 496, + 499, + 534, + 539, + 572, + 582, + 623, + 626, + 629, + 660, + 665, + 719, + 723, + 737, + 770, + 791, + 795, + 862, + 918, + 965, + 982, + 1015 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 84, + 14, + 1080 + ], + "new_fact": [ + 84, + 14, + 1096 + ], + "replay_indices": [ + 11, + 64, + 89, + 163, + 177, + 193, + 207, + 269, + 281, + 312, + 426, + 443, + 543, + 560, + 581, + 615, + 635, + 672, + 697, + 712, + 761, + 840, + 843, + 844, + 852, + 865, + 891, + 921, + 928, + 955, + 1005, + 1017 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 35, + 15, + 1080 + ], + "new_fact": [ + 35, + 15, + 1098 + ], + "replay_indices": [ + 31, + 53, + 86, + 116, + 119, + 164, + 175, + 187, + 218, + 306, + 346, + 389, + 408, + 449, + 458, + 516, + 590, + 616, + 639, + 640, + 645, + 688, + 747, + 758, + 777, + 838, + 840, + 955, + 972, + 975, + 995, + 1011 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 54, + 13, + 1052 + ], + "new_fact": [ + 54, + 13, + 1045 + ], + "replay_indices": [ + 17, + 36, + 117, + 129, + 143, + 152, + 175, + 206, + 210, + 288, + 306, + 341, + 352, + 378, + 403, + 464, + 493, + 540, + 595, + 612, + 615, + 636, + 699, + 702, + 849, + 859, + 865, + 919, + 940, + 975, + 976, + 1020 + ], + "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": [ + 115, + 13, + 1119 + ], + "new_fact": [ + 115, + 13, + 1115 + ], + "replay_indices": [ + 107, + 112, + 236, + 247, + 297, + 306, + 347, + 378, + 388, + 469, + 472, + 474, + 487, + 491, + 545, + 564, + 568, + 583, + 598, + 604, + 634, + 640, + 679, + 762, + 813, + 840, + 848, + 855, + 929, + 937, + 945, + 948 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 106, + 15, + 1112 + ], + "new_fact": [ + 106, + 15, + 1123 + ], + "replay_indices": [ + 15, + 31, + 45, + 77, + 84, + 105, + 112, + 118, + 217, + 270, + 300, + 375, + 390, + 443, + 502, + 508, + 550, + 600, + 610, + 697, + 726, + 739, + 751, + 806, + 817, + 901, + 907, + 928, + 937, + 950, + 972, + 1014 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 112, + 14, + 1131 + ], + "new_fact": [ + 112, + 14, + 1119 + ], + "replay_indices": [ + 52, + 75, + 132, + 160, + 184, + 207, + 213, + 214, + 285, + 287, + 304, + 361, + 366, + 417, + 455, + 470, + 472, + 529, + 530, + 553, + 724, + 775, + 780, + 801, + 802, + 833, + 923, + 924, + 937, + 955, + 1004, + 1005 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 101, + 15, + 1132 + ], + "new_fact": [ + 101, + 15, + 1116 + ], + "replay_indices": [ + 6, + 45, + 71, + 189, + 227, + 241, + 284, + 305, + 330, + 421, + 445, + 458, + 477, + 503, + 523, + 539, + 636, + 652, + 661, + 719, + 727, + 731, + 835, + 840, + 846, + 857, + 858, + 885, + 890, + 948, + 967, + 972 + ], + "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": [ + 1072, + 19, + 1587 + ], + "new_fact": [ + 1072, + 19, + 1655 + ], + "replay_indices": [ + 5, + 7, + 20, + 66, + 145, + 170, + 219, + 263, + 267, + 314, + 367, + 382, + 387, + 439, + 443, + 496, + 512, + 528, + 592, + 593, + 597, + 605, + 607, + 617, + 658, + 682, + 760, + 767, + 849, + 947, + 949, + 952 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1046, + 17, + 1588 + ], + "new_fact": [ + 1046, + 17, + 1604 + ], + "replay_indices": [ + 4, + 54, + 99, + 107, + 154, + 206, + 250, + 277, + 292, + 313, + 318, + 326, + 347, + 352, + 381, + 433, + 437, + 475, + 506, + 564, + 627, + 673, + 677, + 682, + 720, + 748, + 751, + 755, + 825, + 843, + 859, + 930 + ], + "affected_untrained_n": { + "D_second_familiar": 3, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 3, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 3 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1070, + 20, + 1667 + ], + "new_fact": [ + 1070, + 20, + 1593 + ], + "replay_indices": [ + 32, + 60, + 161, + 168, + 211, + 270, + 292, + 317, + 331, + 332, + 348, + 358, + 386, + 387, + 393, + 395, + 409, + 448, + 472, + 523, + 536, + 546, + 567, + 620, + 638, + 694, + 769, + 830, + 918, + 925, + 946, + 963 + ], + "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_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1075, + 18, + 1683 + ], + "new_fact": [ + 1075, + 18, + 1617 + ], + "replay_indices": [ + 28, + 49, + 154, + 220, + 229, + 248, + 276, + 279, + 291, + 315, + 319, + 376, + 406, + 424, + 444, + 457, + 458, + 502, + 535, + 545, + 571, + 600, + 635, + 668, + 696, + 735, + 752, + 790, + 812, + 848, + 937, + 978 + ], + "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": 2 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1110, + 17, + 1623 + ], + "new_fact": [ + 1110, + 17, + 1568 + ], + "replay_indices": [ + 3, + 22, + 67, + 78, + 97, + 139, + 180, + 183, + 184, + 251, + 280, + 282, + 385, + 511, + 534, + 552, + 554, + 577, + 580, + 641, + 651, + 674, + 702, + 720, + 731, + 749, + 760, + 784, + 794, + 858, + 888, + 948 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1133, + 19, + 1592 + ], + "new_fact": [ + 1133, + 19, + 1567 + ], + "replay_indices": [ + 10, + 15, + 48, + 50, + 102, + 114, + 134, + 174, + 221, + 295, + 307, + 397, + 405, + 451, + 505, + 510, + 522, + 563, + 580, + 606, + 644, + 706, + 774, + 788, + 789, + 857, + 865, + 881, + 902, + 914, + 918, + 964 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1129, + 20, + 1615 + ], + "new_fact": [ + 1129, + 20, + 1625 + ], + "replay_indices": [ + 74, + 92, + 241, + 242, + 266, + 270, + 296, + 307, + 321, + 383, + 403, + 433, + 489, + 494, + 500, + 503, + 579, + 604, + 606, + 618, + 636, + 663, + 691, + 766, + 771, + 789, + 837, + 880, + 908, + 922, + 938, + 982 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1114, + 17, + 1585 + ], + "new_fact": [ + 1114, + 17, + 1651 + ], + "replay_indices": [ + 11, + 28, + 64, + 86, + 118, + 162, + 199, + 220, + 286, + 342, + 347, + 390, + 462, + 475, + 486, + 489, + 538, + 548, + 665, + 675, + 751, + 774, + 793, + 813, + 829, + 855, + 905, + 969, + 980, + 984, + 998, + 1021 + ], + "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 + } + } + ], + "case_sha256": "9d756b45e73f2136e48ac1699cd6d992bf9ea9558875da442492b6d77e375384", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270013-local-changed_atomic", + "job_type": "editing", + "phase": "confirmation", + "world": 107270013, + "memory_arm": "local", + "training_arm": "changed_atomic", + "parent_name": "w107270013-local-changed_atomic", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270013-local-changed_atomic", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 61, + 16, + 1096 + ], + "new_fact": [ + 61, + 16, + 1064 + ], + "replay_indices": [ + 16, + 98, + 134, + 156, + 270, + 331, + 397, + 443, + 452, + 473, + 496, + 499, + 534, + 539, + 572, + 582, + 623, + 626, + 629, + 660, + 665, + 719, + 723, + 737, + 770, + 791, + 795, + 862, + 918, + 965, + 982, + 1015 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 84, + 14, + 1080 + ], + "new_fact": [ + 84, + 14, + 1096 + ], + "replay_indices": [ + 11, + 64, + 89, + 163, + 177, + 193, + 207, + 269, + 281, + 312, + 426, + 443, + 543, + 560, + 581, + 615, + 635, + 672, + 697, + 712, + 761, + 840, + 843, + 844, + 852, + 865, + 891, + 921, + 928, + 955, + 1005, + 1017 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 35, + 15, + 1080 + ], + "new_fact": [ + 35, + 15, + 1098 + ], + "replay_indices": [ + 31, + 53, + 86, + 116, + 119, + 164, + 175, + 187, + 218, + 306, + 346, + 389, + 408, + 449, + 458, + 516, + 590, + 616, + 639, + 640, + 645, + 688, + 747, + 758, + 777, + 838, + 840, + 955, + 972, + 975, + 995, + 1011 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 54, + 13, + 1052 + ], + "new_fact": [ + 54, + 13, + 1045 + ], + "replay_indices": [ + 17, + 36, + 117, + 129, + 143, + 152, + 175, + 206, + 210, + 288, + 306, + 341, + 352, + 378, + 403, + 464, + 493, + 540, + 595, + 612, + 615, + 636, + 699, + 702, + 849, + 859, + 865, + 919, + 940, + 975, + 976, + 1020 + ], + "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": [ + 115, + 13, + 1119 + ], + "new_fact": [ + 115, + 13, + 1115 + ], + "replay_indices": [ + 107, + 112, + 236, + 247, + 297, + 306, + 347, + 378, + 388, + 469, + 472, + 474, + 487, + 491, + 545, + 564, + 568, + 583, + 598, + 604, + 634, + 640, + 679, + 762, + 813, + 840, + 848, + 855, + 929, + 937, + 945, + 948 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 106, + 15, + 1112 + ], + "new_fact": [ + 106, + 15, + 1123 + ], + "replay_indices": [ + 15, + 31, + 45, + 77, + 84, + 105, + 112, + 118, + 217, + 270, + 300, + 375, + 390, + 443, + 502, + 508, + 550, + 600, + 610, + 697, + 726, + 739, + 751, + 806, + 817, + 901, + 907, + 928, + 937, + 950, + 972, + 1014 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 112, + 14, + 1131 + ], + "new_fact": [ + 112, + 14, + 1119 + ], + "replay_indices": [ + 52, + 75, + 132, + 160, + 184, + 207, + 213, + 214, + 285, + 287, + 304, + 361, + 366, + 417, + 455, + 470, + 472, + 529, + 530, + 553, + 724, + 775, + 780, + 801, + 802, + 833, + 923, + 924, + 937, + 955, + 1004, + 1005 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 101, + 15, + 1132 + ], + "new_fact": [ + 101, + 15, + 1116 + ], + "replay_indices": [ + 6, + 45, + 71, + 189, + 227, + 241, + 284, + 305, + 330, + 421, + 445, + 458, + 477, + 503, + 523, + 539, + 636, + 652, + 661, + 719, + 727, + 731, + 835, + 840, + 846, + 857, + 858, + 885, + 890, + 948, + 967, + 972 + ], + "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": [ + 1072, + 19, + 1587 + ], + "new_fact": [ + 1072, + 19, + 1655 + ], + "replay_indices": [ + 5, + 7, + 20, + 66, + 145, + 170, + 219, + 263, + 267, + 314, + 367, + 382, + 387, + 439, + 443, + 496, + 512, + 528, + 592, + 593, + 597, + 605, + 607, + 617, + 658, + 682, + 760, + 767, + 849, + 947, + 949, + 952 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1046, + 17, + 1588 + ], + "new_fact": [ + 1046, + 17, + 1604 + ], + "replay_indices": [ + 4, + 54, + 99, + 107, + 154, + 206, + 250, + 277, + 292, + 313, + 318, + 326, + 347, + 352, + 381, + 433, + 437, + 475, + 506, + 564, + 627, + 673, + 677, + 682, + 720, + 748, + 751, + 755, + 825, + 843, + 859, + 930 + ], + "affected_untrained_n": { + "D_second_familiar": 3, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 3, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 3 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1070, + 20, + 1667 + ], + "new_fact": [ + 1070, + 20, + 1593 + ], + "replay_indices": [ + 32, + 60, + 161, + 168, + 211, + 270, + 292, + 317, + 331, + 332, + 348, + 358, + 386, + 387, + 393, + 395, + 409, + 448, + 472, + 523, + 536, + 546, + 567, + 620, + 638, + 694, + 769, + 830, + 918, + 925, + 946, + 963 + ], + "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_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1075, + 18, + 1683 + ], + "new_fact": [ + 1075, + 18, + 1617 + ], + "replay_indices": [ + 28, + 49, + 154, + 220, + 229, + 248, + 276, + 279, + 291, + 315, + 319, + 376, + 406, + 424, + 444, + 457, + 458, + 502, + 535, + 545, + 571, + 600, + 635, + 668, + 696, + 735, + 752, + 790, + 812, + 848, + 937, + 978 + ], + "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": 2 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1110, + 17, + 1623 + ], + "new_fact": [ + 1110, + 17, + 1568 + ], + "replay_indices": [ + 3, + 22, + 67, + 78, + 97, + 139, + 180, + 183, + 184, + 251, + 280, + 282, + 385, + 511, + 534, + 552, + 554, + 577, + 580, + 641, + 651, + 674, + 702, + 720, + 731, + 749, + 760, + 784, + 794, + 858, + 888, + 948 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1133, + 19, + 1592 + ], + "new_fact": [ + 1133, + 19, + 1567 + ], + "replay_indices": [ + 10, + 15, + 48, + 50, + 102, + 114, + 134, + 174, + 221, + 295, + 307, + 397, + 405, + 451, + 505, + 510, + 522, + 563, + 580, + 606, + 644, + 706, + 774, + 788, + 789, + 857, + 865, + 881, + 902, + 914, + 918, + 964 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1129, + 20, + 1615 + ], + "new_fact": [ + 1129, + 20, + 1625 + ], + "replay_indices": [ + 74, + 92, + 241, + 242, + 266, + 270, + 296, + 307, + 321, + 383, + 403, + 433, + 489, + 494, + 500, + 503, + 579, + 604, + 606, + 618, + 636, + 663, + 691, + 766, + 771, + 789, + 837, + 880, + 908, + 922, + 938, + 982 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1114, + 17, + 1585 + ], + "new_fact": [ + 1114, + 17, + 1651 + ], + "replay_indices": [ + 11, + 28, + 64, + 86, + 118, + 162, + 199, + 220, + 286, + 342, + 347, + 390, + 462, + 475, + 486, + 489, + 538, + 548, + 665, + 675, + 751, + 774, + 793, + 813, + 829, + 855, + 905, + 969, + 980, + 984, + 998, + 1021 + ], + "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 + } + } + ], + "case_sha256": "9d756b45e73f2136e48ac1699cd6d992bf9ea9558875da442492b6d77e375384", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270013-local-changed_use", + "job_type": "editing", + "phase": "confirmation", + "world": 107270013, + "memory_arm": "local", + "training_arm": "changed_use", + "parent_name": "w107270013-local-changed_use", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270013-local-changed_use", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 61, + 16, + 1096 + ], + "new_fact": [ + 61, + 16, + 1064 + ], + "replay_indices": [ + 16, + 98, + 134, + 156, + 270, + 331, + 397, + 443, + 452, + 473, + 496, + 499, + 534, + 539, + 572, + 582, + 623, + 626, + 629, + 660, + 665, + 719, + 723, + 737, + 770, + 791, + 795, + 862, + 918, + 965, + 982, + 1015 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 84, + 14, + 1080 + ], + "new_fact": [ + 84, + 14, + 1096 + ], + "replay_indices": [ + 11, + 64, + 89, + 163, + 177, + 193, + 207, + 269, + 281, + 312, + 426, + 443, + 543, + 560, + 581, + 615, + 635, + 672, + 697, + 712, + 761, + 840, + 843, + 844, + 852, + 865, + 891, + 921, + 928, + 955, + 1005, + 1017 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 35, + 15, + 1080 + ], + "new_fact": [ + 35, + 15, + 1098 + ], + "replay_indices": [ + 31, + 53, + 86, + 116, + 119, + 164, + 175, + 187, + 218, + 306, + 346, + 389, + 408, + 449, + 458, + 516, + 590, + 616, + 639, + 640, + 645, + 688, + 747, + 758, + 777, + 838, + 840, + 955, + 972, + 975, + 995, + 1011 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 54, + 13, + 1052 + ], + "new_fact": [ + 54, + 13, + 1045 + ], + "replay_indices": [ + 17, + 36, + 117, + 129, + 143, + 152, + 175, + 206, + 210, + 288, + 306, + 341, + 352, + 378, + 403, + 464, + 493, + 540, + 595, + 612, + 615, + 636, + 699, + 702, + 849, + 859, + 865, + 919, + 940, + 975, + 976, + 1020 + ], + "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": [ + 115, + 13, + 1119 + ], + "new_fact": [ + 115, + 13, + 1115 + ], + "replay_indices": [ + 107, + 112, + 236, + 247, + 297, + 306, + 347, + 378, + 388, + 469, + 472, + 474, + 487, + 491, + 545, + 564, + 568, + 583, + 598, + 604, + 634, + 640, + 679, + 762, + 813, + 840, + 848, + 855, + 929, + 937, + 945, + 948 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 106, + 15, + 1112 + ], + "new_fact": [ + 106, + 15, + 1123 + ], + "replay_indices": [ + 15, + 31, + 45, + 77, + 84, + 105, + 112, + 118, + 217, + 270, + 300, + 375, + 390, + 443, + 502, + 508, + 550, + 600, + 610, + 697, + 726, + 739, + 751, + 806, + 817, + 901, + 907, + 928, + 937, + 950, + 972, + 1014 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 112, + 14, + 1131 + ], + "new_fact": [ + 112, + 14, + 1119 + ], + "replay_indices": [ + 52, + 75, + 132, + 160, + 184, + 207, + 213, + 214, + 285, + 287, + 304, + 361, + 366, + 417, + 455, + 470, + 472, + 529, + 530, + 553, + 724, + 775, + 780, + 801, + 802, + 833, + 923, + 924, + 937, + 955, + 1004, + 1005 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 101, + 15, + 1132 + ], + "new_fact": [ + 101, + 15, + 1116 + ], + "replay_indices": [ + 6, + 45, + 71, + 189, + 227, + 241, + 284, + 305, + 330, + 421, + 445, + 458, + 477, + 503, + 523, + 539, + 636, + 652, + 661, + 719, + 727, + 731, + 835, + 840, + 846, + 857, + 858, + 885, + 890, + 948, + 967, + 972 + ], + "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": [ + 1072, + 19, + 1587 + ], + "new_fact": [ + 1072, + 19, + 1655 + ], + "replay_indices": [ + 5, + 7, + 20, + 66, + 145, + 170, + 219, + 263, + 267, + 314, + 367, + 382, + 387, + 439, + 443, + 496, + 512, + 528, + 592, + 593, + 597, + 605, + 607, + 617, + 658, + 682, + 760, + 767, + 849, + 947, + 949, + 952 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1046, + 17, + 1588 + ], + "new_fact": [ + 1046, + 17, + 1604 + ], + "replay_indices": [ + 4, + 54, + 99, + 107, + 154, + 206, + 250, + 277, + 292, + 313, + 318, + 326, + 347, + 352, + 381, + 433, + 437, + 475, + 506, + 564, + 627, + 673, + 677, + 682, + 720, + 748, + 751, + 755, + 825, + 843, + 859, + 930 + ], + "affected_untrained_n": { + "D_second_familiar": 3, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 3, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 3 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1070, + 20, + 1667 + ], + "new_fact": [ + 1070, + 20, + 1593 + ], + "replay_indices": [ + 32, + 60, + 161, + 168, + 211, + 270, + 292, + 317, + 331, + 332, + 348, + 358, + 386, + 387, + 393, + 395, + 409, + 448, + 472, + 523, + 536, + 546, + 567, + 620, + 638, + 694, + 769, + 830, + 918, + 925, + 946, + 963 + ], + "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_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1075, + 18, + 1683 + ], + "new_fact": [ + 1075, + 18, + 1617 + ], + "replay_indices": [ + 28, + 49, + 154, + 220, + 229, + 248, + 276, + 279, + 291, + 315, + 319, + 376, + 406, + 424, + 444, + 457, + 458, + 502, + 535, + 545, + 571, + 600, + 635, + 668, + 696, + 735, + 752, + 790, + 812, + 848, + 937, + 978 + ], + "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": 2 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1110, + 17, + 1623 + ], + "new_fact": [ + 1110, + 17, + 1568 + ], + "replay_indices": [ + 3, + 22, + 67, + 78, + 97, + 139, + 180, + 183, + 184, + 251, + 280, + 282, + 385, + 511, + 534, + 552, + 554, + 577, + 580, + 641, + 651, + 674, + 702, + 720, + 731, + 749, + 760, + 784, + 794, + 858, + 888, + 948 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1133, + 19, + 1592 + ], + "new_fact": [ + 1133, + 19, + 1567 + ], + "replay_indices": [ + 10, + 15, + 48, + 50, + 102, + 114, + 134, + 174, + 221, + 295, + 307, + 397, + 405, + 451, + 505, + 510, + 522, + 563, + 580, + 606, + 644, + 706, + 774, + 788, + 789, + 857, + 865, + 881, + 902, + 914, + 918, + 964 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1129, + 20, + 1615 + ], + "new_fact": [ + 1129, + 20, + 1625 + ], + "replay_indices": [ + 74, + 92, + 241, + 242, + 266, + 270, + 296, + 307, + 321, + 383, + 403, + 433, + 489, + 494, + 500, + 503, + 579, + 604, + 606, + 618, + 636, + 663, + 691, + 766, + 771, + 789, + 837, + 880, + 908, + 922, + 938, + 982 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1114, + 17, + 1585 + ], + "new_fact": [ + 1114, + 17, + 1651 + ], + "replay_indices": [ + 11, + 28, + 64, + 86, + 118, + 162, + 199, + 220, + 286, + 342, + 347, + 390, + 462, + 475, + 486, + 489, + 538, + 548, + 665, + 675, + 751, + 774, + 793, + 813, + 829, + 855, + 905, + 969, + 980, + 984, + 998, + 1021 + ], + "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 + } + } + ], + "case_sha256": "9d756b45e73f2136e48ac1699cd6d992bf9ea9558875da442492b6d77e375384", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270013-shared_full-fixed", + "job_type": "editing", + "phase": "confirmation", + "world": 107270013, + "memory_arm": "shared_full", + "training_arm": "fixed", + "parent_name": "w107270013-shared_full-fixed", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270013-shared_full-fixed", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 61, + 16, + 1096 + ], + "new_fact": [ + 61, + 16, + 1064 + ], + "replay_indices": [ + 16, + 98, + 134, + 156, + 270, + 331, + 397, + 443, + 452, + 473, + 496, + 499, + 534, + 539, + 572, + 582, + 623, + 626, + 629, + 660, + 665, + 719, + 723, + 737, + 770, + 791, + 795, + 862, + 918, + 965, + 982, + 1015 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 84, + 14, + 1080 + ], + "new_fact": [ + 84, + 14, + 1096 + ], + "replay_indices": [ + 11, + 64, + 89, + 163, + 177, + 193, + 207, + 269, + 281, + 312, + 426, + 443, + 543, + 560, + 581, + 615, + 635, + 672, + 697, + 712, + 761, + 840, + 843, + 844, + 852, + 865, + 891, + 921, + 928, + 955, + 1005, + 1017 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 35, + 15, + 1080 + ], + "new_fact": [ + 35, + 15, + 1098 + ], + "replay_indices": [ + 31, + 53, + 86, + 116, + 119, + 164, + 175, + 187, + 218, + 306, + 346, + 389, + 408, + 449, + 458, + 516, + 590, + 616, + 639, + 640, + 645, + 688, + 747, + 758, + 777, + 838, + 840, + 955, + 972, + 975, + 995, + 1011 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 54, + 13, + 1052 + ], + "new_fact": [ + 54, + 13, + 1045 + ], + "replay_indices": [ + 17, + 36, + 117, + 129, + 143, + 152, + 175, + 206, + 210, + 288, + 306, + 341, + 352, + 378, + 403, + 464, + 493, + 540, + 595, + 612, + 615, + 636, + 699, + 702, + 849, + 859, + 865, + 919, + 940, + 975, + 976, + 1020 + ], + "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": [ + 115, + 13, + 1119 + ], + "new_fact": [ + 115, + 13, + 1115 + ], + "replay_indices": [ + 107, + 112, + 236, + 247, + 297, + 306, + 347, + 378, + 388, + 469, + 472, + 474, + 487, + 491, + 545, + 564, + 568, + 583, + 598, + 604, + 634, + 640, + 679, + 762, + 813, + 840, + 848, + 855, + 929, + 937, + 945, + 948 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 106, + 15, + 1112 + ], + "new_fact": [ + 106, + 15, + 1123 + ], + "replay_indices": [ + 15, + 31, + 45, + 77, + 84, + 105, + 112, + 118, + 217, + 270, + 300, + 375, + 390, + 443, + 502, + 508, + 550, + 600, + 610, + 697, + 726, + 739, + 751, + 806, + 817, + 901, + 907, + 928, + 937, + 950, + 972, + 1014 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 112, + 14, + 1131 + ], + "new_fact": [ + 112, + 14, + 1119 + ], + "replay_indices": [ + 52, + 75, + 132, + 160, + 184, + 207, + 213, + 214, + 285, + 287, + 304, + 361, + 366, + 417, + 455, + 470, + 472, + 529, + 530, + 553, + 724, + 775, + 780, + 801, + 802, + 833, + 923, + 924, + 937, + 955, + 1004, + 1005 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 101, + 15, + 1132 + ], + "new_fact": [ + 101, + 15, + 1116 + ], + "replay_indices": [ + 6, + 45, + 71, + 189, + 227, + 241, + 284, + 305, + 330, + 421, + 445, + 458, + 477, + 503, + 523, + 539, + 636, + 652, + 661, + 719, + 727, + 731, + 835, + 840, + 846, + 857, + 858, + 885, + 890, + 948, + 967, + 972 + ], + "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": [ + 1072, + 19, + 1587 + ], + "new_fact": [ + 1072, + 19, + 1655 + ], + "replay_indices": [ + 5, + 7, + 20, + 66, + 145, + 170, + 219, + 263, + 267, + 314, + 367, + 382, + 387, + 439, + 443, + 496, + 512, + 528, + 592, + 593, + 597, + 605, + 607, + 617, + 658, + 682, + 760, + 767, + 849, + 947, + 949, + 952 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1046, + 17, + 1588 + ], + "new_fact": [ + 1046, + 17, + 1604 + ], + "replay_indices": [ + 4, + 54, + 99, + 107, + 154, + 206, + 250, + 277, + 292, + 313, + 318, + 326, + 347, + 352, + 381, + 433, + 437, + 475, + 506, + 564, + 627, + 673, + 677, + 682, + 720, + 748, + 751, + 755, + 825, + 843, + 859, + 930 + ], + "affected_untrained_n": { + "D_second_familiar": 3, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 3, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 3 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1070, + 20, + 1667 + ], + "new_fact": [ + 1070, + 20, + 1593 + ], + "replay_indices": [ + 32, + 60, + 161, + 168, + 211, + 270, + 292, + 317, + 331, + 332, + 348, + 358, + 386, + 387, + 393, + 395, + 409, + 448, + 472, + 523, + 536, + 546, + 567, + 620, + 638, + 694, + 769, + 830, + 918, + 925, + 946, + 963 + ], + "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_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1075, + 18, + 1683 + ], + "new_fact": [ + 1075, + 18, + 1617 + ], + "replay_indices": [ + 28, + 49, + 154, + 220, + 229, + 248, + 276, + 279, + 291, + 315, + 319, + 376, + 406, + 424, + 444, + 457, + 458, + 502, + 535, + 545, + 571, + 600, + 635, + 668, + 696, + 735, + 752, + 790, + 812, + 848, + 937, + 978 + ], + "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": 2 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1110, + 17, + 1623 + ], + "new_fact": [ + 1110, + 17, + 1568 + ], + "replay_indices": [ + 3, + 22, + 67, + 78, + 97, + 139, + 180, + 183, + 184, + 251, + 280, + 282, + 385, + 511, + 534, + 552, + 554, + 577, + 580, + 641, + 651, + 674, + 702, + 720, + 731, + 749, + 760, + 784, + 794, + 858, + 888, + 948 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1133, + 19, + 1592 + ], + "new_fact": [ + 1133, + 19, + 1567 + ], + "replay_indices": [ + 10, + 15, + 48, + 50, + 102, + 114, + 134, + 174, + 221, + 295, + 307, + 397, + 405, + 451, + 505, + 510, + 522, + 563, + 580, + 606, + 644, + 706, + 774, + 788, + 789, + 857, + 865, + 881, + 902, + 914, + 918, + 964 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1129, + 20, + 1615 + ], + "new_fact": [ + 1129, + 20, + 1625 + ], + "replay_indices": [ + 74, + 92, + 241, + 242, + 266, + 270, + 296, + 307, + 321, + 383, + 403, + 433, + 489, + 494, + 500, + 503, + 579, + 604, + 606, + 618, + 636, + 663, + 691, + 766, + 771, + 789, + 837, + 880, + 908, + 922, + 938, + 982 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1114, + 17, + 1585 + ], + "new_fact": [ + 1114, + 17, + 1651 + ], + "replay_indices": [ + 11, + 28, + 64, + 86, + 118, + 162, + 199, + 220, + 286, + 342, + 347, + 390, + 462, + 475, + 486, + 489, + 538, + 548, + 665, + 675, + 751, + 774, + 793, + 813, + 829, + 855, + 905, + 969, + 980, + 984, + 998, + 1021 + ], + "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 + } + } + ], + "case_sha256": "9d756b45e73f2136e48ac1699cd6d992bf9ea9558875da442492b6d77e375384", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270013-shared_full-changed_atomic", + "job_type": "editing", + "phase": "confirmation", + "world": 107270013, + "memory_arm": "shared_full", + "training_arm": "changed_atomic", + "parent_name": "w107270013-shared_full-changed_atomic", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270013-shared_full-changed_atomic", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 61, + 16, + 1096 + ], + "new_fact": [ + 61, + 16, + 1064 + ], + "replay_indices": [ + 16, + 98, + 134, + 156, + 270, + 331, + 397, + 443, + 452, + 473, + 496, + 499, + 534, + 539, + 572, + 582, + 623, + 626, + 629, + 660, + 665, + 719, + 723, + 737, + 770, + 791, + 795, + 862, + 918, + 965, + 982, + 1015 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 84, + 14, + 1080 + ], + "new_fact": [ + 84, + 14, + 1096 + ], + "replay_indices": [ + 11, + 64, + 89, + 163, + 177, + 193, + 207, + 269, + 281, + 312, + 426, + 443, + 543, + 560, + 581, + 615, + 635, + 672, + 697, + 712, + 761, + 840, + 843, + 844, + 852, + 865, + 891, + 921, + 928, + 955, + 1005, + 1017 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 35, + 15, + 1080 + ], + "new_fact": [ + 35, + 15, + 1098 + ], + "replay_indices": [ + 31, + 53, + 86, + 116, + 119, + 164, + 175, + 187, + 218, + 306, + 346, + 389, + 408, + 449, + 458, + 516, + 590, + 616, + 639, + 640, + 645, + 688, + 747, + 758, + 777, + 838, + 840, + 955, + 972, + 975, + 995, + 1011 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 54, + 13, + 1052 + ], + "new_fact": [ + 54, + 13, + 1045 + ], + "replay_indices": [ + 17, + 36, + 117, + 129, + 143, + 152, + 175, + 206, + 210, + 288, + 306, + 341, + 352, + 378, + 403, + 464, + 493, + 540, + 595, + 612, + 615, + 636, + 699, + 702, + 849, + 859, + 865, + 919, + 940, + 975, + 976, + 1020 + ], + "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": [ + 115, + 13, + 1119 + ], + "new_fact": [ + 115, + 13, + 1115 + ], + "replay_indices": [ + 107, + 112, + 236, + 247, + 297, + 306, + 347, + 378, + 388, + 469, + 472, + 474, + 487, + 491, + 545, + 564, + 568, + 583, + 598, + 604, + 634, + 640, + 679, + 762, + 813, + 840, + 848, + 855, + 929, + 937, + 945, + 948 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 106, + 15, + 1112 + ], + "new_fact": [ + 106, + 15, + 1123 + ], + "replay_indices": [ + 15, + 31, + 45, + 77, + 84, + 105, + 112, + 118, + 217, + 270, + 300, + 375, + 390, + 443, + 502, + 508, + 550, + 600, + 610, + 697, + 726, + 739, + 751, + 806, + 817, + 901, + 907, + 928, + 937, + 950, + 972, + 1014 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 112, + 14, + 1131 + ], + "new_fact": [ + 112, + 14, + 1119 + ], + "replay_indices": [ + 52, + 75, + 132, + 160, + 184, + 207, + 213, + 214, + 285, + 287, + 304, + 361, + 366, + 417, + 455, + 470, + 472, + 529, + 530, + 553, + 724, + 775, + 780, + 801, + 802, + 833, + 923, + 924, + 937, + 955, + 1004, + 1005 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 101, + 15, + 1132 + ], + "new_fact": [ + 101, + 15, + 1116 + ], + "replay_indices": [ + 6, + 45, + 71, + 189, + 227, + 241, + 284, + 305, + 330, + 421, + 445, + 458, + 477, + 503, + 523, + 539, + 636, + 652, + 661, + 719, + 727, + 731, + 835, + 840, + 846, + 857, + 858, + 885, + 890, + 948, + 967, + 972 + ], + "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": [ + 1072, + 19, + 1587 + ], + "new_fact": [ + 1072, + 19, + 1655 + ], + "replay_indices": [ + 5, + 7, + 20, + 66, + 145, + 170, + 219, + 263, + 267, + 314, + 367, + 382, + 387, + 439, + 443, + 496, + 512, + 528, + 592, + 593, + 597, + 605, + 607, + 617, + 658, + 682, + 760, + 767, + 849, + 947, + 949, + 952 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1046, + 17, + 1588 + ], + "new_fact": [ + 1046, + 17, + 1604 + ], + "replay_indices": [ + 4, + 54, + 99, + 107, + 154, + 206, + 250, + 277, + 292, + 313, + 318, + 326, + 347, + 352, + 381, + 433, + 437, + 475, + 506, + 564, + 627, + 673, + 677, + 682, + 720, + 748, + 751, + 755, + 825, + 843, + 859, + 930 + ], + "affected_untrained_n": { + "D_second_familiar": 3, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 3, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 3 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1070, + 20, + 1667 + ], + "new_fact": [ + 1070, + 20, + 1593 + ], + "replay_indices": [ + 32, + 60, + 161, + 168, + 211, + 270, + 292, + 317, + 331, + 332, + 348, + 358, + 386, + 387, + 393, + 395, + 409, + 448, + 472, + 523, + 536, + 546, + 567, + 620, + 638, + 694, + 769, + 830, + 918, + 925, + 946, + 963 + ], + "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_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1075, + 18, + 1683 + ], + "new_fact": [ + 1075, + 18, + 1617 + ], + "replay_indices": [ + 28, + 49, + 154, + 220, + 229, + 248, + 276, + 279, + 291, + 315, + 319, + 376, + 406, + 424, + 444, + 457, + 458, + 502, + 535, + 545, + 571, + 600, + 635, + 668, + 696, + 735, + 752, + 790, + 812, + 848, + 937, + 978 + ], + "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": 2 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1110, + 17, + 1623 + ], + "new_fact": [ + 1110, + 17, + 1568 + ], + "replay_indices": [ + 3, + 22, + 67, + 78, + 97, + 139, + 180, + 183, + 184, + 251, + 280, + 282, + 385, + 511, + 534, + 552, + 554, + 577, + 580, + 641, + 651, + 674, + 702, + 720, + 731, + 749, + 760, + 784, + 794, + 858, + 888, + 948 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1133, + 19, + 1592 + ], + "new_fact": [ + 1133, + 19, + 1567 + ], + "replay_indices": [ + 10, + 15, + 48, + 50, + 102, + 114, + 134, + 174, + 221, + 295, + 307, + 397, + 405, + 451, + 505, + 510, + 522, + 563, + 580, + 606, + 644, + 706, + 774, + 788, + 789, + 857, + 865, + 881, + 902, + 914, + 918, + 964 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1129, + 20, + 1615 + ], + "new_fact": [ + 1129, + 20, + 1625 + ], + "replay_indices": [ + 74, + 92, + 241, + 242, + 266, + 270, + 296, + 307, + 321, + 383, + 403, + 433, + 489, + 494, + 500, + 503, + 579, + 604, + 606, + 618, + 636, + 663, + 691, + 766, + 771, + 789, + 837, + 880, + 908, + 922, + 938, + 982 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1114, + 17, + 1585 + ], + "new_fact": [ + 1114, + 17, + 1651 + ], + "replay_indices": [ + 11, + 28, + 64, + 86, + 118, + 162, + 199, + 220, + 286, + 342, + 347, + 390, + 462, + 475, + 486, + 489, + 538, + 548, + 665, + 675, + 751, + 774, + 793, + 813, + 829, + 855, + 905, + 969, + 980, + 984, + 998, + 1021 + ], + "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 + } + } + ], + "case_sha256": "9d756b45e73f2136e48ac1699cd6d992bf9ea9558875da442492b6d77e375384", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + }, + { + "name": "edit-w107270013-shared_full-changed_use", + "job_type": "editing", + "phase": "confirmation", + "world": 107270013, + "memory_arm": "shared_full", + "training_arm": "changed_use", + "parent_name": "w107270013-shared_full-changed_use", + "parent_dir": "/ossfs/workspace/llm-memory-editability/results/knowledge-change-v1/runs/w107270013-shared_full-changed_use", + "candidate_seed": 107270041, + "per_cell": 16, + "replay_n": 32, + "case_ids": [ + "first_familiar-00", + "first_familiar-01", + "first_familiar-02", + "first_familiar-03", + "first_strict-00", + "first_strict-01", + "first_strict-02", + "first_strict-03", + "second_familiar-00", + "second_familiar-01", + "second_familiar-02", + "second_familiar-03", + "second_strict-00", + "second_strict-01", + "second_strict-02", + "second_strict-03" + ], + "cases": [ + { + "case_id": "first_familiar-00", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 61, + 16, + 1096 + ], + "new_fact": [ + 61, + 16, + 1064 + ], + "replay_indices": [ + 16, + 98, + 134, + 156, + 270, + 331, + 397, + 443, + 452, + 473, + 496, + 499, + 534, + 539, + 572, + 582, + 623, + 626, + 629, + 660, + 665, + 719, + 723, + 737, + 770, + 791, + 795, + 862, + 918, + 965, + 982, + 1015 + ], + "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_familiar-01", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 84, + 14, + 1080 + ], + "new_fact": [ + 84, + 14, + 1096 + ], + "replay_indices": [ + 11, + 64, + 89, + 163, + 177, + 193, + 207, + 269, + 281, + 312, + 426, + 443, + 543, + 560, + 581, + 615, + 635, + 672, + 697, + 712, + 761, + 840, + 843, + 844, + 852, + 865, + 891, + 921, + 928, + 955, + 1005, + 1017 + ], + "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_familiar-02", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 35, + 15, + 1080 + ], + "new_fact": [ + 35, + 15, + 1098 + ], + "replay_indices": [ + 31, + 53, + 86, + 116, + 119, + 164, + 175, + 187, + 218, + 306, + 346, + 389, + 408, + 449, + 458, + 516, + 590, + 616, + 639, + 640, + 645, + 688, + 747, + 758, + 777, + 838, + 840, + 955, + 972, + 975, + 995, + 1011 + ], + "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_familiar-03", + "role": "first", + "stratum": "familiar", + "old_fact": [ + 54, + 13, + 1052 + ], + "new_fact": [ + 54, + 13, + 1045 + ], + "replay_indices": [ + 17, + 36, + 117, + 129, + 143, + 152, + 175, + 206, + 210, + 288, + 306, + 341, + 352, + 378, + 403, + 464, + 493, + 540, + 595, + 612, + 615, + 636, + 699, + 702, + 849, + 859, + 865, + 919, + 940, + 975, + 976, + 1020 + ], + "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": [ + 115, + 13, + 1119 + ], + "new_fact": [ + 115, + 13, + 1115 + ], + "replay_indices": [ + 107, + 112, + 236, + 247, + 297, + 306, + 347, + 378, + 388, + 469, + 472, + 474, + 487, + 491, + 545, + 564, + 568, + 583, + 598, + 604, + 634, + 640, + 679, + 762, + 813, + 840, + 848, + 855, + 929, + 937, + 945, + 948 + ], + "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": "first_strict-01", + "role": "first", + "stratum": "strict", + "old_fact": [ + 106, + 15, + 1112 + ], + "new_fact": [ + 106, + 15, + 1123 + ], + "replay_indices": [ + 15, + 31, + 45, + 77, + 84, + 105, + 112, + 118, + 217, + 270, + 300, + 375, + 390, + 443, + 502, + 508, + 550, + 600, + 610, + 697, + 726, + 739, + 751, + 806, + 817, + 901, + 907, + 928, + 937, + 950, + 972, + 1014 + ], + "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": "first_strict-02", + "role": "first", + "stratum": "strict", + "old_fact": [ + 112, + 14, + 1131 + ], + "new_fact": [ + 112, + 14, + 1119 + ], + "replay_indices": [ + 52, + 75, + 132, + 160, + 184, + 207, + 213, + 214, + 285, + 287, + 304, + 361, + 366, + 417, + 455, + 470, + 472, + 529, + 530, + 553, + 724, + 775, + 780, + 801, + 802, + 833, + 923, + 924, + 937, + 955, + 1004, + 1005 + ], + "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": "first_strict-03", + "role": "first", + "stratum": "strict", + "old_fact": [ + 101, + 15, + 1132 + ], + "new_fact": [ + 101, + 15, + 1116 + ], + "replay_indices": [ + 6, + 45, + 71, + 189, + 227, + 241, + 284, + 305, + 330, + 421, + 445, + 458, + 477, + 503, + 523, + 539, + 636, + 652, + 661, + 719, + 727, + 731, + 835, + 840, + 846, + 857, + 858, + 885, + 890, + 948, + 967, + 972 + ], + "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": [ + 1072, + 19, + 1587 + ], + "new_fact": [ + 1072, + 19, + 1655 + ], + "replay_indices": [ + 5, + 7, + 20, + 66, + 145, + 170, + 219, + 263, + 267, + 314, + 367, + 382, + 387, + 439, + 443, + 496, + 512, + 528, + 592, + 593, + 597, + 605, + 607, + 617, + 658, + 682, + 760, + 767, + 849, + 947, + 949, + 952 + ], + "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": 3 + } + }, + { + "case_id": "second_familiar-01", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1046, + 17, + 1588 + ], + "new_fact": [ + 1046, + 17, + 1604 + ], + "replay_indices": [ + 4, + 54, + 99, + 107, + 154, + 206, + 250, + 277, + 292, + 313, + 318, + 326, + 347, + 352, + 381, + 433, + 437, + 475, + 506, + 564, + 627, + 673, + 677, + 682, + 720, + 748, + 751, + 755, + 825, + 843, + 859, + 930 + ], + "affected_untrained_n": { + "D_second_familiar": 3, + "S_same_answer_second_familiar": 0, + "D_second_strict": 0, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 3, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 3 + } + }, + { + "case_id": "second_familiar-02", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1070, + 20, + 1667 + ], + "new_fact": [ + 1070, + 20, + 1593 + ], + "replay_indices": [ + 32, + 60, + 161, + 168, + 211, + 270, + 292, + 317, + 331, + 332, + 348, + 358, + 386, + 387, + 393, + 395, + 409, + 448, + 472, + 523, + 536, + 546, + 567, + 620, + 638, + 694, + 769, + 830, + 918, + 925, + 946, + 963 + ], + "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_familiar-03", + "role": "second", + "stratum": "familiar", + "old_fact": [ + 1075, + 18, + 1683 + ], + "new_fact": [ + 1075, + 18, + 1617 + ], + "replay_indices": [ + 28, + 49, + 154, + 220, + 229, + 248, + 276, + 279, + 291, + 315, + 319, + 376, + 406, + 424, + 444, + 457, + 458, + 502, + 535, + 545, + 571, + 600, + 635, + 668, + 696, + 735, + 752, + 790, + 812, + 848, + 937, + 978 + ], + "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": 2 + } + }, + { + "case_id": "second_strict-00", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1110, + 17, + 1623 + ], + "new_fact": [ + 1110, + 17, + 1568 + ], + "replay_indices": [ + 3, + 22, + 67, + 78, + 97, + 139, + 180, + 183, + 184, + 251, + 280, + 282, + 385, + 511, + 534, + 552, + 554, + 577, + 580, + 641, + 651, + 674, + 702, + 720, + 731, + 749, + 760, + 784, + 794, + 858, + 888, + 948 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 6, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-01", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1133, + 19, + 1592 + ], + "new_fact": [ + 1133, + 19, + 1567 + ], + "replay_indices": [ + 10, + 15, + 48, + 50, + 102, + 114, + 134, + 174, + 221, + 295, + 307, + 397, + 405, + 451, + 505, + 510, + 522, + 563, + 580, + 606, + 644, + 706, + 774, + 788, + 789, + 857, + 865, + 881, + 902, + 914, + 918, + 964 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 4, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-02", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1129, + 20, + 1615 + ], + "new_fact": [ + 1129, + 20, + 1625 + ], + "replay_indices": [ + 74, + 92, + 241, + 242, + 266, + 270, + 296, + 307, + 321, + 383, + 403, + 433, + 489, + 494, + 500, + 503, + 579, + 604, + 606, + 618, + 636, + 663, + 691, + 766, + 771, + 789, + 837, + 880, + 908, + 922, + 938, + 982 + ], + "affected_untrained_n": { + "D_second_familiar": 0, + "S_same_answer_second_familiar": 0, + "D_second_strict": 3, + "S_same_answer_second_strict": 0, + "D_second_registered_familiar": 0, + "S_same_answer_second_registered_familiar": 0, + "T_second_train": 0 + } + }, + { + "case_id": "second_strict-03", + "role": "second", + "stratum": "strict", + "old_fact": [ + 1114, + 17, + 1585 + ], + "new_fact": [ + 1114, + 17, + 1651 + ], + "replay_indices": [ + 11, + 28, + 64, + 86, + 118, + 162, + 199, + 220, + 286, + 342, + 347, + 390, + 462, + 475, + 486, + 489, + 538, + 548, + 665, + 675, + 751, + 774, + 793, + 813, + 829, + 855, + 905, + 969, + 980, + 984, + 998, + 1021 + ], + "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 + } + } + ], + "case_sha256": "9d756b45e73f2136e48ac1699cd6d992bf9ea9558875da442492b6d77e375384", + "nodes": [ + 0, + 128, + 512 + ], + "lr": 0.0001, + "replay_weight": 1.0, + "parameter_scope": "mlp", + "block_index": 0 + } + ], + "gpus": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "created_utc": "2026-10-06T18:34:57.487874+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": 5400, + "maximum_edit_seconds": 3600, + "maximum_engineering_seconds": 600, + "maximum_gpu_hours": 25, + "development_gate": { + "atomic": 0.95, + "train_composite": 0.9, + "inner_success": 0.9 + }, + "development_selection": "No selection on propagation or familiar/strict accuracy; failed prerequisites stop confirmation", + "independent_confirmation_worlds": 3 +} diff --git a/docs/development-artifacts/knowledge-change-v1/postprocessing-source/analyze_knowledge_change.py b/docs/development-artifacts/knowledge-change-v1/postprocessing-source/analyze_knowledge_change.py new file mode 100644 index 0000000000000000000000000000000000000000..dbc016b273eb36780b466dbce44d6c54901305d9 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-v1/postprocessing-source/analyze_knowledge_change.py @@ -0,0 +1,203 @@ +"""Paired-world differences, common baseline mastery and exportable figures.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import shutil +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from llm_memory_editability.grok_depth import utc, write_json + + +def mean(values): + values = [v for v in values if v is not None] + return float(np.mean(values)) if values else None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + args = parser.parse_args() + root = args.root + summary = json.loads((root / "report/summary.json").read_text()) + by_world = defaultdict(dict) + for row in summary["editing_worlds"]: + if row["arm"] == "edit": + by_world[(row["phase"], row["world"], row["memory"], row["role"], row["stratum"])][ + row["training"] + ] = row + differences = [] + for (phase, world, memory, role, stratum), arms in by_world.items(): + if len(arms) != 3: + continue + for control in ["fixed", "changed_atomic"]: + differences.append( + dict( + phase=phase, + world=world, + memory=memory, + role=role, + stratum=stratum, + treatment="changed_use", + control=control, + D_difference=arms["changed_use"]["D"] - arms[control]["D"], + E_difference=arms["changed_use"]["E"] - arms[control]["E"], + U_difference=arms["changed_use"]["U"] - arms[control]["U"], + ) + ) + # Exploratory cohort: common original-answer mastery across all six parents. + # This conditions on training outcomes; full graph-selected D remains primary. + cohorts = defaultdict(dict) + for row in summary["editing_cases"]: + if row["arm"] == "edit": + cohorts[(row["phase"], row["world"], row["case"], row["role"], row["stratum"])][ + (row["memory"], row["training"]) + ] = row + common_rows = [] + for (phase, world, case, role, stratum), arms in cohorts.items(): + if len(arms) != 6: + continue + loaded = {} + task = f"D_{role}_{stratum}" + for key, row in arms.items(): + directory = root / "runs" / ("edit-" + row["parent"]) / case + with np.load(directory / "lr0.0001-edit/predictions-000512.npz") as saved: + loaded[key] = { + name: saved[name].copy() + for name in [ + task + "__parent_correct", + task + "__correct", + task + "__old_rows", + task + "__new_rows", + ] + } + reference = next(iter(loaded.values())) + for values in loaded.values(): + for field in ["old_rows", "new_rows"]: + np.testing.assert_array_equal( + values[task + "__" + field], reference[task + "__" + field] + ) + common = np.logical_and.reduce([v[task + "__parent_correct"] for v in loaded.values()]) + for (memory, training), values in loaded.items(): + common_rows.append( + dict( + phase=phase, + world=world, + case=case, + role=role, + stratum=stratum, + memory=memory, + training=training, + n=len(common), + common_n=int(common.sum()), + coverage=float(common.mean()), + D=float(values[task + "__correct"][common].mean()) if common.any() else None, + ) + ) + analysis = dict( + paired_world_differences=differences, + exploratory_common_mastery=common_rows, + common_subset_warning=( + "Post-training cohort across all six parents; exploratory, " + "not primary and not independent replicates" + ), + ) + write_json(root / "report/analysis.json", analysis) + try: + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + for phase in sorted({r["phase"] for r in summary["endpoints"]}): + fig, axes = plt.subplots(1, 3, figsize=(12, 3.8)) + labels = ["Fixed", "Changed: atomics", "Changed: use"] + arms = ["fixed", "changed_atomic", "changed_use"] + for memory, offset, color in [ + ("local", -0.17, "#5975a4"), + ("shared_full", 0.17, "#cc8963"), + ]: + base = { + r["training"]: r + for r in summary["endpoint_means"] + if r["phase"] == phase and r["memory"] == memory + } + if len(base) != 3: + continue + axes[0].bar( + np.arange(3) + offset, + [base[a]["familiar"] * 100 for a in arms], + width=0.32, + label=memory, + color=color, + ) + for axis, role in zip(axes[1:], ["first", "second"], strict=True): + rows = { + r["training"]: r + for r in summary["editing_means"] + if r["phase"] == phase + and r["memory"] == memory + and r["role"] == role + and r["stratum"] == "familiar" + and r["arm"] == "edit" + } + if len(rows) == 3: + axis.bar( + np.arange(3) + offset, + [rows[a]["D"] * 100 for a in arms], + width=0.32, + color=color, + ) + for axis, title in zip( + axes, + [ + "Original familiar composition", + "After unseen first-hop edits", + "After unseen second-hop edits", + ], + strict=True, + ): + axis.set_title(title, fontsize=10) + axis.set_xticks(np.arange(3), labels, rotation=15, fontsize=8) + axis.set_ylim(0, 105) + axis.set_ylabel("Full-answer accuracy (%)") + axis.spines[["top", "right"]].set_visible(False) + axes[0].legend(fontsize=8) + fig.suptitle( + phase + ": equal-world means; factual addresses reserved before training", + fontsize=10, + ) + fig.tight_layout() + for extension in ["png", "pdf"]: + fig.savefig(root / "report" / f"{phase}.{extension}", dpi=160) + plt.close(fig) + except ImportError: + analysis["plot_unavailable"] = True + write_json(root / "report/analysis.json", analysis) + artifact = root.parents[1] / "docs/development-artifacts" / root.name / "postprocessing-source" + artifact.mkdir(parents=True, exist_ok=True) + path = Path(__file__).resolve() + target = artifact / path.name + if target.exists() and target.read_bytes() != path.read_bytes(): + raise FileExistsError("Do not replace a different postprocessing snapshot") + if not target.exists(): + shutil.copy2(path, target) + write_json( + root / "postprocessing-provenance.json", + dict( + utc=utc(), + path=str(target), + sha256=hashlib.sha256(target.read_bytes()).hexdigest(), + exploratory_common_subset=True, + ), + ) + print(json.dumps(dict(paired_worlds=len(differences), common_case_rows=len(common_rows)))) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/knowledge-change-v1/postprocessing-source/finalize_knowledge_change.py b/docs/development-artifacts/knowledge-change-v1/postprocessing-source/finalize_knowledge_change.py new file mode 100644 index 0000000000000000000000000000000000000000..61dc4039eca5ccb5348d4fa6d45ac24132161115 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-v1/postprocessing-source/finalize_knowledge_change.py @@ -0,0 +1,99 @@ +"""Finish analysis and independently verify W&B when the batch becomes terminal.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +from pathlib import Path + +from llm_memory_editability.grok_depth import utc, write_json + + +def read(path): + return json.loads(Path(path).read_text()) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--analyzer", type=Path, required=True) + args = parser.parse_args() + config = read(args.config) + write_json(args.root / "finalizer-process.json", dict(pid=os.getpid(), utc=utc())) + terminal = {"complete", "finished_with_failures", "development_prerequisite_not_met"} + while True: + state = read(args.root / "controller-state.json") + if state["state"] in terminal: + break + time.sleep(15) + subprocess.run([sys.executable, str(args.analyzer), "--root", str(args.root)], check=True) + source_valid = all( + hashlib.sha256((Path(config["source_root"]) / path).read_bytes()).hexdigest() == digest + for path, digest in config["source"].items() + ) + assert source_valid, "Frozen sources changed" + local = [] + for name in state["completed"]: + directory = args.root / "runs" / name + assert read(directory / "audit.json")["passed"] + local.append(dict(name=name, audited=True)) + tracking_ready = False + for _ in range(120): + path = args.root / "tracking-completion.json" + if path.exists() and read(path)["passed"]: + tracking_ready = True + break + time.sleep(15) + if not tracking_ready: + write_json( + args.root / "finalizer-failure.json", dict(reason="W&B tracking not drained", utc=utc()) + ) + raise RuntimeError("W&B tracking not drained") + import wandb + + api = wandb.Api(timeout=30) + remote = [] + for name in state["completed"]: + directory = args.root / "runs" / name + tracking = read(args.root / "tracking-wandb" / name / "state.json") + run = api.run(f"zhusq20/llm-memory-editability/{tracking['run_id']}") + last = read(directory / "learning.json")[-1]["step"] + assert run.name == name and run.group == config["batch"] + 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 + remote.append(dict(name=name, run_id=run.id, last_step=last, url=run.url)) + write_json( + args.root / "cloud-final-audit.json", + dict(passed=True, runs=remote, registered_runs=len(remote), utc=utc()), + ) + report = read(args.root / "report/summary.json") + write_json( + args.root / "completion-manifest.json", + dict( + executed_jobs_audited=True, + full_confirmation_complete=state["state"] == "complete" and not report["missing"], + state=state["state"], + completed=len(state["completed"]), + failed=state["failed"], + missing_planned_jobs=report["missing"], + reader_trainings=len(report["endpoints"]), + edit_sham_branches=len(report["editing_cases"]), + sources_unchanged=source_valid, + cloud_runs_verified=len(remote), + allocated_gpu_hours=state.get("allocated_gpu_hours"), + utc=utc(), + ), + ) + print(json.dumps(dict(local=len(local), cloud=len(remote), state=state["state"])), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/knowledge-change-v1/postprocessing-source/manifest.json b/docs/development-artifacts/knowledge-change-v1/postprocessing-source/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..e749c1e5bde6ac5fb9a848f73988f219c629824d --- /dev/null +++ b/docs/development-artifacts/knowledge-change-v1/postprocessing-source/manifest.json @@ -0,0 +1,4 @@ +{ + "analyze_knowledge_change.py": "4dcea7b0be4e3d9ec02929db3cc7154de02448563b0f4006d00b1bc0edeee87e", + "finalize_knowledge_change.py": "6d1171d6be2d04f6a8d0d33294c68b74c4f4ac294f9fde7737715b1236cf58d6" +} diff --git a/docs/development-artifacts/knowledge-change-v1/protocol.md b/docs/development-artifacts/knowledge-change-v1/protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..daa2311eddefcb63050c7829e03d96250a3796a6 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-v1/protocol.md @@ -0,0 +1,35 @@ +# 知识变化中的调用学习 + +2026-10-07用户授权实际执行。主问题:在变化的事实参数状态下练习组合使用,是否提升未见事实更新后的组合回答?结论层级为受控人工任务中的训练方法有效性。无额外状态预测器,不做本批KV patch矩阵。 + +## 文献与方法来源 + +共享访问复用已核验的LPT式首轮KV读通路:[Monea et al., 2026](https://arxiv.org/html/2610.02383v1),保持现有GPT2/pre-LN/GELU小模型,论文为RMSNorm/SwiGLU/RoPE,因此不是完整预训练复现。仅选local/shared_full,避开窗口和detach带来的上下文与编辑梯度差异。 + +[Editable Neural Networks](https://arxiv.org/html/2004.00345v2)在编辑后的可靠性/局部性损失上通过编辑器反传;本批不复现二阶元学习,也不训练编辑器,而采用临时原子参数编辑下的调用适应。多跳更新评估沿用[MQuAKE](https://arxiv.org/abs/2305.14795)的派生答案要求,在人工图中精确重算真值。不得声称首先提出可编辑训练或多跳编辑评价。 + +## 配对比较 + +两架构×三训练臂:fixed固定事实、changed_atomic原子改变但只训练新原子及不受影响的组合、changed_use原子改变并训练受影响组合。每架构同父状态分出三臂;两架构初值/语料/预算相同。fixed即同预算额外普通组合训练控制,不与未续训父模型混淆。changed_atomic是事实变化经历控制,其组合查询曝光不同,不声称完全监督匹配。 + +开发复用730011的既有128k父模型,只读复制、不重新训练旧批。正式三个新图107270011/12/13,两架构各从相同随机初值训练128k。模型每轮4块、R4、宽128、4头、无dropout;基础语料/采样/优化复用latent-scaling-v1。每世界三训练臂同父状态。 + +每个调用学习片段先仅编辑共享的首块MLP,512步Adam lr1e-4,原子答案/句点/EOS CE加32无关原子的冻结参考KL,clip1,无组合或桥标签。随后冻结该MLP,训练所有剩余参数512步,AdamW lr1e-4/无weight decay,batch192,四等长采样流:当前目标原子、其他原子、强调组合、不受影响组合。fixed/changed_use强调相同的原始训练查询,changed_use按当前图更新答案。changed_atomic用不受影响组合替代强调流,避免给出与新事实矛盾的旧答案。 + +片段结束精确还原首块MLP,保留其余参数学习;共32片段,八个训练事实(每角色四个)循环四次。各片段新优化器、配对随机采样种子。此固定范围是为使临时参数更新可以精确撤回的受控实现,不证明事实只存于该MLP,不等同于无限制动态世界预训练。所有臂都采用相同冻结范围。 + +## 划分与评分 + +先按图、独立于模型表现生成每角色/事实池16候选案例,每格前4个保留测试;所有测试更新地址优先保留,再取熟悉且有训练组合后果的每角色4个训练地址。训练更新和测试更新地址完全不交。训练仅使用原注册训练查询,familiar/strict查询不输入优化;中间桥不会出现在组合文本。自然语言事实/新关系类型未测试。 + +每个终点在16个测试事实(熟悉/严格×首/次跳×4)分别执行edit及旧事实sham;同一512步首MLP编辑器与32原子KL回放。节点0/128/512,全部直接E、必要后继原子、回放R、未回放U原子、未影响U组合、派生D和训练查询T分别保存。主D为受影响留出问题,先按事实等权,再世界等权。父模型本已正确子集和操作成功子集只作条件分析,覆盖必报;不把原先不会的组合都称为更新传播失败。所有逐节点独立进程重载。 + +## 开发门槛与预算 + +只用操作前提决定是否开展正式比较:六开发臂终点common/anchor原子≥95%、训练组合≥90%、32片段直接写入平均≥90%,工程/重载通过。传播率和熟悉/严格测试分数不用于选择。配方不根据正式结果调整。门槛失败保存六臂及全部开发编辑结果,停止新世界;下一配方需另立开发修订。 + +计划6条新世界基础训练、24条调用续训、24项测试编辑任务(共768分支),外加2个既有开发父状态只读复制;8GPU独立容器,LM专属Docker固定镜像。上限25 GPU小时,单训练5400秒、编辑3600秒、工程600秒;控制器拒绝静默重启。所有原始低分/失败保留,不把运行完成等同研究假设得到支持。W&B在线默认开启。 + +## 执行与计算边界 + +冻结全部源代码、配置与图划分哈希。训练节点0/1/8/16/24/32片段保存权重与原始预测,精确核对MLP恢复。编辑原始张量和预测逐节点独立重载。记录片段原子写入与使用后保持,所有曝光与计算采用执行形状近似,冻结MLP和KL下不宣称精确反向FLOPs;同架构各训练臂更新数/批量/长度一致。人工图、单初始化/世界、有限回放编辑范围限制推广;方法含新增反事实组合监督,不声称从单跳标签无监督学得全部组合。 diff --git a/docs/development-artifacts/knowledge-change-v1/source/configs/experiment-tracking-defaults.json b/docs/development-artifacts/knowledge-change-v1/source/configs/experiment-tracking-defaults.json new file mode 100644 index 0000000000000000000000000000000000000000..92273f717dfdee8e79a02a1a3fd47f874f8435f8 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/docs/development-artifacts/knowledge-change-v1/protocol.md b/docs/development-artifacts/knowledge-change-v1/source/docs/development-artifacts/knowledge-change-v1/protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..daa2311eddefcb63050c7829e03d96250a3796a6 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-v1/source/docs/development-artifacts/knowledge-change-v1/protocol.md @@ -0,0 +1,35 @@ +# 知识变化中的调用学习 + +2026-10-07用户授权实际执行。主问题:在变化的事实参数状态下练习组合使用,是否提升未见事实更新后的组合回答?结论层级为受控人工任务中的训练方法有效性。无额外状态预测器,不做本批KV patch矩阵。 + +## 文献与方法来源 + +共享访问复用已核验的LPT式首轮KV读通路:[Monea et al., 2026](https://arxiv.org/html/2610.02383v1),保持现有GPT2/pre-LN/GELU小模型,论文为RMSNorm/SwiGLU/RoPE,因此不是完整预训练复现。仅选local/shared_full,避开窗口和detach带来的上下文与编辑梯度差异。 + +[Editable Neural Networks](https://arxiv.org/html/2004.00345v2)在编辑后的可靠性/局部性损失上通过编辑器反传;本批不复现二阶元学习,也不训练编辑器,而采用临时原子参数编辑下的调用适应。多跳更新评估沿用[MQuAKE](https://arxiv.org/abs/2305.14795)的派生答案要求,在人工图中精确重算真值。不得声称首先提出可编辑训练或多跳编辑评价。 + +## 配对比较 + +两架构×三训练臂:fixed固定事实、changed_atomic原子改变但只训练新原子及不受影响的组合、changed_use原子改变并训练受影响组合。每架构同父状态分出三臂;两架构初值/语料/预算相同。fixed即同预算额外普通组合训练控制,不与未续训父模型混淆。changed_atomic是事实变化经历控制,其组合查询曝光不同,不声称完全监督匹配。 + +开发复用730011的既有128k父模型,只读复制、不重新训练旧批。正式三个新图107270011/12/13,两架构各从相同随机初值训练128k。模型每轮4块、R4、宽128、4头、无dropout;基础语料/采样/优化复用latent-scaling-v1。每世界三训练臂同父状态。 + +每个调用学习片段先仅编辑共享的首块MLP,512步Adam lr1e-4,原子答案/句点/EOS CE加32无关原子的冻结参考KL,clip1,无组合或桥标签。随后冻结该MLP,训练所有剩余参数512步,AdamW lr1e-4/无weight decay,batch192,四等长采样流:当前目标原子、其他原子、强调组合、不受影响组合。fixed/changed_use强调相同的原始训练查询,changed_use按当前图更新答案。changed_atomic用不受影响组合替代强调流,避免给出与新事实矛盾的旧答案。 + +片段结束精确还原首块MLP,保留其余参数学习;共32片段,八个训练事实(每角色四个)循环四次。各片段新优化器、配对随机采样种子。此固定范围是为使临时参数更新可以精确撤回的受控实现,不证明事实只存于该MLP,不等同于无限制动态世界预训练。所有臂都采用相同冻结范围。 + +## 划分与评分 + +先按图、独立于模型表现生成每角色/事实池16候选案例,每格前4个保留测试;所有测试更新地址优先保留,再取熟悉且有训练组合后果的每角色4个训练地址。训练更新和测试更新地址完全不交。训练仅使用原注册训练查询,familiar/strict查询不输入优化;中间桥不会出现在组合文本。自然语言事实/新关系类型未测试。 + +每个终点在16个测试事实(熟悉/严格×首/次跳×4)分别执行edit及旧事实sham;同一512步首MLP编辑器与32原子KL回放。节点0/128/512,全部直接E、必要后继原子、回放R、未回放U原子、未影响U组合、派生D和训练查询T分别保存。主D为受影响留出问题,先按事实等权,再世界等权。父模型本已正确子集和操作成功子集只作条件分析,覆盖必报;不把原先不会的组合都称为更新传播失败。所有逐节点独立进程重载。 + +## 开发门槛与预算 + +只用操作前提决定是否开展正式比较:六开发臂终点common/anchor原子≥95%、训练组合≥90%、32片段直接写入平均≥90%,工程/重载通过。传播率和熟悉/严格测试分数不用于选择。配方不根据正式结果调整。门槛失败保存六臂及全部开发编辑结果,停止新世界;下一配方需另立开发修订。 + +计划6条新世界基础训练、24条调用续训、24项测试编辑任务(共768分支),外加2个既有开发父状态只读复制;8GPU独立容器,LM专属Docker固定镜像。上限25 GPU小时,单训练5400秒、编辑3600秒、工程600秒;控制器拒绝静默重启。所有原始低分/失败保留,不把运行完成等同研究假设得到支持。W&B在线默认开启。 + +## 执行与计算边界 + +冻结全部源代码、配置与图划分哈希。训练节点0/1/8/16/24/32片段保存权重与原始预测,精确核对MLP恢复。编辑原始张量和预测逐节点独立重载。记录片段原子写入与使用后保持,所有曝光与计算采用执行形状近似,冻结MLP和KL下不宣称精确反向FLOPs;同架构各训练臂更新数/批量/长度一致。人工图、单初始化/世界、有限回放编辑范围限制推广;方法含新增反事实组合监督,不声称从单跳标签无监督学得全部组合。 diff --git a/docs/development-artifacts/knowledge-change-v1/source/scripts/report_knowledge_change.py b/docs/development-artifacts/knowledge-change-v1/source/scripts/report_knowledge_change.py new file mode 100644 index 0000000000000000000000000000000000000000..ab55422807d432a95f33d4d0edd39970a8fa5237 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-v1/source/scripts/report_knowledge_change.py @@ -0,0 +1,226 @@ +"""World-weighted reports of training in fixed and changed factual states.""" + +from __future__ import annotations + +import argparse +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from llm_memory_editability.grok_depth import write_json + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + args = parser.parse_args() + config = json.loads(args.config.read_text()) + root = Path(config["repository"]) / "results" / config["batch"] + out = root / "report" + out.mkdir(exist_ok=True) + endpoints, edits, missing = [], [], [] + for spec in config["specs"] + config["editing_specs"]: + directory = root / "runs" / spec["name"] + path = directory / "complete.json" + if not path.exists(): + missing.append(spec["name"]) + continue + result = json.loads(path.read_text()) + audit_path = directory / "audit.json" + assert audit_path.exists() and json.loads(audit_path.read_text())["passed"] + if spec["job_type"] == "reader": + endpoints.append( + dict( + name=spec["name"], + world=spec["world"], + phase=spec["phase"], + memory=spec["memory_arm"], + training=spec["training_arm"], + metrics=result["endpoint"]["metrics"], + inner_success=float(np.mean([e["inner_success"] for e in result["episodes"]])), + training_seconds=result["training_seconds"], + ) + ) + elif spec["job_type"] == "editing": + for branch in result["branches"]: + task = f"D_{branch['role']}_{branch['stratum']}" + d = branch["metrics"][task] + edits.append( + dict( + parent=spec["parent_name"], + world=spec["world"], + phase=spec["phase"], + memory=spec["memory_arm"], + training=spec["training_arm"], + role=branch["role"], + stratum=branch["stratum"], + arm=branch["arm"], + case=branch["case_id"], + E=branch["metrics"]["E_new"]["accuracy"], + U=branch["metrics"]["U_atomic"]["accuracy"], + D=d["accuracy"], + n=d["n"], + baseline_coverage=d["parent_correct_coverage"], + parent_correct_D=d["new_following_parent_correct"], + operation_coverage=d["operation_correct_coverage"], + operation_D=d["new_following_operation_correct"], + old_answer=d["old_answer_accuracy"], + U_composition=branch["metrics"]["U_familiar"]["accuracy"], + ) + ) + grouping = defaultdict(list) + for row in endpoints: + grouping[(row["phase"], row["memory"], row["training"])].append(row) + means = [] + for (phase, memory, training), rows in grouping.items(): + means.append( + dict( + phase=phase, + memory=memory, + training=training, + worlds=len(rows), + familiar=float(np.mean([r["metrics"]["familiar_test"]["accuracy"] for r in rows])), + strict=float(np.mean([r["metrics"]["strict_test"]["accuracy"] for r in rows])), + atomic=float(np.mean([r["metrics"]["common_atomic"]["accuracy"] for r in rows])), + inner_success=float(np.mean([r["inner_success"] for r in rows])), + ) + ) + # Equal cases within each world, then equal worlds. Cases are not independent worlds. + cells = defaultdict(list) + for row in edits: + cells[ + ( + row["phase"], + row["memory"], + row["training"], + row["role"], + row["stratum"], + row["arm"], + row["world"], + ) + ].append(row) + world_cells = [] + for key, rows in cells.items(): + phase, memory, training, role, stratum, arm, world = key + values = {} + for field in [ + "E", + "U", + "D", + "baseline_coverage", + "parent_correct_D", + "operation_coverage", + "operation_D", + "old_answer", + "U_composition", + ]: + valid = [r[field] for r in rows if r[field] is not None] + values[field] = float(np.mean(valid)) if valid else None + world_cells.append( + dict( + phase=phase, + memory=memory, + training=training, + role=role, + stratum=stratum, + arm=arm, + world=world, + cases=len(rows), + **values, + ) + ) + groups = defaultdict(list) + for r in world_cells: + groups[ + tuple(r[k] for k in ["phase", "memory", "training", "role", "stratum", "arm"]) + ].append(r) + edit_means = [] + for key, rows in groups.items(): + values = {} + for field in [ + "E", + "U", + "D", + "baseline_coverage", + "parent_correct_D", + "operation_coverage", + "operation_D", + "old_answer", + "U_composition", + ]: + valid = [r[field] for r in rows if r[field] is not None] + values[field] = float(np.mean(valid)) if valid else None + edit_means.append( + dict( + zip(["phase", "memory", "training", "role", "stratum", "arm"], key, strict=True), + worlds=len(rows), + **values, + ) + ) + report = dict( + endpoints=endpoints, + editing_cases=edits, + endpoint_means=means, + editing_worlds=world_cells, + editing_means=edit_means, + missing=missing, + limitations=[ + "Synthetic template task; first-block MLP restored after each training episode; " + "remaining parameters trained", + "Not second-order meta-learning or unconstrained changing-world pretraining", + "Atomic-change control uses unaffected composition queries; " + "query exposures differ from changed-use treatment", + "Static and changed-use share query prefixes, budgets and parent; " + "changed labels add supervised counterfactual information", + "Three fresh confirmation worlds, one initialization per world", + "Finite-KL local MLP editing does not guarantee unchanged behavior", + "Conditional D and coverage always reported alongside full-pool D", + ], + ) + write_json(out / "summary.json", report) + lines = [ + "# 固定知识与知识变化训练:结果", + "", + "本批检验:在临时事实参数变化下学习组合使用,是否改善未见事实的原子编辑后传播。普通Loop与共享KV各比较fixed、changed_atomic、changed_use。", + "", + "开发世界与新世界分开;按世界等权,不把编辑案例当成独立世界。", + "", + "| 阶段 | 架构 | 训练 | 世界 | 原子 | 熟悉组合 | 严格组合 | 训练写入成功 |", + "|---|---|---|---:|---:|---:|---:|---:|", + ] + for r in means: + lines.append( + f"|{r['phase']}|{r['memory']}|{r['training']}|{r['worlds']}|{r['atomic']:.2%}|{r['familiar']:.2%}|{r['strict']:.2%}|{r['inner_success']:.2%}|" + ) + lines += [ + "", + "| 阶段 | 架构 | 训练 | 编辑角色 | 事实池 | 世界 | " + "E更新 | U原子 | D传播 | 父模型正确覆盖 | 父正确D |", + "|---|---|---|---|---|---:|---:|---:|---:|---:|---:|", + ] + for r in edit_means: + if r["arm"] != "edit": + continue + conditional = f"{r['parent_correct_D']:.2%}" if r["parent_correct_D"] is not None else "—" + lines.append( + f"|{r['phase']}|{r['memory']}|{r['training']}|{r['role']}|{r['stratum']}|{r['worlds']}|{r['E']:.2%}|{r['U']:.2%}|{r['D']:.2%}|{r['baseline_coverage']:.2%}|{conditional}|" + ) + lines += [ + "", + "全部原始案例、sham、必要事实条件和旧答案保留见summary.json。", + "", + "缺失项:" + str(missing), + "", + "解释边界:", + "", + ] + ["- " + x for x in report["limitations"]] + (out / "report.md").write_text("\n".join(lines) + "\n") + print( + json.dumps(dict(endpoints=len(endpoints), edit_branches=len(edits), missing=len(missing))) + ) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/knowledge-change-v1/source/scripts/run_knowledge_change.py b/docs/development-artifacts/knowledge-change-v1/source/scripts/run_knowledge_change.py new file mode 100644 index 0000000000000000000000000000000000000000..71d2eee028811d5ff0701a41f1fda54b8fd0351c --- /dev/null +++ b/docs/development-artifacts/knowledge-change-v1/source/scripts/run_knowledge_change.py @@ -0,0 +1,795 @@ +"""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 = "knowledge-change-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 freeze(): + from llm_memory_editability.interface_editing import _hash_json + from llm_memory_editability.knowledge_change import TRAINING_ARMS, panel + 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) + historical = read( + REPOSITORY / "docs/development-artifacts/shared-cache-branch-v1/frozen-config.json" + ) + base = next( + s + for s in historical["specs"] + if s["world"] == 730011 and s["memory_arm"] == "local" and s["repeats"] == 4 + ) + specs, editing = [], [] + for world in [730011, 107270011, 107270012, 107270013]: + phase = "development" if world == 730011 else "confirmation" + for memory in ["local", "shared_full"]: + s = dict( + base, + world=world, + phase=phase, + memory_arm=memory, + initialization=base["initialization"] if phase == "development" else 107270021, + stream_seed=base["stream_seed"] if phase == "development" else 107270031, + name=f"base-w{world}-{memory}", + job_type="base", + nodes=[0, 32000, 64000, 96000, 128000], + checkpoint_nodes=[0, 128000], + repeat_nodes=[], + test_repeats=[], + ) + s.pop("matched_compute_step", None) + s["initial_model_sha256"] = model_digest(construct(s, "cpu")) + s["data_sha256"] = data_digest(build_world(s)) + if phase == "development": + old = REPOSITORY / "results/shared-cache-branch-v1/runs" / f"w730011-{memory}-r4" + s["reuse_dir"] = str(old) + s["reuse_checkpoint_sha256"] = sha(old / "model-128000.pt") + specs.append(s) + selected_panel = panel(s) + for training in TRAINING_ARMS: + name = f"w{world}-{memory}-{training}" + spec = dict( + s, + name=name, + job_type="reader", + training_arm=training, + parent_name=s["name"], + parent_dir=str(RESULTS / "runs" / s["name"]), + episodes=32, + inner_steps=512, + reader_steps=512, + inner_lr=1e-4, + reader_lr=1e-4, + batch_size=192, + panel_sha256=_hash_json(selected_panel), + ) + specs.append(spec) + editing.append( + dict( + name="edit-" + name, + job_type="editing", + phase=phase, + world=world, + memory_arm=memory, + training_arm=training, + parent_name=name, + parent_dir=str(RESULTS / "runs" / name), + candidate_seed=107270041, + per_cell=16, + replay_n=32, + case_ids=[c["case_id"] for c in selected_panel["test"]], + cases=selected_panel["test"], + case_sha256=_hash_json(selected_panel["test"]), + nodes=[0, 128, 512], + lr=1e-4, + replay_weight=1.0, + parameter_scope="mlp", + block_index=0, + ) + ) + paths = [ + *REPOSITORY.glob("src/llm_memory_editability/*.py"), + REPOSITORY / "scripts/run_knowledge_change.py", + REPOSITORY / "scripts/report_knowledge_change.py", + REPOSITORY / "tests/test_knowledge_change.py", + 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=historical["runtime"], + maximum_run_seconds=5400, + maximum_edit_seconds=3600, + maximum_engineering_seconds=600, + maximum_gpu_hours=25, + development_gate=dict(atomic=0.95, train_composite=0.90, inner_success=0.90), + development_selection=( + "No selection on propagation or familiar/strict accuracy; " + "failed prerequisites stop confirmation" + ), + independent_confirmation_worlds=3, + ) + write_json(ARTIFACT / "frozen-config.json", config) + write_json( + ARTIFACT / "execution-lock.json", {"config_sha256": sha(ARTIFACT / "frozen-config.json")} + ) + print( + json.dumps( + dict(specs=len(specs), edits=len(editing), 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"] == "reader": + from llm_memory_editability import knowledge_change as kc + + if audit_only: + kc.audit(out) + else: + kc.train(spec, out, config["source"], engineering) + return + 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 + assert read(Path(spec["parent_dir"]) / "audit.json")["passed"] + if audit_only: + editor.audit(out) + else: + editor.run(spec, out) + assert read(out / "run.json")["case_sha256"] == spec["case_sha256"] + return + from llm_memory_editability.shared_cache import install_training_adapter + + latent = install_training_adapter(spec) + if audit_only: + latent.audit(out) + return + if "reuse_dir" in spec and not engineering: + original = Path(spec["reuse_dir"]) + assert read(original / "audit.json")["passed"] + assert sha(original / "model-128000.pt") == spec["reuse_checkpoint_sha256"] + for path in original.iterdir(): + if path.is_file() and path.name not in { + "audit.json", + "run.json", + "container-command.json", + "container-runtime.json", + "worker.log", + "worker-completion.json", + }: + shutil.copy2(path, out / path.name) + write_json( + out / "run.json", + dict( + spec=spec, + initial_model_sha256=spec["initial_model_sha256"], + reused_parent=str(original), + pid=os.getpid(), + gpu=int(os.environ.get("PHYSICAL_GPU", 0)), + ), + ) + return + if engineering: + spec = dict( + spec, steps=8, nodes=[0, 8], checkpoint_nodes=[0, 8], repeat_nodes=[], test_repeats=[] + ) + write_json( + out / "run.json", + dict( + spec=spec, + initial_model_sha256=spec["initial_model_sha256"], + pid=os.getpid(), + gpu=int(os.environ.get("PHYSICAL_GPU", 0)), + ), + ) + latent.train(spec, out, config["source"]) + + +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_knowledge_change.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), + ) + if engineering: + from llm_memory_editability import knowledge_change as kc + + job = next( + s + for s in config["specs"] + if s["job_type"] == "reader" + and s["phase"] == "development" + and s["memory_arm"] == "shared_full" + ) + job = dict( + job, + parent_dir=str( + REPOSITORY / "results/shared-cache-branch-v1/runs/w730011-shared_full-r4" + ), + ) + kc.train(job, out / "episodic-smoke", config["source"], engineering=True) + kc.audit(out / "episodic-smoke") + 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_knowledge_change.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_full" + and s["job_type"] == "base" + and s["phase"] == "development" + ), + 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" + development_passed = False + development_decided = False + active_started = {} + used_gpu_seconds = 0.0 + 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())) + used_gpu_seconds += time.monotonic() - active_started.pop(gpu) + del active[gpu] + total_gpu_seconds = used_gpu_seconds + sum( + time.monotonic() - started for started in active_started.values() + ) + state["allocated_gpu_hours"] = total_gpu_seconds / 3600 + if total_gpu_seconds > config["maximum_gpu_hours"] * 3600: + for _gpu, (p, log, out, cname, spec) in list(active.items()): + subprocess.run( + ["docker", "--context", "lm-memory", "stop", "-t", "10", cname], + check=False, + ) + p.wait(timeout=30) + log.close() + write_json(out / "failure.json", dict(reason="batch GPU budget exhausted")) + state["failed"].append(spec["name"]) + write_json(RESULTS / "budget-stop.json", dict(skipped=[s["name"] for s in pending])) + active, pending = {}, [] + break + if ( + not development_decided + and not any(s["phase"] == "development" for s in pending) + and not any(v[4]["phase"] == "development" for v in active.values()) + ): + development_decided = True + dev = [ + s + for s in config["specs"] + if s["job_type"] == "reader" and s["phase"] == "development" + ] + checks = [] + for s in dev: + path = RESULTS / "runs" / s["name"] / "complete.json" + if not path.exists(): + checks.append(dict(name=s["name"], passed=False, reason="missing")) + continue + r = read(path) + m = r["endpoint"]["metrics"] + success = sum(x["inner_success"] for x in r["episodes"]) / len(r["episodes"]) + passed = ( + m["common_atomic"]["accuracy"] >= 0.95 + and m["anchor_atomic"]["accuracy"] >= 0.95 + and m["train_composite"]["accuracy"] >= 0.90 + and success >= 0.90 + ) + checks.append( + dict( + name=s["name"], + passed=passed, + atomic=m["common_atomic"]["accuracy"], + train=m["train_composite"]["accuracy"], + inner_success=success, + ) + ) + development_passed = ( + all(c["passed"] for c in checks) and len(checks) == 6 and not state["failed"] + ) + write_json( + RESULTS / "development-gate.json", + dict( + passed=development_passed, + checks=checks, + selection="prerequisites only; no D or test accuracy selection", + ), + ) + if not development_passed: + write_json( + RESULTS / "confirmation-not-started.json", + dict( + reason="development prerequisites not met", + planned_jobs=[s["name"] for s in pending], + ), + ) + pending = [] + 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["phase"] == "development" or development_passed) + and (s["job_type"] == "base" or s["parent_name"] in state["completed"]) + ), + None, + ) + if eligible is not None: + pending.remove(eligible) + active[gpu] = (*container(config, gpu, eligible), eligible) + active_started[gpu] = time.monotonic() + 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_knowledge_change.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" + if development_passed + else "development_prerequisite_not_met", + 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_knowledge_change.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/knowledge-change-v1/source/src/llm_memory_editability/__init__.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c606cfd654948ec99bedce5244b7c6608a801a1d --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/__main__.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..860f4f8babf02fc2d6920b26bf4ac11a3e254766 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/alignment_coverage.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/alignment_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..6efacd7bf323dd87ad027292dee80a9f665032fa --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/architecture_bridge.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/architecture_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..3d611f12f7be01721c8f453b8981605455e4b585 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/architecture_bridge_toy.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/architecture_bridge_toy.py new file mode 100644 index 0000000000000000000000000000000000000000..a406337c9f1b455c1c07183ec90de18541f7d03b --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_analysis.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae07fb7fccdec9430d5e69bc1b304a9fcebe914 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_branch.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c6ebef8f0f501ac43d2d94de8f4f59b954208b --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_capacity.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_capacity.py new file mode 100644 index 0000000000000000000000000000000000000000..d07d84eb1c19bc5055e15255b0de00799b8713c5 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_causal_paths.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_causal_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2d8963ce2c5db80362fdd38cc80e83c8415b53 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_confirmation_stats.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_confirmation_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..27d0d82cc96b250b88771946b569218a090bee50 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_context_control.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_context_control.py new file mode 100644 index 0000000000000000000000000000000000000000..26c20f349951ff08ba251e2e61c158ad8f4c0f85 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_context_gradient.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_context_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..89f78f244a71569026fd75d76ac6b10b702fed9d --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_cross.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..960ef7e03dd29b834df68149d8aca7cbcd077a10 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_cross_continue.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_cross_continue.py new file mode 100644 index 0000000000000000000000000000000000000000..df0a21278c640164306e05b7465e24cc0e6d0df8 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_cross_scale.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_cross_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..af5c92edca554475a9bdf9dee9b46438455b1f96 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_cross_train.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_cross_train.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5f3f45a169e643c408f1044eaa766b79a595fd --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_data.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3acf9b51a11985eb747a2c2565bc551ae803fd9b --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_direction.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_direction.py new file mode 100644 index 0000000000000000000000000000000000000000..15e8d1db07bd56a73048608a8d9dfb99e5737a7a --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_direction_cross.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_direction_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..27051c00db64d66676d95dc16a1351dff5d797a6 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_direction_formation.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_direction_formation.py new file mode 100644 index 0000000000000000000000000000000000000000..96a3aa141c344b0fea47995c861792eb5d95398a --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_direction_refresh.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_direction_refresh.py new file mode 100644 index 0000000000000000000000000000000000000000..5f48462e2c66886ef8e483fa7e48986d075ad3fb --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_edit.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..685a33d6157d090f0afdfaa38b5c2d731eda4d0e --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_followup.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..c90b76331ad0bbd37276b4a9fe14b865360e7a60 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_measure.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_measure.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf7c45f10b2be179635d21d0f3a7fde2ee6ca6c --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_mechanism_causal.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_mechanism_causal.py new file mode 100644 index 0000000000000000000000000000000000000000..8ac824d1ef628725bf1ee9ca778d381516508a80 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..322ecd4a965475d9878cbb14cb7a3eee131cf9ca --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_mechanism_edit.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_mechanism_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..6e51c693528d73250f62b70686f96b42b7eb9e4f --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py new file mode 100644 index 0000000000000000000000000000000000000000..4d87971e01bb7f679239d58f88ea4ac1b054eb88 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_model.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7190d562883dec0d900e7ac14e894975f76499fb --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_organization.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_organization.py new file mode 100644 index 0000000000000000000000000000000000000000..a64a674326bdc2e7202a987e0ac941b40640d912 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_organization_train.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_organization_train.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5d2bba261629aecc04944afd599bb827c634a8 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_original_data.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_original_data.py new file mode 100644 index 0000000000000000000000000000000000000000..98352c46d29112ab2ac2be7212204897c13aea18 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_original_diagnostics.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_original_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..dc0de9f1aeb4e6e8a48ea33b265811985ebea4d8 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_original_model.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_original_model.py new file mode 100644 index 0000000000000000000000000000000000000000..039ceaef72cf7fefa38bb094dbefbe9f7e88d651 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_original_report.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_original_report.py new file mode 100644 index 0000000000000000000000000000000000000000..8aace2494390c65045a2d379beb42695d3b84c8e --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_original_train.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_original_train.py new file mode 100644 index 0000000000000000000000000000000000000000..eea8f0449758025224fd3bb37444cc7e54e7ef7c --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_path_diagnostics.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_path_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..219336bcde27c897b81d6c253255dca79eb11d1c --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_path_minimal.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_path_minimal.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2ed53451de1a88abe78ee5e58cb49745597c2b --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_path_transfer.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_path_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..0c54e9cfda468b9a153577dd716a037dde1577f1 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_readout_control.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_readout_control.py new file mode 100644 index 0000000000000000000000000000000000000000..877089e7e83d985cfb9e4b5e65920b2db8312d4d --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_relation_response.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_relation_response.py new file mode 100644 index 0000000000000000000000000000000000000000..2e69b15143ef5b90779481035823b06102c3b5ab --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..3943eb3bac42c3c9c13d8b3c40061fc830348860 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py new file mode 100644 index 0000000000000000000000000000000000000000..8535796aba3f18178d69d214c04bc922b0dfa21d --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_shortcut_control.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_shortcut_control.py new file mode 100644 index 0000000000000000000000000000000000000000..60ee531b9c2a08e1cf2cfba210a312300b93480d --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_shortcut_edit.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_shortcut_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..856a9a8a4fd753c498c4b965d5c30a057bdebffd --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..52dd3441331f501688eedfe95286f26462de3625 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..684e672ca551a48aacb2f4bc81db94092282f4cf --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bios_train.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bios_train.py new file mode 100644 index 0000000000000000000000000000000000000000..958bf5b4de4feec20d76d07a5d28016fec584d7a --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bridge_reencoding.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bridge_reencoding.py new file mode 100644 index 0000000000000000000000000000000000000000..1dbbe769879cff4d2b00a6c39164102b50d035e3 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/bridge_workspace.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/bridge_workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3ee68821631607b4922cfce3654cd2784d82ba --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/capacity_controls.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/capacity_controls.py new file mode 100644 index 0000000000000000000000000000000000000000..3806e6b81fda1ae9bc25fd74e38f846ddd3a456d --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/capacity_scaling.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/capacity_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c152e8710de107c8fb2f4ba2275cdea5cbdcf3 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/cli.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..1aec4627fdf91a196893b3a6d47c8188da55d55b --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/composition_curves.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/composition_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..13009dcfa856d01722da32842dcc3a7fe078a635 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/curve_tracking.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/curve_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..526a40aecb32ed282e9de766f3162546d80403ac --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/depth_step.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/depth_step.py new file mode 100644 index 0000000000000000000000000000000000000000..8f828c9ccea5c225dd4fc257587afe3c0ff7c6bf --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..fc14c085184dc030670f1eea92655b73d0eec7c8 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/depth_step_mechanism.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/depth_step_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb78cafec65ea5b0a4031d27502f7d0c4b00e16 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/experiment_tracking.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/experiment_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..167c8e1a359008fa8b7c89642273e85c9699643e --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/experiments.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/experiments.py new file mode 100644 index 0000000000000000000000000000000000000000..21513c79efc2f2e137213ca20f5444209e6d313d --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_depth.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grok_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb93ea353cb12f972942a3cf658bc6593f81bb7 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_depth_bridge.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grok_depth_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..ca05be9fcd170cee34075ae1aa2fa0c2bcca1e2c --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_depth_data.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grok_depth_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8696c3ffe204466f57619157a3f47739f899c6c4 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_loop_data.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grok_loop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..18cae2dbd6dfdd997883935619a80811eede27d0 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_loop_mechanism.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grok_loop_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd1ad614952efa432b820d8f26f1e282657a947 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_loop_model.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grok_loop_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed46483cb7277c172f8848cefb9e2d085d67c0b --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f3cac329831b303c1dc9ca05c270837de0614eec --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py b/docs/development-artifacts/knowledge-change-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/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_loop_supervision.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grok_loop_supervision.py new file mode 100644 index 0000000000000000000000000000000000000000..104364e93299229e1a8216acabb046e5fae1dde4 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_loop_train.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grok_loop_train.py new file mode 100644 index 0000000000000000000000000000000000000000..ffee809fcc7335c7b68e3321427ffcc0342c3086 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_multihop.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grok_multihop.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0824b5e038658e91c3cbc5e521a316861f20a4 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_multihop_data.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grok_multihop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d857233765485dc4bf1a210fda171628a20d9817 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_usage_data.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grok_usage_data.py new file mode 100644 index 0000000000000000000000000000000000000000..04e5650b0bdea1e25cfde235045efc9b14e0c769 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grok_usage_train.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grok_usage_train.py new file mode 100644 index 0000000000000000000000000000000000000000..8460dcf149ad8f229cc4c16783e8e7429acd0610 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..9530969731263b69c576f12989a3610ead6036f5 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/grokking_reproduction.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/grokking_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f7ba958ea469d5edea6e98c9941dcc49427a6f --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/hebbian_data.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/hebbian_data.py new file mode 100644 index 0000000000000000000000000000000000000000..b67eee718fd00d44c1de51a2821e24aa7251196b --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/hebbian_followup.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/hebbian_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..89afed17153ba18880997b4089ddadb1b997f80b --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/hebbian_future.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/hebbian_future.py new file mode 100644 index 0000000000000000000000000000000000000000..24171d0e5bc0c31f7cc4ac32af06d86dd8ec15f4 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/hebbian_interface.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/hebbian_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..0135ee958b76df5e2df2aa4ea0c2c57c40f2b24a --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/hebbian_learning.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/hebbian_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..78155602739f614f369304edc920dbb75b590bea --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/hebbian_model.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/hebbian_model.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8e5da864f18f673c829d8b68db641d728ca437 --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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/knowledge-change-v1/source/src/llm_memory_editability/hebbian_statistics.py b/docs/development-artifacts/knowledge-change-v1/source/src/llm_memory_editability/hebbian_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..52bcc965886f86bf20041ec40ce6aa95b96a725f --- /dev/null +++ b/docs/development-artifacts/knowledge-change-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