Archive experiment updates 2026-10-08 (17/119)
Browse filesFile-level snapshot; code revision eb6fa2872daec8b3cea3832ee9dfec9e63cf2176. Weights and Docker images remain local.
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+2
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/slow_documentation_tests.txtAdded+11
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/sort_auto_mappings.pyAdded+124
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/__init__.pyAdded
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_configuration.pyAdded+16
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_feature_extraction.pyAdded+5
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_image_processing.pyAdded+5
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_modeling.pyAdded+33
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_pipeline.pyAdded+33
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_processing.pyAdded+6
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_tokenization.pyAdded+5
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_tokenization_fast.pyAdded+8
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/tests_fetcher.pyAdded+1260
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/tf_ops/onnx.jsonAdded+245
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/update_metadata.pyAdded+339
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/update_tiny_models.pyAdded+200
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/utils.pyAdded+27
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/visualization.ipynbAdded+170
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/README.mdAdded+77
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/cosine_metrics.ipynbAdded+198
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/cross_query_semantic_patching.ipynbAdded+214
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/data_preparation.ipynbAdded+985
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/logit_lens.ipynbAdded+201
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/training_dynamics.ipynbAdded
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/validation.jsonAdded+76
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/contract-tests.logAdded+2
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/execution-lock.jsonAdded+3
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/frozen-config.jsonAdded+237
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/fullpool-smoke.logAdded+349
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.pdfAdded+3
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.txtAdded+1482
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.pdfAdded+3
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.txtAdded+1400
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/protocol.mdAdded+13
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/smoke-config.jsonAdded+34
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/configs/experiment-tracking-defaults.jsonAdded+11
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/configs/implicit-reasoning-paper-reproduction-v2.jsonAdded+82
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/scripts/execute_learning_use.pyAdded+364
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/scripts/run_memory_interface_next.pyAdded+397
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/__init__.pyAdded+19
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/__main__.pyAdded+5
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/alignment_coverage.pyAdded+503
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/architecture_bridge.pyAdded+549
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/architecture_bridge_toy.pyAdded+410
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_analysis.pyAdded+399
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_branch.pyAdded+127
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_capacity.pyAdded+48
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_causal_paths.pyAdded+455
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_confirmation_stats.pyAdded+280
- docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_context_control.pyAdded+250
209 unmodified lines210211212209 unmodified linesdocs/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 -textdocs/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 -textdocs/development-artifacts/implicit-reasoning-paper-reproduction-v1/paper.pdf filter=lfs diff=lfs merge=lfs -text209 unmodified lines210211212213214209 unmodified linesdocs/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 -textdocs/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 -textdocs/development-artifacts/implicit-reasoning-paper-reproduction-v1/paper.pdf filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.pdf filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.pdf filter=lfs diff=lfs merge=lfs -text
1234567891011docs/source/en/generation_strategies.mddocs/source/en/model_doc/ctrl.mddocs/source/en/model_doc/kosmos-2.mddocs/source/en/model_doc/seamless_m4t.mddocs/source/en/model_doc/seamless_m4t_v2.mddocs/source/en/task_summary.mddocs/source/en/tasks/prompting.mdsrc/transformers/models/blip_2/modeling_blip_2.pysrc/transformers/models/ctrl/modeling_ctrl.pysrc/transformers/models/fuyu/modeling_fuyu.pysrc/transformers/models/kosmos2/modeling_kosmos2.py123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124# 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:
```bashpython 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:
```bashpython utils/sort_auto_mappings.py --check_only```"""import argparseimport osimport refrom 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)12345678910111213141516from 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 = attribute12345from transformers import Wav2Vec2FeatureExtractor
class CustomFeatureExtractor(Wav2Vec2FeatureExtractor): pass12345from transformers import CLIPImageProcessor
class CustomImageProcessor(CLIPImageProcessor): pass123456789101112131415161718192021222324252627282930313233import 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): pass123456789101112131415161718192021222324252627282930313233import 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}123456from transformers import ProcessorMixin
class CustomProcessor(ProcessorMixin): feature_extractor_class = "AutoFeatureExtractor" tokenizer_class = "AutoTokenizer"12345from transformers import BertTokenizer
class CustomTokenizer(BertTokenizer): pass12345678from transformers import BertTokenizerFast
from .custom_tokenization import CustomTokenizer
class CustomTokenizerFast(BertTokenizerFast): slow_tokenizer_class = CustomTokenizer pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260# 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, andwhen 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, notjust 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 Aimports module B, then changing module B impacts module A, so the tests using module A should be run. We thus get thedependencies of each model and then recursively builds the 'reverse' map of dependencies to get all modules and testsimpacted 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
```bashpython utils/tests_fetcher.py```
Base use to fetch the tests on a the main branch (with diff from the last commit):
```bashpython utils/tests_fetcher.py --diff_with_last_commit```"""
import argparseimport collectionsimport importlib.utilimport jsonimport osimport reimport tempfilefrom contextlib import contextmanagerfrom pathlib import Pathfrom 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",]
@contextmanagerdef 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245{ "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": [] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339# 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`):
```bashpython utils/update_metadata.py --token <token> --commit_sha <commit_sha>```
Usage to check all pipelines are properly defined in the constant `PIPELINE_TAGS_AND_AUTO_MODELS` of this script, sothat new pipelines are properly added as metadata (as used in `make repo-consistency`):
```bashpython utils/update_metadata.py --check-only```"""import argparseimport collectionsimport osimport reimport tempfilefrom typing import Dict, List, Tuple
import pandas as pdfrom datasets import Datasetfrom 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.pyTRANSFORMERS_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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200# 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 uploadstiny models for all model classes (if their tiny versions are not on the Hub yet), as well as produces an updatedversion 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 argparseimport copyimport jsonimport multiprocessingimport osimport time
from create_dummy_models import COMPOSITE_MODELS, create_tiny_modelsfrom huggingface_hub import ModelFilter, hf_api
import transformersfrom transformers import AutoFeatureExtractor, AutoImageProcessor, AutoTokenizerfrom 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, )123456789101112131415161718192021222324252627import pandas as pdimport jsonimport torchimport torch.nn as nnimport 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170{ "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+8oGLForUkoFR04MABtm3bxpkzZxoM4j777LMdVBWUl5dTUlJCTEwMM2bMaLLd4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fffhsABwcHFi9ezJo1a3jnnXf4+9//TkxMDL6+vpaH4w4aNIioqCjmzJnDmTNnOHnyJAsXLmTKlCnKeqBmobqKigozYK6oqOjoUlpE6v1umzlzppl75zFYTX/5y18sbQBzRkaG5bXJZDK//PLLZm9vb7Ozs7M5LCzMfPHiRav13rx50/zss8+a3dzczDqdzhwbG2uurKxUVFuHPNWlq6urqyM5OZnExMRO8aBQqVd0FAkoIYTdkjEoIYTdkoASQtgtCSghhN2SgBJC2C0JKCGE3ZKAEkLYLQkoIYTdkoASQtgtCSghhN2SgBJC2C0JKCGE3fr/EB7I2ptQEB8AAAAASUVORK5CYII=", "text/plain": [ "<Figure size 500x400 with 2 Axes>" ] }, "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": "iVBORw0KGgoAAAANSUhEUgAAAbwAAAGXCAY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BytXrsSqVatw5syZWr/dk5Zv3rx5+PPPP3Hp0qU672PXrl34+OOPcezYsXoNUWhIn376KS5cuICEhAQ6w2sh6B4eIaTZe+655+Dm5qZ239dQ8vPz8fvvv+Ptt9+mZNeC0CVNQkizx+PxkJiYaOgwOA4ODvU6YyWGQWd4hBBCjALdwyOEEGIU6AyPEEKIUaCERwghxChQwiOEEGIUKOERQggxCpTwCCGEGAVKeIQQQowCJTxCCCFGgRIeIYQQo/D/Yp8U5LIytzkAAAAASUVORK5CYII=", "text/plain": [ "<Figure size 500x400 with 1 Axes>" ] }, "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}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677# 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.
```bashgit clone https://github.com/OSU-NLP-Group/GrokkedTransformer.gitcd 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/<your_dataset>/`. > > 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/ <path_to_GrokkedTransformer_repo>/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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "8adc6d63", "metadata": {}, "outputs": [], "source": [ "import json\n", "\n", "id_e2_to_queries = {} # {\"<e_581>\": [\"<e_1525><r_123>\", \"<e_98><r_158>\", ...],...}\n", "ood_e2_to_queries = {} # {\"<e_581>\": [\"<e_1915><r_25>\", ...], ...}\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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214{ "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 = {} # {\"<r_1>\": [\"<e_1>\", \"<e_2>\", ...], ...}\n", "id_e2_dict = {} # {\"<e_2>\": [\"<e_1><r_1>\", \"<e_3><r_3>\", ...], ...}\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/xnp5ZAAAACXBI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KERGJhkGFiIhEw6BCRESiYVAhIiLRMKgQEZFoGFSIiEg0DCpERCQaBhUiIhINgwoREYmGQYWIiETz/0IUE/oYucskAAAAAElFTkSuQmCC", "text/plain": [ "<Figure size 600x600 with 2 Axes>" ] }, "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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985{ "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\": \"<e_736><r_120>\", \n", " \"target_text\": \"<e_736><r_120><e_1544></a>\",\n", " }\n", " \"\"\"\n", " input_text = \"\".join(c)\n", " target_text = input_text + \"\".join([t, \"</a>\"])\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 = [\"<e_{}>\".format(i) for i in range(num_entities)]\n", " ind2entity, entity2ind = build_dicts(entities)\n", "\n", " relations = [\"<r_{}>\".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 \"</a>\" used as <eos>\n", "vocab = vocab + [\"<mask>\", \"<sep>\", \"<a>\", \"</a>\", \"<q>\", \"</q>\"]\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 = [\"<e_{}>\".format(i) for i in range(num_entities)]\n", " ind2entity, entity2ind = build_dicts(entities)\n", "\n", " relations = [\"<r_{}>\".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 \"</a>\" used as <eos>\n", "vocab = vocab + [\"<mask>\", \"<sep>\", \"<a>\", \"</a>\", \"<q>\", \"</q>\"]\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 = [\"<e_{}>\".format(i) for i in range(num_entities)]\n", " ind2entity, entity2ind = build_dicts(entities)\n", "\n", " relations = [\"<r_{}>\".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 \"</a>\" used as <eos>\n", "vocab = vocab + [\"<mask>\", \"<sep>\", \"<a>\", \"</a>\", \"<q>\", \"</q>\"]\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 \"</a>\" used as <eos>\n", "vocab = vocab + [\"<mask>\", \"<sep>\", \"<a>\", \"</a>\", \"<q>\", \"</q>\"]\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 = [\"<e_{}>\".format(i) for i in range(num_entities)]\n", " ind2entity, entity2ind = build_dicts(entities)\n", "\n", " relations = [\"<r_{}>\".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 \"</a>\" used as <eos>\n", "vocab = vocab + [\"<mask>\", \"<sep>\", \"<a>\", \"</a>\", \"<q>\", \"</q>\"]\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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201{ "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}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576{ "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 }}12...... [100%]6 passed in 2.40s123{ "config_sha256": "f7faf264e54f1c29457bc43a3f61102df691abbdb0fb47e01ade3c1c116e14a1"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237{ "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"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349/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.5torch version: 2.6.0+cu126transformers version: 4.37.0.dev0local gpu count: 1setting 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=['<s>', '<pad>', '</s>', '<unk>', '<mask>'], 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|> 50256lm.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.5torch version: 2.6.0+cu126transformers version: 4.37.0.dev0local gpu count: 1setting device complete. device: cudaSpecial 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=['<s>', '<pad>', '</s>', '<unk>', '<mask>'], 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.123version https://git-lfs.github.com/spec/v1oid sha256:7c2c7ae4d335e8bcf6e6b2fd5a1795eaedbd038375b025d7aeed2a7f4c8d1bb8size 587752123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing , pages 15686–15702December 6-10, 2023 ©2023 Association for Computational LinguisticsMQUAKE: Assessing Knowledge Editing inLanguage Models via Multi-Hop QuestionsZexuan Zhong†∗, Zhengxuan Wu‡∗,Christopher D. Manning‡, Christopher Potts‡ and Danqi Chen††Princeton University ‡Stanford University{zzhong,danqic}@cs.princeton.edu {wuzhengx,manning,cgpotts}@stanford.eduAbstractThe 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 updatingmodel weights. Current evaluation paradigmsare extremely limited, mainly validating therecall of edited facts, but changing one factshould cause rippling changes to the model’srelated beliefs. If we edit the UK Prime Min-ister to now be Rishi Sunak , then we shouldget a different answer to Who is married tothe British Prime Minister? In this work, wepresent a benchmark, MQUAKE (Multi-hopQuestion Answering for Knowledge Editing),comprising multi-hop questions that assesswhether edited models correctly answer ques-tions where the answer should change as anentailed consequence of edited facts. While wefind that current knowledge-editing approachescan recall edited facts accurately, they fail catas-trophically on the constructed multi-hop ques-tions. We thus propose a simple memory-basedapproach, MeLLo, which stores all edited factsexternally while prompting the language modeliteratively to generate answers that are consis-tent with the edited facts. While MQUAKE re-mains challenging, we show that MeLLo scaleswell with LLMs (up to 175B) and outperformsprevious model editors by a large margin.11 IntroductionAs large language models (LLMs) are deployedwidely, the need to keep their knowledge correctand up-to-date without massive retraining costsbecomes increasingly important (Sinitsin et al.,2020). Prior work has proposed knowledge editingmethods to incrementally inject a set of new factsinto a language model (Zhu et al., 2021; De Caoet 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?RecallEdited FactBoris Johnson Rishi SunakCarrie Johnson Carrie JohnsonModel Before EditModel After EditOurQuestionWho is currently the head of the British government?RecallRelated FactBoris Johnson Rishi SunakFigure 1: An example of our benchmark MQUAKE .Existing knowledge-editing methods often perform wellat answering paraphrased questions of the edited factbut 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 benchmarksoften focus on measuring whether the edited modelcan recall the newly injected facts and whether un-related knowledge remains unchanged post-editing.However, a vital unaddressed question is whetherthe edited model can handle questions where the an-swer should change as an entailed consequence ofedited facts. For example (see Figure 1), if we up-date the British Prime Minister from Boris Johnsonto Rishi Sunak within a model, the answer to Whois married to the British Prime Minister? shouldalso change as a consequence of this edit.Therefore, we propose MQUAKE (Multi-hopQuestion Answering for Knowledge Editing), anew benchmark for a more complete evaluationof knowledge-editing methods. Each example inMQUAKE consists of a multi-hop question (in-cluding{2, 3, 4}-hop questions) which correspondsto a chain of facts. When we edit one or a few factsin a chain, the edited model needs to propagatethe change to entailed consequences of the editedfacts. MQUAKE includes a dataset MQUAKE- CF15686based on counterfactual edits, and another datasetMQUAKE- T of temporal knowledge updates toevaluate model editors on real-world changes.We evaluate state-of-the-art knowledge-editingmethods on MQUAKE , testing from editing factsmentioned in one question to editing facts men-tioned in a large set of questions. The latter settingevaluates approaches that are designed to handlemany edits, such as MEMIT (Meng et al., 2022b).Surprisingly, existing knowledge-editing methodsoften perform well on answering questions that areparaphrases of the edited fact but fail drasticallyon questions where the answer should change asa consequence of an edited fact. For example, aGPT-J model edited by ROME (Meng et al., 2022a)can only answer 7.6% of multi-hop questions inMQUAKE- CF, even though it could answer43.4%of the questions before editing.Towards faithful knowledge editing, we proposea simple but effective method, MeLLo, that sig-nificantly outperforms existing model editors evenwith a large number of edits. Instead of updatingmodel weights, MeLLo stores edits in an explicitmemory inspired by memory-based editing meth-ods (Mitchell et al., 2022b) and prompts the lan-guage model iteratively to interact with the editedfacts. Specifically, it decomposes a multi-hop ques-tion into sub-questions successively, generates ten-tative answers, and checks whether it is consistentwith 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 suchas GPT-3 (Brown et al., 2020; Ouyang et al., 2022)unlike methods requiring weight updates. We hopethat both our benchmark and proposed methodprovide additional insights into building faithfulknowledge-editing methods.2 Problem DefinitionThis section introduces our setting and argues thata model edit is only truly successful if the editedmodel also returns new correct answers for ques-tions that change as a consequence of the edits.2.1 Querying Factual Knowledge in LLMsWe 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 languageprompt template tr(⋅) for each type of relationr as a way of querying knowledge from a lan-guage model (Petroni et al., 2019). This templatetakes 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 relationhead of government, we can form a cloze sentenceThe Prime Minister of the United Kingdom is __ .We consider an autoregressive language modelf ∶ X → Y, which takes a piece of text x∈ X as in-put and predicts y ∈ Y, the continuation ofx. Givena fact triple (s, r, o), we can query the languagemodel to recall the fact by feeding the prompttr(s)as input and matching the output f(tr(s)) withthe object o. While prior work has studied howto 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 enhancingknowledge retrieval is not our focus.2.2 Knowledge EditingThe knowledge stored in a language model canbe incorrect or become outdated over time. Onepossible solution is to edit the knowledge on thefly without retraining. A fact edit is defined as apair of fact triples that share the same subject andrelation e= ((s, r, o),(s, r, o∗)), which representsthe associated object is updated from o to o∗. Forsimplicity, we abbreviate the notation for an edit ase= (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 thatyields 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 toincorporate E. Our proposed alternative, MeLLo,is much more lightweight: it keeps f frozen andinstead uses E as an external knowledge store toguide generation (Section 5).In previous work (De Cao et al., 2021; Mitchellet al., 2022a,c; Meng et al., 2022a,b), the evaluationfocuses on assessing whether the edited model re-calls the updated knowledge and whether unrelatedknowledge remains unchanged post-editing. Toevaluate 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 equalto o∗ (or assigns o∗ a high probability). Addition-ally, they check correctness by varying tr(s) whilekeeping semantic equivalence (Meng et al., 2022b).2.3 Evaluation of Multi-hop QuestionsBy only evaluating single-hop questions, exist-ing methods were tested for recalling edited facts.15687It remains unknown whether an edited modelcan handle a question where the answer shouldchange as an entailed consequence of an editedfact. We propose to evaluate edited models withmulti-hop questions by considering a chain offacts C = ⟨(s1, r1, o1), . . . ,(sn, rn, on)⟩, wherethe object of ith fact also serves as the subjectof the next fact in the chain, i.e., oi = si+1. Wedenote R = [r1, . . . , rn] as the relation set andS = [s1, . . . , sn] as the subject set. We then use Cto construct a multi-hop question that asks aboutthe head entity s1, with the answer being the tailentity on. Similar to a single-hop question, wegenerate a question as tR(S). For example, witha 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 PrimeMinister? Once one or more facts in the chain areedited, e.g., (United Kingdom, head of government,Boris Johnson → Rishi Sunak), the language modelhas to leverage the updated knowledge to answerthe question, which we posit as a crucial indicatorof a model faithfully updating the fact.3 MQ UAKE: Multi-hop QuestionAnswering for Knowledge EditingWe 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, comprisestemporal-based knowledge updates and is intendedto assess the effectiveness of knowledge editingmethods 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 evaluationsettings, followed by evaluation metrics in the end.3.1 Data Construction of MQ UAKE- CFSampling chains of facts Our dataset is con-structed based on Wikidata (Vrande ˇci´c andKrötzsch, 2014), a knowledge base consisting offact triples associated with millions of entities. Wefirst sample chains of facts from Wikidata. We man-ually select 37 common relations and consider asubgraph that solely comprises these relations andthe top 20% of common entities based on hyperlinkcounts in Wikipedia articles. 2 We collect chainsthat contain N = 2, 3, 4 triples from the Wikidatasubgraph. We also adopt heuristics rules to ensurethat the sampled fact triples are coherent and leadto natural questions (see Appendix A.1 for details).Filtering unrecallable facts As answering multi-hop questions requires the model to leverage eachsingle-hop fact, we filter out any chain of factswhich 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 eachrelation type following prior work (Petroni et al.,2019; Meng et al., 2022a), and query the modelusing 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 aset of questions Q about the head entity s1 with thegold answer a being the tail entity oN. We leverageChatGPT (gpt-3.5-turbo) to automatically gen-erate questions given a chain of facts C, because(1) this provides us more diverse question formatsof good quality; (2) it is challenging to manuallywrite question templates for all the different types.We prompt ChatGPT to generate three questionsfor each sampled chain of facts. We include theprompt we used and examples of generated multi-hop questions in Appendix A.3.Sampling counterfactual edits So far, wehave collected ⟨Q, a,C⟩ (questions, answer, facttriples) 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. Fora triple (s, r, o), we sample a counterfactual ob-ject o∗ from all possible objects that are related torelation r. We replace (s, r, o) with (s, r, o∗) inthe chain and update other facts accordingly. Wemake sure that, after injecting counterfactual ed-its, the new chain still exists so that we are ableto find an updated answer a∗. We only keep thesampled edits if the corresponding updated answera∗ is not identical to the original one a. We use thesame filtering process as Appendix A.2 to make2We focus on common entities as LMs can recall factsabout common entities more reliably (Mallen et al., 2023).15688E (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 ofW ALL-E’s creator located?What is the location of the headquarters of the companythat employed the creator of W ALL-E?Where is the headquarters of the company that employedthe creator of W ALL-E situated?a Emeryvillea∗ BeijingC (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-hopquestions Q, the desirable answer pre- and post-editinga, 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 TotalMQUAKE- CF1 2,454 855 446 3,7552 2,425 853 467 3,7453 - 827 455 1,2824 - - 436 436All 4,879 2,535 1,804 9,218MQUAKE- T 1 (All) 1,421 445 2 1,868Table 2: Data statistics of MQUAKE.sure GPT-J can recall all unedited single-hop factsin the chains.3.2 Data Construction of MQ UAKE- TFollowing a similar procedure to buildingMQUAKE- 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 mostchanges in Wikidata come from schema changes,i.e., ( Encyclopédie, instance of , encyclopedia →written work) instead of actual fact updates. Wethen manually select 6 relations where the changesare most likely to align with real fact changes, e.g.,(United Kingdom, head of government, Boris John-son → Rishi Sunak). Similarly, we sample chains offacts and filter out unrecallable facts using GPT-J.When we generate edits given a fact chain, insteadof sampling artificial counterfactual facts, we re-quire that edits come from the diff set between thetwo versions of Wikidata. Note that different fromMQUAKE- CF, each instance in MQUAKE- T re-lates to only one edit, because all the edits are aboutposition changes (e.g., head of state) and involvingtwo in a question is not coherent. The goal of thisdataset is to evaluate how successfully edited lan-guage models can answer questions which involveauthentic updates to real-world knowledge.3.3 Dataset SummaryDataset 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 editsthat we want to inject into the language model, Qrepresents multi-hop questions we use to evaluateediting methods (we provide three multi-hop ques-tions), a and a∗ denote the correct answer beforeand after edits, and C and C∗ correspondingly repre-sent the factual triples associated with this questionbefore and after editing. A desirable knowledgeediting method will inject all the edits in E into themodel, and enable the model to internally use theedits and answer the questions.Data statistics Table 2 summarizes the statisticsof the MQUAKE- CF and MQUAKE- T datasets.The MQUAKE- CF dataset consists of more than9K N-hop questions (N ∈ {2, 3, 4}), each of whichassociates with one or more edits. 3 We regardit as a diagnostic dataset to study the ability ofedited models leveraging newly injected knowl-edge through editing methods. The MQUAKE- Tdataset 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 andk ∈ {1, 100, 500, 1868} on MQUAKE- T), and con-sider all instances in a group at the same timeand inject all the edited facts of these instancesinto the model at once. This harder setting is par-ticularly interesting for editing methods such asMEMIT, which can handle large numbers of editseffectively (Meng et al., 2022b).3Throughout the paper, our experiments on MQUAKE-CF are conducted on a randomly sampled subset of the fulldataset which includes 3000 instances (1000 instances for eachof {2,3,4}-hop questions) due to limited compute resources.15689Base Model Method Edit-wise Instance-wise Multi-hop Multi-hop (CoT)GPT-JBase – 100.0 43.4 42.1FT 44.1 24.1 1.6 ↓41.8 1.9 ↓40.2MEND 72.8 59.6 9.2 ↓34.2 11.5 ↓30.6ROME 90.8 86.7 7.6 ↓35.8 18.1 ↓24.0MEMIT 97.4 94.0 8.1 ↓35.3 12.3 ↓29.8Vicuna-7BBase – 61.0 30.0 36.6FT 20.2 7.8 0.7 ↓29.3 0.2 ↓36.4MEND 65.2 47.6 7.4 ↓22.6 8.4 ↓28.2ROME 99.8 89.6 8.4 ↓21.6 12.2 ↓24.4MEMIT 96.6 84.0 7.6 ↓22.4 9.0 ↓27.6Table 3: Performance results on MQUAKE- CF (maximally 4 edits) for different knowledge editing methodsusing 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 questionswith {1,2,3,4} edits in Appendix G.3.4 Evaluation MetricsWe use the following metrics to measure whetherthe edits are made successfully. We include de-tailed formal definitions in Appendix B.• Edit-wise success rate measures how manyfacts can be successfully recalled from theedited language model.• Instance-wise accuracy measures in howmany multi-hop instances, the model can re-call all the individual single-hop facts. This isa reference metric for multi-hop performance,as the model must encode each individual factin order to answer the multi-hop question. Wemeasure instance-wise accuracy both beforeand after editing the model.• Multi-hop accuracy measures the accuracyof the original and edited language modelson multi-hop questions. In our datasets, thereare three generated multi-hop questions foreach instance. If any of the three questions iscorrectly answered by the model, we regard itas accurate. This is the main metric that wefocus on to study models’ ability to use editedknowledge consistently.4 MQ UAKE Challenges Model Editors4.1 Experimental SetupLanguage models We use GPT-J (6B) andVicuna-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 thatexisting parameter-update methods require accessto 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 languagemodels (Ouyang et al., 2022; Brown et al., 2020).Knowledge editing approaches We evaluate thefollowing state-of-the-art knowledge editing ap-proaches on our datasets (more details can be foundin Appendix C).• Fine-tuning (FT) simply performs gradientdescent on the edits to update model parame-ters. We follow Zhu et al. (2021) and fine-tuneone layer in the model with a norm constrainton weight changes.• MEND (Mitchell et al., 2022a) trains a hyper-network to produce weight updates by trans-forming the raw fine-tuning gradients givenan edited fact.• ROME (Meng et al., 2022a) first localizesthe factual knowledge at a certain layer in theTransformer architecture, and then updates thefeedforward network in that layer to insert thenew facts.• MEMIT (Meng et al., 2022b) extends ROMEto edit a large set of facts. It updates feedfor-ward networks in a range of layers to encodeall the facts.Given an edited fact (s, r, o → o∗), we convert itto a cloze statement tr(s) and apply knowledgeediting approaches with the objective of correctlypredicting the edited object o∗ given tr(s). We15690Edit- Instance- Multi- Multi-hopMethod wise wise hop (CoT)Base – 100.0 34.3 46.8FT 19.5 19.0 0.0 ↓34.3 0.2 ↓46.6MEND 99.0 98.5 16.0 ↓18.3 38.2 ↓8.6ROME 100.0 97.7 0.3 ↓34.0 11.3 ↓35.5MEMIT 100.0 98.9 0.3 ↓34.0 4.8 ↓42.0Table 4: Performance results on MQUAKE- T for differ-ent knowledge editing methods using GPT-J as the basemodel.We consider edits associated with each instanceindependently. Base denotes the model before editing.include the templates of cloze statement tr for eachrelation 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-writtenprompt templates (for single-hop facts) or GPT-generated questions (for multi-hop fact chains). Weadapt in-context learning and prompt the modelwith demonstrations when calculating instance-wise and multi-hop accuracy, in order to encouragethe language model to recall and output knowledgein the desirable format (Brown et al., 2020).We also consider chain-of-thought prompting(Wei et al., 2022) with in-context demonstrationsto ensure the model’s reasoning ability is fully uti-lized. See Appendix D for detailed prompts thatwe used to query language models. We denote themulti-hop accuracy with chain-of-thought prompt-ing as multi-hop (CoT).4.2 Results on MQ UAKE- CFTable 3 shows the results on MQUAKE- CF whenconsidering each instance individually across dif-ferent methods with GPT-J and Vicuna-7B as theediting base models. As shown, all of the editingmethods perform better than our fine-tuning base-line. In addition, they all gain traction on edit-wiseevaluation, with MEMIT and ROME achievinghigher than 90% accuracy with GPT-J and Vicuna-7B. In other words, when injecting a small numberof edits, these techniques successfully inject the ed-its into language models and have the edited modelrecall them at inference time, which corroboratesprevious 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 entailsa worse instance-wise accuracy (e.g., 59.6% forMEND vs. 94.0% for MEND), as instance-wisecorrectness relies on recalling every fact from themodel correctly for multi-hop questions.0 500 1000 1500 2000 2500 3000Number of Edited Instances010203040Multi-hop Acc. (%)FTMENDBaseMEMITROME(a) MQ UAKE- CF0 250 500 750 1000 1250 1500 1750Number of Edited Instances010203040Multi-hop Acc. (%)FTMENDBaseMEMITROME(b) MQ UAKE- TFigure 2: Multi-hop performance (CoT) of GPT-Jbefore 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 modelsfails catastrophically at answering multi-hop ques-tions. Even with the strongest baseline approach,MEMIT, multi-hop performance changes from43.4% → 8.1% with GPT-J and 30.0% → 7.6%with Vicuna-7B. Our results lead to a surprisingconclusion 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 performancedrops significantly as well. Our findings suggestthat current knowledge-editing techniques, insteadof integrating new facts into the model as new inter-nal knowledge, are ratherhard coding them into themodel by updating weights locally. We hope theseresults can act as a call to the community to rethinkthe faithfulness of knowledge-editing methods and15691Tentative answerMulti-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 KushnerRetrieved fact David Cameron is married to Courtney LoveAnswer Jared KushnerSubquestion What is the country of citizenship of Jared Kushner?The country of citizenship of Jared Kushner is United StatesJared Kushner is a citizen of CanadaCanada…… ……Final answer Ottawa Retrieved factAnswerDavid Cameron is married to Courtney LoveEdited Fact MemoryThe capital of the US is SeattleThe CEO of Apple is Carlos Slim…Our Approach: MeLLoQuery the memory with a subquestionRetrieve an edited fact from the memory Tentative answers generated by the model Retrieved facts Edited facts stored in the memoryJared 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 theretrieved fact contradicts the generated answer and updates the prediction accordingly. The concrete prompts usedin MeLLo are shown in Appedix F.conduct deeper evaluations of edited models.One hypothesis that these edited models cannotanswer our multi-hop questions faithfully is thatour prompt is not effective enough. Recent workssuggest 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 promptwith explanations and reevaluate all methods. De-tails about our CoT prompt template can be foundin Appendix D. As shown in Table 3, CoT helpsslightly 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- TWe evaluate all methods on GPT-J with real-worldknowledge edit on MQUAKE .4 The evaluationresults are shown in Table 4. We find that inthis setting, all methods except fine-tuning achievenear-perfect performance in terms of edit-wise andinstance-wise accuracy. However, on multi-hopquestions, the performance drops significantly com-pared to the base model before editing. We findthat MEND works surprisingly well with CoT onMQUAKE- T. We hypothesize that this may bedue to MEND being particularly effective in edit-ing certain relations (e.g., head of state ). On the4We exclude Vicuna-7B on MQUAKE- T as it is trainedmore recently, and is likely to be contaminated with the newknowledge in our temporal questions.other hand, our results show that the edited modelwith CoT can substantially boost multi-hop perfor-mance. This suggests that explicit knowledge recallgreatly helps the edited models answer multi-hopquestions, while these models struggle to utilizethe edited knowledge internally.4.4 Evaluation with Edits at ScaleWe extend our evaluation and consider all the ed-its from a randomly split group of k instancesat the same time ( k ∈ {1, 100, 1000, 3000} onMQUAKE- CF and k ∈ {1, 100, 500, 1868} onMQUAKE- T). The results are shown in Fig-ure 2. We find that, on both MQUAKE- CF andMQUAKE- T, the multi-hop performance of allmethods further drops when injecting more editsinto language models at the same time.5 MeLLo: A Proposal for Editing LargeLanguage ModelsIn Section 4, our evaluation results show that ex-isting knowledge-editing methods fail catastroph-ically on multi-hop questions of MQUAKE . Inthis section, we present a simple but effective alter-native, MeLLo (Memory-based Editing for LargeLanguage Models).5.1 MethodFigure 3 illustrates how MeLLo answers multi-hopquestions. Inspired by memory-based knowledge-editing methods (Mitchell et al., 2022b), MeLLo15692keeps 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 tentativeanswers contradict any edited facts in the mem-ory. MeLLo can be applied easily to LLMs such asGPT-3 (Ouyang et al., 2022; Brown et al., 2020).Edited fact memory MeLLo stores all the editedfacts explicitly in memory. Specifically, all editedfacts are first converted into sentence statementsthrough manually-defined templates. Then, an off-the-shelf retrieval model (we use the pretrainedContriever model; Izacard et al. 2021) is used toembed all the edit statements and save them in aretrieval index. The index takes a query as inputand 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 Toanswer multi-hop questions with LLMs, we fol-low previous works and first prompt the model todecompose the multi-hop questions into multiplesimple 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., JaredKushner) to the subquestion based on the (unedited)knowledge stored in the model. Third, to assesswhether the generated answer conflicts with anynew knowledge edits, the subquestion is used as aquery to retrieve a most relevant editing statementfrom the edited facts saved in memory. Fourth,the model is prompted to self-check if the retrievedfact contradicts the generated answer. If it does, themodel adjusts the intermediate answer to this sub-question using the retrieved statement. Note that itis possible that a subquestion does not relate to anyedited fact in memory as the corresponding fact isnot edited; in this case, the model is prompted tokeep the generated answer as the retrieved edit doesnot cause a contradiction. Finally, the model eithergenerates the next subquestion of the multi-hopquestion or outputs the final answer.5.2 Evaluation ResultsWe 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 performanceof MeLLo on MQUAKE- CF and MQUAKE- T.We find that with the same base model (i.e.,GPT-J), MeLLo outperforms MEMIT and MENDsignificantly 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 MeLLoworks particularly well on strong base languagemodels which can easily follow the instructions inour prompts. Along with its simplicity and efficacy,we think MeLLo can serve as a strong knowledge-editing baseline for future research. First, it doesnot require access to white-box model weights, soit 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 inremoving or adding knowledge on the fly.We note that in order to answer multi-hop ques-tions correctly after editing, the retriever we use inMeLLo needs to retrieve all the associated editedfacts from the memory. In Appendix H, we investi-gate how retrieval accuracy affects the performanceof MeLLo when using GPT-3 as the base model.6 Related WorkKnowledge-editing methods Past work has in-vestigated different approaches in editing LLMsat scale by injecting new knowledge into staticmodel artifacts (Zhu et al., 2021; Sotoudeh andThakur, 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 locatingand modifying model weights that are responsi-ble for specific concepts (Meng et al., 2022a,b;Dai et al., 2022b), and fast adaptation through asmall auxiliary editing network (Mitchell et al.,2022a; De Cao et al., 2021). Recent work editsknowledge representations during decoding pro-cedures of LLMs (Hernandez et al., 2023). Ourproposed approach MeLLo share a similar spiritwith SERAC (Mitchell et al., 2022b) where an ex-plicit memory component is used to maintain allthe edited facts. Different from SERAC, whichtrains additional models to incorporate the memory,MeLLo directly uses the base model to self-checkwhether the model generations need be adjusted.This allows MeLLo to be easily applied to black-15693MQUAKE- CF MQUAKE- T# Edited instances 1 100 1000 3000 1 100 500 1868Base Model MethodGPT-J MEMIT 12.3 9.8 8.1 1.8 4.8 1.0 0.2 0.0GPT-J MEND 11.5 9.1 4.3 3.5 38.2 17.4 12.7 4.6GPT-J MeLLo 20.3 12.5 10.4 9.8 85.9 45.7 33.8 30.7Vicuna-7B MeLLo 20.3 11.9 11.0 10.2 84.4 56.3 52.6 51.3GPT-3 MeLLo 68.7 50.5 43.6 41.2 91.1 87.4 86.2 85.5Table 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 resultswith 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 evaluationmetrics for knowledge-editing techniques often in-volve verifying the updated answers by queryingthe edited facts or related facts (paraphrased orlogically-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; Zhuet al., 2021; Hase et al., 2023). More recent worktakes a step forward by evaluating LLMs’ abilitiesto make inferences based on injected facts (Onoeet al., 2023) (e.g., after learning iPhone is a smart-phone, the model should also know iPhone canbrowse the internet), or measuring the absence ofunintended side effects of model edits (Hoelscher-Obermaier et al., 2023). Complementary withexisting evaluation tools, MQUAKE particularlyfocuses on assessing whether edited models can an-swer multi-hop questions where the answer shouldchange as an entailed consequence, showing thatexisting approaches fail on those questions.Prompting methods for multi-hop QA Sincethe debut of effective base models such as GPT-3,prompt-based methods combined with an optionalretrieval module have become a popular approachin handling multi-step QA tasks (Press et al., 2022;Yao et al., 2023; Khattab et al., 2022). Recentwork also seeks to combine external NLI mod-ules to justify whether answers to prompt-basedqueries are able to handle reasoning-based QAquestions (Mitchell et al., 2022c). Our method issimilar but more generic since we rely on the LLMitself to perform NLI step-by-step before reachingthe final answer.7 ConclusionIn this work, we present a benchmark MQUAKEthat assesses knowledge editing methods for lan-guage models via multi-hop questions. We findthat although edited language models can effec-tively recall edited facts, they fail on multi-hopquestions that are entailed consequences of the ed-its. We propose a simple but effective alternative,MeLLo, which significantly outperforms existingknowledge editing methods. MeLLo does not re-quire any additional training and can be appliedto large LMs such as GPT-3 (Brown et al., 2020).We hope our work can facilitate future research ondeveloping faithful knowledge editing methods.LimitationsThe 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 LLMsremains less explored. Note that existing edit-ing methods are very computationally expen-sive. We leave the evaluation on other modelsas future work.• We demonstrate that MeLLo outperforms ex-isting knowledge editing methods on modelswith > 6B parameters. As MeLLo relies onlanguage models for question decompositionand self-checking, future work may study howMeLLo works with smaller models such asGPT-2 (Radford et al., 2019).• Our proposed memory-based approach,MeLLo, while being very effective on theMQUAKE benchmark, requires manually15694defined prompts to drive language modelson new tasks. Although we believe MeLLois easy to instantiate on different tasks, weacknowledge this limitation and leave theevaluation on other tasks as future work.• The multi-hop questions in MQUAKE areautomatically generated by ChatGPT, ratherthan being crafted by humans. AlthoughMQUAKE- T already involves real knowl-edge changes, we posit that the use ofhuman-authored questions could further alignMQUAKE with the realistic applications ofknowledge editing methods.AcknowledgementsWe thank Dan Friedman, Tianyu Gao, EricMitchell, Mengzhou Xia, Howard Yen, Jiayi Gengfor providing valuable feedback. This research ispartially supported by an NSF CAREER award(IIS-2239290), a Sloan Research Fellowship, andMicrosoft Azure credits through the “AccelerateFoundation Models Academic Research” Initiative.ZZ is supported by a JP Morgan Ph.D. Fellowship.CM is a CIFAR Fellow.ReferencesTom Brown, Benjamin Mann, Nick Ryder, MelanieSubbiah, Jared D Kaplan, Prafulla Dhariwal, ArvindNeelakantan, Pranav Shyam, Girish Sastry, AmandaAskell, et al. 2020. Language models are few-shotlearners. In Advances in Neural Information Process-ing Systems (NeurIPS).Wei-Lin Chiang, Zhuohan Li, Zi Lin, Ying Sheng,Zhanghao Wu, Hao Zhang, Lianmin Zheng, SiyuanZhuang, Yonghao Zhuang, Joseph E. Gonzalez, IonStoica, 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, BaobaoChang, and Furu Wei. 2022a. Knowledge neurons inpretrained transformers. In Association for Computa-tional Linguistics (ACL).Damai Dai, Li Dong, Yaru Hao, Zhifang Sui, BaobaoChang, and Furu Wei. 2022b. Knowledge neurons inpretrained transformers. In Association for Computa-tional Linguistics (ACL).Nicola De Cao, Wilker Aziz, and Ivan Titov. 2021.Editing factual knowledge in language models. InEmpirical Methods in Natural Language Processing(EMNLP).Qingxiu Dong, Damai Dai, Yifan Song, Jingjing Xu,Zhifang Sui, and Lei Li. 2022. Calibrating factualknowledge 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, andSrinivasan Iyer. 2023. Do language models havebeliefs? Methods for detecting, updating, and visu-alizing model beliefs. In European Chapter of theAssociation for Computational Linguistics (EACL) .Evan Hernandez, Belinda Z Li, and Jacob Andreas.2023. Measuring and manipulating knowledge rep-resentations in language models. arXiv preprintarXiv:2304.00740.Jason Hoelscher-Obermaier, Julia Persson, Esben Kran,Ioannis Konstas, and Fazl Barez. 2023. Detect-ing edit failures in large language models: Animproved specificity benchmark. arXiv preprintarXiv: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 unsuperviseddense information retrieval with contrastive learn-ing. Transactions on Machine Learning Research(TMLR).Zhengbao Jiang, Frank F Xu, Jun Araki, and GrahamNeubig. 2020. How can we know what languagemodels know? In Transactions of the Association ofComputational Linguistics (TACL).Omar Khattab, Keshav Santhanam, Xiang LisaLi, David Hall, Percy Liang, Christopher Potts,and Matei Zaharia. 2022. Demonstrate-search-predict: Composing retrieval and language mod-els for knowledge-intensive NLP. arXiv preprintarXiv:2212.14024.Alex Mallen, Akari Asai, Victor Zhong, Rajarshi Das,Hannaneh Hajishirzi, and Daniel Khashabi. 2023.When not to trust language models: Investigatingeffectiveness and limitations of parametric and non-parametric memories. In Association for Computa-tional Linguistics (ACL).Kevin Meng, David Bau, Alex Andonian, and YonatanBelinkov. 2022a. Locating and editing factual asso-ciations in GPT. In Advances in Neural InformationProcessing Systems (NeurIPS).Kevin Meng, Arnab Sen Sharma, Alex Andonian,Yonatan Belinkov, and David Bau. 2022b. Mass-editing memory in a transformer. In InternationalConference on Learning Representations (ICLR) .15695Eric Mitchell, Charles Lin, Antoine Bosselut, ChelseaFinn, and Christopher D Manning. 2022a. Fast modelediting at scale. In International Conference onLearning 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 languagemodels with NLI. In Empirical Methods in NaturalLanguage Processing (EMNLP).Yasumasa Onoe, Michael JQ Zhang, Shankar Padman-abhan, Greg Durrett, and Eunsol Choi. 2023. Canlms learn new entities from descriptions? Challengesin propagating injected knowledge. In Associationfor 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, JohnSchulman, 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 followinstructions with human feedback. In Advances inNeural Information Processing Systems (NeurIPS) .Fabio Petroni, Tim Rocktäschel, Patrick Lewis, An-ton Bakhtin, Yuxiang Wu, Alexander H Miller, andSebastian 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. Measuringand narrowing the compositionality gap in languagemodels. arXiv preprint arXiv:2210.03350.Alec Radford, Jeffrey Wu, Rewon Child, David Luan,Dario Amodei, Ilya Sutskever, et al. 2019. Languagemodels are unsupervised multitask learners. OpenAIblog.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 Methodsin Natural Language Processing (EMNLP) , pages4222–4235.Anton Sinitsin, Vsevolod Plokhotnyuk, Dmitry Pyrkin,Sergei Popov, and Artem Babenko. 2020. Editableneural networks. In International Conference onMachine Learning (ICML).Matthew Sotoudeh and Aditya V Thakur. 2019. Cor-recting deep neural networks with small, generalizingpatches. In Workshop on Safety and Robustness inDecision Making.Hugo Touvron, Thibaut Lavril, Gautier Izacard, XavierMartinet, 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 preprintarXiv: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, MaartenBosma, Ed Chi, Quoc Le, and Denny Zhou. 2022.Chain of thought prompting elicits reasoning in largelanguage models. In Advances in Neural InformationProcessing Systems (NeurIPS).Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, IzhakShafran, Karthik Narasimhan, and Yuan Cao. 2023.ReAct: Synergizing reasoning and acting in languagemodels. In International Conference on LearningRepresentations (ICLR).Zexuan Zhong, Dan Friedman, and Danqi Chen. 2021.Factual probing is [MASK]: Learning vs. learning torecall. In North American Chapter of the Associationfor 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 reasoningin large language models. In International Confer-ence on Learning Representations (ICLR) .Wenxuan Zhou, Sheng Zhang, Hoifung Poon, andMuhao Chen. 2023b. Context-faithful prompt-ing for large language models. arXiv preprintarXiv:2303.11315.Chen Zhu, Ankit Singh Rawat, Manzil Zaheer, SrinadhBhojanapalli, Daliang Li, Felix Yu, and Sanjiv Kumar.2021. Modifying memories in transformer models.In International Conference on Machine Learning(ICML).15696A Details of Dataset ConstructionA.1 Sampling Fact Chains from WikidataWe collect chains of facts that containN = {2, 3, 4}triples from Wikidata. We adopt heuristic rules toensure that the sampled fact triples are coherentand lead to natural questions. Specifically, we ap-ply the following constraints when sampling factchains from Wikidata. (1) The sampled chain doesnot involve a circle; (2) The sampled chain doesnot contain two triples that share the same relationtype; (3) The triples with the object being a countrycan only appear in the last two hops of the chain;(4) The sampled chain contains up to three objecttypes; (5) All triples with a person or location ob-ject are consecutive in the chain; (6) The subjectentity associated with the relation headquarterslocation (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 theseheuristic rules, we manually label the object typesfor each relation we consider. For example, therelation head of state (P35) corresponds to a personas the object.A.2 Filtering Unrecallable Facts with GPT-JWe filter out any chain of facts which contain atleast one fact that cannot be recalled by GPT-J. Foreach relation type, we manually define a questiontemplate as well as 8 demonstration examples forin-context-learning. We use in-context-learning toensure the model can capture the answer formatfrom the context. Table 6 shows an example of theprompt we use to recall facts of the relation devel-oper (P178). We include the question templates ofall relations on MQ UAKE in Appendix I.A.3 Generating Questions using ChatGPTGiven a chain of facts, we prompt ChatGPT(gpt-3.5-turbo) to automatically generate multi-hop questions. The prompt we used is shown inTable 7.In Table 8, we show some randomly selectedexamples of the questions generated by ChatGPTon MQUAKE- CF. We select 3 instances from2, 3, 4−hop questions, each of which contains threegenerated questions. As shown, ChatGPT success-fully transforms the chain of triples into grammati-cally correct questions. Although these multi-hopquestions are synthetic, they are logically consis-tent with the flow of the triple chains. We believethese generated questions are of sufficient qual-ity for assessing the efficacy of knowledge-editingmethods.B Evaluation MetricsWe evaluate the editing results based on three evalu-ation metrics: edit-wise success rate, instance-wiseaccuracy, and multi-hop accuracy. Suppose wehave edited a language model and obtain the editedmodel f∗(⋅).Edit-wise success rate measures how manyedited facts can be recalled by the edited languagemodel. Given an edit e= (s, r, o → o∗), the editingsuccess is defined as 1 [f∗(tr(s))= o∗]. We takethe averaged value of the all edits in the dataset andrefer it as the edit-wise success rate metric.Instance-wise accuracy measures how many in-stances are there where all the associated factscan be recalled by the language model (eitherthe original or edited one). Given an instanced= ⟨E, Q, a, a∗, C, C∗⟩, the instance-wise accuracybefore editing is defined as1⎡⎢⎢⎢⎢⎣⋀(s,r,o)∈C[f(tr(s))= o]⎤⎥⎥⎥⎥⎦,and the instance-wise accuracy post editing is de-fined as1⎡⎢⎢⎢⎢⎣⋀(s,r,o)∈C∗[f∗(tr(s))= o∗]⎤⎥⎥⎥⎥⎦.We report the averaged instance-wise accuracy inour evaluation.Multi-hop accuracy measures the accuracy onmulti-hop questions. We regard an instance be-ing predicted correctly if any of the multi-hopquestions are answered correctly by the languagemodel. Given an instance d = ⟨E, Q, a, a∗, C, C∗⟩,the multi-hop accuracy before editing is defined as1⎡⎢⎢⎢⎣⋁q∈Q[f(q)= a]⎤⎥⎥⎥⎦,and the multi-hop accuracy post editing is definedas1⎡⎢⎢⎢⎣⋁q∈Q[f∗(q)= a∗]⎤⎥⎥⎥⎦.We report the averaged multi-hop accuracy in ourevaluation.15697(In-context-learning examples)Q: Who is the developer of Telegram? A: Telegram FZ-LLCQ: Who is the developer of Microsoft Windows? A: MicrosoftQ: Who is the developer of PlayStation 2? A: Sony Interactive EntertainmentQ: Who is the developer of iTunes? A: Apple Inc.Q: Who is the developer of SR-71 Blackbird? A: Kelly JohnsonQ: Who is the developer of Moblin? A: Linux FoundationQ: Who is the developer of Xbox 360? A: MicrosoftQ: Who is the developer of Kinsey scale? A: Alfred Kinsey(Query during inference)Q: Who is the developer of SteamOS? A: Valve CorporationTable 6: An example of the prompt we used to recall single-hop factf with relation developer (P178) from languagemodels. We use in-context-learning with 8 demonstration examples to ensure the model can output the answer in adesirable 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’tinclude 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 threepossible questions in natural English.System:1. What continent is the country of citizenship of the author of Daredevil/Bullseye: The Targetlocated in?2. From which continent does the author of Daredevil/Bullseye: The Target’s country of citizenshipbelong?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 manuallywrite 12 demonstrations as the prompt when querying ChatGPT.C Implementation Details for KnowledgeEditing MethodsC.1 Fine-tuningOur fine-tuning baseline (FT) performs gradientdescent on the edits to update model parameters.We fine-tune layer 21 of GPT-J and layer 31 ofVicuna-7B. We follow Zhu et al. (2021) and use anorm constraint on weight changes with a coeffi-cient 5 × 10−5 in our implementation.C.2 MENDWe use the GPT-J MEND editor trained by Menget al. (2022a). For Vicuna-7B, we train our ownMEND editor model on the Wikitext generationediting dataset (Mitchell et al., 2022a) with thedifferent hyperparameters. During inference, weset the learning rate scale to be 1.0.C.3 ROMEFor GPT-J, we use the default hyperparameters ofROME and the pre-computed covariance statisticsreleased by Meng et al. (2022a). For Vicuna-7B,we run ROME to update model weights at layer9 with the default hyperparameters. We computethe covariance statistics for Vicuna-7B on Wikitextusing a sample size of 100,000.C.4 MEMITFor GPT-J, we use the default hyperparameters ofMEMIT and the pre-computed covariance statisticsreleased by Meng et al. (2022b). For Vicuana-7B,we update model weights at layers {5, 6, 7, 8, 9}with the default hyperparameters. Similarly, wecompute the covariance statistics for Vicuna-7B onWikitext using a sample size of 100,000.15698Examples of 2-hop questionsC (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 questionsC (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 Bostonreceived their education?What is the city where the headquarters of the institution where the head of government of Boston was educatedat located?Examples of 4-hop questionsC (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, wequery ChatGPT (gpt-3.5-turbo) to generate multi-hop questions with the prompt shown in Table 7.D Chain-of-thought Prompting forMulti-hop QuestionsWe use chain-of-thought (CoT) prompting (Weiet al., 2022) to maximize model performance. Ta-ble 9 shows one simplified example of our promptwith CoT.E Extended Golden Labels forMQUAKE- TOur MQUAKE- T contains limited test cases. Tobetter assess the model’s original performance onmulti-hop questions, we extend the possible goldenlabels for each multi-hop question. Specifically,we allow outdated answers given smaller language15699Question: 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. Thecapital 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 GeneralMotors.Answer: Model Generated Answer Goes HereTable 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 fromthe most current to the most outdated.Input: What is the name of the current head of the United States of America government?Output:Joe BidenDonald TrumpBarack ObamaGeorge W. BushBill ClintonGeorge H. W. BushRonald ReaganJimmy CarterGerald FordRichard NixonInput: What is the name of the current head of the New York City government?Output: Model Generated Answer Goes HereTable 10: The template of the prompt we used for extending golden labels for MQUAKE- T. The prompt containsone demonstration for better aligning model behaviors.models tend to be less calibrated. To extend thegolden labels, we use GPT-3 (text-davinci-003)to query outdated answers. See the prompt we usedin Table 10.F Prompts used in MeLLoThe prompt we used in MeLLo is shown in Ta-ble 11. We first prompt the language model to de-compose subquestions. Then the language modelgenerates a tentative question to the subquestion(marked in green text); then we use the generatedsubquestion to retrieve the most relevant edited fact(marked in light blue text) and append it to theprompt. The model self-checks if the retrieved factcontradicts the generated answer. The promptingprocedure goes iteratively until the model generatesthe final answer.G Breakdown Results on MQ UAKE- CFTable 12 and Table 13 present the breakdown re-sults on MQUAKE- CF when using GPT-J as thebase model. We find that, in all editing methods(1) the performance on 2-hop questions is muchhigher than 3-hop and 4-hop questions; (2) theperformance is worse when there are more editsasssociated with the edited instances.H Impact of Retrieval PerformanceIn MeLLo, in order to answer multi-hop questionscorrectly after editing, the retrieval model needs toretrieve all the associated edited facts (each ques-tion is associated with 1-4 edited facts) from thememory. Here we investigate how retrieval accu-racy affects the performance of MeLLo when usingGPT-3 as the base model. We compute the retrievalaccuracy (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: JaredKushnerSubquestion: 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: CanadaSubquestion: 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: OttawaFinal answer: OttawaTable 11: A step-by-step illustration of MeLLo solving one simplified example. Green parts are generated by thelanguage model, and blue parts are facts retrieved by the retriever.2-hop 3-hop 4-hop AllBase 47.5 27.1 45.3 42.1FT 3.7 1.4 0.5 1.9MEND 13.9 11.3 9.5 11.5ROME 33.8 9.1 11.4 18.1MEMIT 22.5 6.0 8.4 12.3Table 12: Breakdown multi-hop performance (CoT) onMQUAKE- CF for {2,3,4}-hop questions. We use GPT-J as the base model in this experiment# Edits = 1 2 3 4 AllBase 34.0 43.0 40.4 51.7 42.1FT 4.2 0.7 0.3 0.0 1.9MEND 16.0 11.0 7.3 4.4 11.5ROME 23.8 20.9 9.0 2.6 18.1MEMIT 20.5 9.8 5.5 2.6 12.3Table 13: Breakdown multi-hop performance (CoT) onMQUAKE- CF for questions with {1,2,3,4} edits. Weuse GPT-J as the base model in this experiment.# Instances (k =) 1 100 1000 3000Retrieval acc. 93.6 67.7 59.4 58.7MeLLo (on GPT-3) 68.7 50.5 43.6 41.2Table 14: How retrieval accuracy affects the multi-hopperformance of MeLLo on MQUAKE- CF. We considera group of k instances at the same time. Retrieval acc.:how many instances where all the associated edited factsare correctly retrieved from the memory.sociated edited facts are correctly retrieved from thememory) when applying MeLLo on MQUAKE-CF with GPT-3 by considering different numbersof edited instances at the same time. As Table 14shows, the performance of MeLLo decreases if theretrieval accuracy is lower (as a result of consider-ing more instances at the same time). Among thosequestions where all associated facts are success-fully retrieved from memory, MeLLo can answer73.1% of them correctly. This indicates that re-trieval performance can significantly impact themodel performance. When we consider more ir-relevant knowledge edits in the memory, retrievalcan be more challenging, and we expect that usingmore advanced retrieval techniques can improvethe performance.I Question/Cloze Statement Templatesused in MQ UAKETable 15 shows the question templates andthe cloze-style statement templates we use inMQUAKE. We use the question templates to querysingle-hop facts when we use GPT-J for filteringand use the cloze-style statement templates to con-vert an edited fact to a natural language statement.15701Relation Question template Cloze-style statement templateP30 Which continent is [S] located in? [S] is located in the continent ofP36 What is the capital of [S]? The capital of [S] isP35 What is the name of the current head of state in [S]? The name of the current head of state in [S] isP6 What is the name of the current head of the [S] government? The name of the current head of the [S] government isP20 Which city did [S] die in? [S] died in the city ofP26 Who is [S] married to? [S] is married toP140 Which religion is [S] affiliated with? [S] is affiliated with the religion ofP1412 What language does [S] speak? [S] speaks the language ofP19 Which city was [S] born in? [S] was born in the city ofP69 Which university was [S] educated at? The univeristy where [S] was educated isP40 Who is [S]’s child? [S]’s child isP27 What is the country of citizenship of [S]? [S] is a citizen ofP175 Who performed [S]? [S] was performed byP108 Who is the employer of [S]? [S] is employed byP112 Who founded [S]? [S] was founded byP50 Who is the author of [S]? The author of [S] isP170 Who was [S] created by? [S] was created byP407 Which language was [S] written in? [S] was written in the language ofP37 What is the official language of [S]? The official language of [S] isP740 Where was [S] founded? [S] was founded in the city ofP495 Which country was [S] created in? [S] was created in the country ofP106 What kind of work does [S] do? [S] works in the field ofP136 What type of music does [S] play? The type of music that [S] plays isP364 What is the original language of [S]? The original language of [S] isP937 Which city did [S] work in? [S] worked in the city ofP800 What is [S] famous for? [S] is famous forP641 Which sport is [S] associated with? [S] is associated with the sport ofP413 What position does [S] play? [S] plays the position ofP286 Who is the head coach of [S]? The head coach of [S] isP159 Which city is the headquarter of [S] located in? The headquarters of [S] is located in the city ofP178 Who is the developer of [S]? [S] was developed byP488 Who is the chairperson of [S]? The chairperson of [S] isP169 Who is the chief executive officer of [S]? The chief executive officer of [S] isP449 Who is the original broadcaster of [S]? The origianl broadcaster of [S] isP176 Which company is [S] produced by? The company that produced [S] isP1037 Who is the director of [S]? The director of [S] isP1308 Who is the [S]? The [S] isTable 15: Question templates and cloze-style statement templates that are used in MQUAKE . “[S]” represents aplaceholder for the subject entity of the fact. We use the question templates to query single-hop facts when we useGPT-J for filtering and use the cloze-style statement templates to convert an edited fact to a statement.15702123version https://git-lfs.github.com/spec/v1oid sha256:131344c1b52cacb5d062ffd261b455a1a1cc0d9f2b70555de429455eb23be15csize 164873812345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400Evaluating the Ripple Effects of Knowledge Editing in Language ModelsRoi 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.ilAbstractModern language models capture a large bodyof factual knowledge. However, some factscan be incorrectly induced or become obso-lete over time, resulting in factually incorrectgenerations. This has led to the developmentof various editing methods that allow updat-ing facts encoded by the model. Evaluation ofthese methods has primarily focused on testingwhether an individual fact has been success-fully injected, and if similar predictions forother subjects have not changed. Here weargue that such evaluation is limited, since in-jecting one fact (e.g., ‘ ‘ J a c kD e p pi st h es o no fJohnny Depp’’ ) introduces a ‘‘ripple effect’’in the form of additional facts that the modelneeds to update (e.g., ‘‘Jack Depp is the sib-ling of Lily-Rose Depp’’ ). To address this, wepropose novel evaluation criteria that considerthe implications of an edit on related facts.Using these criteria, we then construct R IPPLE-EDITS, a diagnostic benchmark of 5K factualedits, capturing various types of ripple effects.We evaluate prominent editing methods onRIPPLEEDITS, showing that they fail to introduceconsistent changes in the model’s knowledge.In addition, we find that a simple in-contextediting baseline obtains the best scores on ourbenchmark, suggesting a promising researchdirection for model editing. 11 IntroductionModern language models (LMs) capture a largevolume 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 onknowledge editing (KE) methods, which modifyLMs to fix their factual errors (we provide a for-mal definition in §2). Knowledge editing workhas 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 theInter 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 agiven LM, while ‘‘overriding’’ beliefs the modelmight have on e and r (e.g., that Messi plays forParis Saint-Germain).A key question with KE is how to evaluatethe success of such editing operations. The mostbasic ‘‘sanity-check’’ is that the model correctlycompletes (e,r, ?), as well as other paraphrasesof this task, with o. However, this is not enoughas an evaluation, since one needs to check thatthe model did not distort other facts. Indeed,the standard evaluation protocol (Mitchell et al.,2022; Meng et al., 2022, 2023) for KE focuses onthese two aspects of correctly completing variousparaphrases of the new fact, as well as ensuringthat other unrelated facts have not been changed.In this work, we argue that to evaluate modeledits, one should go beyond the single fact that wasedited and check that other facts that are logicallyderived from the edit were also changed accord-ingly. For example, ifz is the mother ofe, then thechildren of z are the siblings of e. Consequently,once we modify the belief of a certain model thatz → z′is the mother of e, then we should alsoensure 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 whichLionel Messiplays modifies other related facts,such as his country of residence, while other facts283Transactions of the Association for Computational Linguistics, vol. 12, pp. 283–298, 2024. https://doi.org/10.1162/tacl a 00643Action 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 ofRIPPLEEDITS, compared to existing knowledge editingbenchmarks. 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 thatare implied by a factual edit as ripple effects.To account for ripple effects in the evaluation offactual edits, we propose six concrete evaluationcriteria (see §3, Figure 2), for testing which factsother than the edit itself should be modified orretained post-editing. Our tests evaluate how wellthe model integrates the edit with the rest of itsknowledge, through queries that involve logicalreasoning, complex composition of facts with theedit as an intermediate step, subject aliasing, andspecificity across relations.Building upon these criteria, we createRIPPLEEDITS, a new benchmark for comprehensiveevaluation of KE of LMs (see §4). R IPPLEEDITSincludes 5K entries, each consisting of a factualedit, along with a set of test queries that check ifthe edit was successful in terms of its ripple effect.Moreover, R IPPLEEDITS contains meta-data foreach edit, including information about the time-stamp of the edit (i.e., recent versus old), and thepopularity of the entities (i.e., head versus tail).We use R IPPLEEDITS to evaluate three popularediting methods on five recent strong LMs (see§5). We find that, even though current KE methodsare effective in modifying a particular fact, theyoften fail to capture the ripple effects entailedby that fact, and demonstrate poor performanceon most of our evaluation criteria. Moreover,analyzing how editing performance varies acrossmodel sizes and entity frequencies, we find that(a) larger models handle ripple effects better, and(b) editing frequent entities results in more logicalreasoning errors.Last, we consider a simple in-context editingbaseline for KE that leverages the casual atten-tion mechanism rather than explicit parametricupdates. While this method achieves the best re-sults on our benchmark, outperforming currentparametric KE methods, there is still ample roomfor improvement that calls for future research.To conclude, our work makes multiple contri-butions: (a) it highlights key limitations of KEevaluation, specifically regarding ripple effectsand introduces comprehensive evaluation crite-ria to mitigate those limitations, (b) it proposesRIPPLEEDITS, a benchmark inspired by these cri-teria, (c) it evaluates current methods for KEand shows that they do not perform well on thistask, while demonstrating that in-context edit-ing is a promising direction for KE. We releaseRIPPLEEDITS and our code to facilitate future workon KE.2 Problem SettingWe consider editing of factual knowledge, wherefacts 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 modelbefore 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 givensubject e and relation r, and (b) injection of anew fact (e,r,o ∗) that is not captured by themodel. Moreover, we note that for one-to-onerelations like Date of birth , where there isa single object for a given subject, an injectionedit can be viewed as populating an empty object(e,r, ∅) → (e,r,o ∗). In contrast, for one-to-manyrelations, such as Sibling and Occupation,an injection edit augments the set of objects (e,r,284Figure 2: An illustration of our evaluation criteria, for an edit that simulates adding a sibling to the subject entityPrince, shown at the top of each graph with a bold arrow and an edit sign over the Sibling relation. Foreach 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 tobe inserted to the knowledge graph (KG) is presented with an edit sign next to the relation. We show the samenode 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 SubjectAliasing (D) we verify the edit also propagates to paraphrases of the input. In Preservation (E), we verify thatother targets of the edited subject-relation are preserved. In Relation Specificity, we verify other relations for thesubject are not modified.{o1,..,o n}) → (e,r, {o1,..,o n,o∗}). Whether anedit is viewed as a modification or injection, de-pends on whether that information was capturedin the model before the edit. Moreover, evaluat-ing if a specific fact (before or after an edit) isencoded by a model is typically done by testingif the model predicts the object for various inputqueries that represent the subject and relation (seemore details in §3.2).3 Ripple Effects of Factual EditsWe focus on evaluating the downstream effect of agiven edit, i.e., given an edit (e,r,o ) → (e,r,o ′),we expect certain facts related to the edit to changeas well. Consider, for example, the edit shown inFigure 1. Changing the team for which Messi playsmight also affect the league he plays in and hiscountry of residence. Formally, for a given model,assume a knowledge-graph K := {(ei,r i,o i)}Ni=1of N factual triplets, representing the model’sknowledge, and let δ :( e,r,o ) → (e,r,o ′) be anedit request for K.W ed e f i n et h eripple effect ofδ on K, as the set of triplets R(δ) that the modelimplicitly needs to inject, modify, or delete fromK to reflect the world state after the edit.Notably, different edits can cause ripple effectsof varying magnitudes. For example, changing thecountry of Rome from Italy to France, will entailmany follow-up changes, such as the countryin which the Colosseum is located, the languagespoken in Rome, and so forth. In contrast, updatingthe siblings of Prince (Figure 2) is both morerealistic and should result in a more local effect.We refer to the number of facts affected by asingle editδ (i.e.,|R(δ)|) as its severity. In general,editing popular entities that appeared frequentlyduring training is likely to introduce more changes,and thus, editing their properties has a higherseverity.3.1 Evaluation CriteriaWe wish to evaluate how well models capture theripple effects of factual edits. However, given thatripple effects can potentially span a large numberof implied edits, we focus on evaluating modifiedfacts that are within a 2-hop distance from the285subject or object of the edit. Concretely, for anedit δ :( e,r,o ) → (e,r,o ∗), we evaluate theripple effect R(δ), via the following evaluationcriteria (examples are shown in Figure 2):1. Logical Generalization (LG): Relations in aknowledge graph satisfy certain logical con-straints. For example, the relation Siblingis symmetric and therefore if (e, Sib-ling,o ) is true then (o, Sibling,e ) isalso 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 thatsuch logical implications about the subject e,the original object o, and the new object o∗,hold after editing. We focus and elaborateon specific constraints in §4.2. Compositionality I (CI):A s δ alters oneedge in a knowledge graph, we can checkthe composition of this edge with otheredges. Namely, we test if the model cancompose the edited fact with other factsabout the target object. Let (o,r′,z ) and(o∗,r′,z∗) be two facts of the same relationabout o and o∗, respectively. Also, denoteby 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 followingchange (e,r′′,z ) → (e,r′′,z∗). For example(Figure 2B), the professions of the siblingsof Prince can be modified once a newsibling is injected.3. Compositionality II (CII):W et e s ti ft h emodel can compose the edited fact with factsabout a different subject e′⁄= e. Formally,let (e′,r′,e ) be a fact about e′with e as itsobject, and denote byr′′= r′◦r the complexrelation expressing the composition of r′andr (see an example in criterion 2). After theedit δ, the following change is expected forthe subject e′: (e′,r′′,o ) → (e′,r′′,o∗).F o rinstance (Figure 2C), changing the siblingsof Prince also modifies the siblings ofthe founder of Paisley Park Records(i.e., r′′is a complex relation expressing‘‘siblings of the founder’’).4. Subject Aliasing (SA): We test that editinga fact about e induces the same edit to otherentities e′that are aliases of e, namely, (e′,r,o ) → (e′,r,o ∗). For instance (Figure 2D),modifying the siblings of Prince shouldalso modify the sibling of his alias, PrinceRoger Nelson .5. Preservation (PV):I f r is a one-to-manyrelation, then adding a new object shouldnot affect the other objects encoded aboute. Hence, in such cases, we expect that anyexisting triplet (e,r,o ′) for an object o′⁄= o∗would remain following the edit. For exam-ple (Figure 2E), after inserting the siblingNicholas Carminowe for Prince,t h efact that Tyka Nelson is also his siblingshould be retained.6. Relation Specificity (RS): We test that factsabout e, with relations whose objects are notinfluenced by o, are indeed not affected bythe edit. For example (Figure 2F), modifyingthe sibling of Prince should not change hisMother. Note that these facts complementthose evaluated by Logical Generalization.In §4.1, we describe how we generate factual ed-iting evaluations, based on the above criteria.3.2 Related WorkKnowledge Editing Methods Several methodshave 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 layerscan be cast as key-value memories (Geva et al.,2021) that store factual knowledge (Dai et al.,2022). Other methods learn encodings that updatethe hidden representations created during modelinference (Hernandez et al., 2023a), or augmentthe 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 greaterdetail.Separately from factual KE, recent work hasalso 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 (Zhang286et 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 MLPlayers (Yao et al., 2022).Knowledge Editing Evaluation Recently,there has been a growing interest in KE evalua-tion (Yao et al., 2023). The prominent benchmarksfor evaluating factual KE are the Zero-Shot Rela-tion Extraction (zsRE) (Levy et al., 2017; De Caoet al., 2021) and CounterFact (Meng et al., 2022).zsRE is a question-answering dataset for relation-specific queries, which includes human generatedparaphrases that are used to measure robustnessto semantically equivalent inputs. For example,for the triplet ( x, Country, y), zsRE containsqueries such as ‘‘ In which country is x? ’’. Coun-terFact offers a more challenging setting, whereedits are counterfactuals of a low probability,such as changing the City of The Louvrefrom Paris to Rome.Evaluation in zsRE and CounterFact focuseson three primary aspects of (a) efficacy: checkingthat the model generates the target object post-editing, (b) paraphrasing: testing robustness ingenerating the target for paraphrases of the input,and (c) specificity: verifying that facts not relatedto the edit are unaffected. In addition, Counter-Fact evaluates the generation quality of the editedmodel when prompted with the edit’s subject,measuring: consistency, i.e., similarity with sub-jects that share the same property as the editedobject, and fluency in terms of repetitiveness ofthe generated text. More broadly, previous workevaluated to which extent LMs have beliefs (Geninand Huber, 2022; Kassner et al., 2021; Hase et al.,2023), and Hase et al. (2023) examined if updat-ing beliefs propagates to entailed facts, extendingthe Wikidata5m dataset (Wang et al., 2021b) totest editing specificity.Recently, Onoe et al. (2023) introduce the taskof entity knowledge propagation, aiming to exam-ine the extent to which models are able to reasonabout emergent entities that did not appear in pre-training. In addition, Hoelscher-Obermaier et al.(2023) show that existing KE methods can haveunwanted side effects and suffer from low speci-ficity. A concurrent work by Zhong et al. (2023)introduces MQUAKE, a benchmark that tests theability of models to perform multi-hop reasoningafter 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 commonsenseknowledge and introduce MEMIT-CSKPROBE,a dataset for semantic generalization of common-sense edits. RIPPLEEDITS is different from MEMIT-CSKPROBE as it evaluates editing of factualknowledge rather than commonsense knowledge.4T h e R IPPLEEDITS BenchmarkIn this section, we describe a data generationpipeline (§4.1) for factual edit requests and queriesfor evaluating their ripple effects. Then, we applyour pipeline to create the R IPPLEEDITS benchmarkfor comprehensive KE evaluation (§4.2), and val-idate the quality of the data ( §4.3).4.1 Data Generation PipelineWe describe our data generation process (illus-trated in Figure 3), that creates KE evaluationexamples, each consisting of a factual edit requestand 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 theedits and test queries to a fixed set of Nrel basicrelations.2Step 1: Factual Triplet Collection The firststep of the pipeline (Figure 3A) is to collect facts,from which we will later create edit requests. Tothis end, we use WIKIDATA, a relational knowledgebase consisting of facts that are expressed astriplets (e,r,o ), where e is a subject entity, r isa relation, and o is an object. We collect tripletsof three types:• RECENT: To create ‘‘real’’ plausible edit re-quests, we collect triplets that were insertedto WIKIDATA only recently, and represent rel-atively new facts. Therefore, they can be usedto create injection edit requests for modelsthat were trained before these facts were in-troduced, to simulate cases of an out-of-datemodel that requires factual updates. We col-lect such facts by randomly sampling tripletsthat have been modified during a range of250 days after July 2022.2The full list of relations is available in our codebase,example relations are shown in Figure 4.287Figure 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, wegenerate 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 correspondingto random facts, for which we will later gen-erate modification edits (similarly to Menget al., 2022). These edits simulate factual ed-its that are meant to fix incorrect model pre-dictions (e.g., predicting that the capital ofGermany is Frankfurt). To this end, we di-vide the entities in WIKIDATA into 10 uniformbuckets, based on the number of triplets as-sociated with them. Intuitively, this can beviewed as a popularity measure. Then, wesample Nent entities from each group andrandomly choose one triplet for each entity.• POPULAR: The two previous triplet types arerandomly sampled from the entire knowledgebase, and most of them are likely to representfacts about tail entities (except perhaps for asmall subset in the top bucket). Such entitiesare often not captured by models (Mallenet al., 2023), and therefore not suitable fortesting modification edits. To address this,we sample triplets from WIKIDATA with a sub-ject that is apopular entity, namely, it appearsin one of the top-viewed pages in Wikipedia.3Importantly, these types of triplets allow con-trolling for the ripple effect severity ( §3),i.e., how models handle the ripple effects ofpopular entities versus tail entities.Step 2: Edit Generation Once we obtain factualtriplets, we turn to generate edit requests for them(Figure 3B). For R ECENT, triplets represent newfacts that are meant to be injected to the model,assuming that the latter was trained before thesefacts were introduced to the world. Hence, for3We extracted the entities whose correspondingWikipedia page was included in the top-1000 most viewedpages in at least one month during 2020-2022.RECENT, the target triplet for injection is the tripletitself.For R ANDOM and P OPULAR triplets, we createan 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 therelation r, and extracting their objects Or = {o1,...,o Ncand}. Then, for every triplet (e,r,o ) inRANDOM and P OPULAR, we sample a target ob-ject o′⁄= o from Or. Sampling the target objectfrom triplets with the same relation makes the editrequest technically consistent with the originaltriplet – the target object is of the same ‘‘type’’ asthe original object (for example, a triplet with therelation Capital will get a new object of typeCity). The new triplet (e,r,o ′) will thus resultin a ‘‘fake’’ fact, since it attaches a wrong objecto′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 nextstep 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 queriesfor each criterion. Each test query correspondsto a triplet of subject and object entities and apossibly complex relation, that is expected to betrue post-editing. In what follows, we provide de-tails on our implementation, using objects fromWIKIDATA.For an entity e, we denote by S(e) the set oftriplets in WIKIDATA in which e is the subject, andby T (e) the set of triplets in which e is the ob-ject. Moreover, for every relation r, we manuallydefine a set Dr of relations that semantically de-pend on it. Namely, for a given subject, changing288r’s target object is expected to change the targetobjects for the relations Dr. For instance, the setDr for the relation r = Mother, includes therelations Sibling, Sister, Brother, Aunt,and Uncle, among others. Then, for every rela-tion r′∈ Dr, we craft a logical rule for obtainingthe new target for that relation post-editing. Forinstance, for the relation r = Sibling,w es e talogical 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 Drto generate test queries for Logical Generaliza-tion and Relation Specificity.F o r Logical Gener-alization, we apply the rule corresponding to eachrelation r′∈ Dr to obtain a set of test queries(x,r′,z′) about x ∈{ e,o,o ∗}, where z′is thetarget obtained from the logical rule. For RelationSpecificity, we create a test query for every tripletin S(e) with a relation that is not in Dr (but is inour set of Nrel relations).To generate text queries for CompositionalityI, 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 throughT (e) and for each triplet (z,r′,e ) ∈T (e),w econstruct a two-hop query (z,r′◦ r,o∗) about zwith o∗ as the answer. For Subject Aliasing ,w euse information maintained by W IKIDATA to cre-ate a test query (e′,r,o ∗) for every alias e′ofe. 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 thispoint (Figure 3D), we have factual edit requestsand their corresponding test queries. To use themas inputs to LMs, we convert them from triplet-form to natural language (NL). To this end, wemanually 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 withthis relation. For instance, the template ‘‘Thedate of birth of < e> is’’ converts trip-lets with the relation r = Date of Birth anda subject entity e.For the Preservation triplets generated for anedit (e,r, {o1,...,o n}) → (e,r, {o1,...,o n,o∗}),whereo∗ is a new object added to a set of possiblymultiple (n ≥ 0) objects, we form a single NLRECENT 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.8Subject triplets count 31.7 13.3 115.2Subject page back-links 278.1 121.6 3934.5Subject page views 189.6 67.91 7376.5Object triplets count 192.4 46.4 39.5Object page back-links 18634.2 3065.0 2136.0Object page views 2852.4 1379.7 1176.7Table 1: Statistics per subset of RIPPLEEDITS, show-ing the average of different metrics. Breakdown byevaluation criteria shows the number of queries ofeach criterion per edit. For a given subject/objectentity, triplets count is the number of W IKIDATAfacts it is associated with, page back-links is thenumber of Wikipedia pages with a link to the en-tity’s page, and page views is the recent averagedaily view count of the entity’s page.query about other objects than the edited one, e.g.,‘‘The award received by < e> whichis not < o∗> is’’ .4.2 Data StatisticsWe used our data generation pipeline to collectedits for 2,000 R ECENT facts, 1,000 R ANDOM facts,and 1,000 P OPULAR facts, focusing on Nrel =5 4basic relations for which we manually crafted NLtemplates and logical rules. 4 To obtain the R AN-DOM subset, we set Nent = 200 to sample 200facts from each entity group in W IKIDATA.F o redit generation of R ANDOM and P OPULAR,w es e tNcand = 100, 000. We call our diagnostic bench-mark RIPPLEEDITS, and publicly release it to the re-search community. Notably, R IPPLEEDITS focuseson ripple edits and is meant to complement exist-ing benchmarks, and so it does not include pre-vious evaluations, such as subject specificity andmodel consistency.Statistics on R IPPLEEDITS are presented inTable 1, showing that our generation process re-sulted in 18-26 test queries per edit and over 3queries per evaluation test, on average. Moreover,4We release the templates and rules in our codebase.289Figure 4: Most frequent relations and their frequency, in each subset of R IPPLEEDITS.POPULAR edits contain more popular subjects (asintended), while R ECENT edits have more popu-lar objects. Figure 4 shows the top relations andtheir frequency in each subset of R IPPLEEDITS,demonstrating the diversity of the generated facts.4.3 Data QualityWe conducted a manual analysis to validate thatour generation pipeline produces valid test queries.Concretely, we sampled 200 random test queriesfrom R IPPLEEDITS and checked the following tworequirements: (a) soundness: the triplet that repre-sents a given test query should be semanticallycorrect, namely, the entity type of the objectshould match the relation type and the relationtype should match the entity type of the sub-ject. For example, queries such as ‘‘The capitalof Hilary Clinton is’’ or ‘‘The sibling of LebronJames is Los Angeles’’ would have been disquali-fied. (b) grammatically correct: we check that thephrasing of the test query in natural language isgrammatical.We found that 100% of the queries were sound(i.e., semantically clear and correct), showing thatthe data curating process was designed properly.Furthermore, 98.5% of the queries were gram-matically correct, while the ones which were notcontain entity representations in a non-English lan-guage. This shows that our templates are generalenough to properly fit various entity names.5 ExperimentsWe use R IPPLEEDITS to evaluate recent KE meth-ods, and show that despite substantial progresson existing benchmarks, current methods struggleto introduce consistent changes to the model’sknowledge 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 forfuture research.5.1 Evaluation SettingData To evaluate how well an editing methodhandles the ripple effects resulting from editing agiven model, the data first needs to be adjustedsuch that (a) only cases of successful edits areevaluated, and (b) only test queries that the modelanswered correctly pre-editing are used for evalu-ation. Concretely, for an editing method F and amodel 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 forthe test queries before applying the edit, and (b)M successfully generates o′when queried aboute and r, namely, the edit has successfully beenapplied. For example, we verify that the modelcan predict the children of o′before asking aboute’s new siblings.Editing Methods We evaluate three KE meth-ods: MEND (Mitchell et al., 2022), ROME (Menget al., 2022), and MEMIT (Meng et al., 2023).MEND trains a network that modifies gradientsto produce local edits. ROME makes rank-oneupdates to the weights of the Transformer’s MLPlayers to modify specific factual associations, and290Figure 5: An example modification edit from ourICE baseline. The color code of the KG is similarto 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’sparameters.MEMIT is an extension of ROME that is adjustedto editing many facts at once.Baseline Motivated by the recent success ofLMs to learn in-context and follow instructions(Brown et al., 2020; Ouyang et al., 2022; Liu et al.,2023), specifically for knowledge editing (Zhonget al., 2023; Zheng et al., 2023), we experimentwith an in-context editing (ICE) baseline for fac-tual editing. Unlike the above methods, it doesnot introduce changes to the model parameters,but rather generation is conditioned on the newfact. Concretely, given an edit(e,r,o ) → (e,r,o ∗)and a test query q, we use the following promptto obtain an answer from the model: ‘‘Imag-ine that < o∗> would have been < Pr>’’,where Pr is a manually-written proposition ofr, such as ‘‘The mother of < e>’’ when r =Mother and e is the subject. An example isdepicted in Figure 5.Models We use 4 recent auto-regressivedecoder-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, LLaMAwith 7B parameters, (Touvron et al., 2023), andGPT-NeoX with 20B parameters (Black et al.,2022). In addition, as our baseline does notrequire access to the model parameters, we alsoevaluate it on the closed-source model GPT-3RECENT RANDOM POPULAREdits Tests Edits Tests Edits TestsGPT-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 ourevaluation (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 forGPT-3. (b) Portion of queries, on average, thatwere used in our evaluation.text-davinci-003 with 175B parameters(Brown et al., 2020). However, for the baselinewe do not include results for GPT-2 and GPT-J asthe number of testable edits for these models israther small (≤ 20% for each of the data subsets).For all model-method combinations, except forROME with LL AMA, we use the official imple-mentation and hyperparameters from Meng et al.(2022). We adjust ROME to LLAMA by followingthe authors’ method and codebase. Table 2 showsthe number of edits and test queries left, for everymodel, after filtering out non-successful edits andinapplicable 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 theaverage accuracy over the test queries per exam-ple, and then average over all the examples. For agiven test query, we let the model generate a max-imum of 20 tokens. A generation is consideredsuccessful if one of the aliases of the target ob-ject appears in the text. In cases of multiple goldtarget objects (as in Preservation), we evaluateeach target object separately and consider the gen-eration as correct if it matches at least one object.5.2 ResultsTables 3, 4, 5 show the evaluation results on theRECENT,R ANDOM, and P OPULAR subsets, respec-tively. Considering the average scores across allsubsets, we observe that existing editing meth-ods struggle to handle the ripple effect inducedby editing facts, with low average accuracy of38–66 across all models. This suggests that, while291LG CI CII SA PV RS Avg.GPT-2ROME 20.2 35.6 46.8 86.8 100 55.4 57.5MEMIT 21.8 30.3 46.2 92.9 100 56.8 58.0MEND 28.9 23.7 20.7 87.1 100 51.9 52.1GPT-J ROME 15.2 29.5 50.5 90.3 99.4 60.0 57.5MEMIT 18.0 35.0 48.1 88.4 98.6 42.2 55.0GPT-NEOROME 27.2 54.3 69.4 98.9 98.4 80.3 71.4ICE 48.3 29.0 62.2 100 99.4 80.7 69.9LLAMA ROME 16.7 47.8 50.0 93.6 97.6 59.3 60.8ICE 59.6 74.8 85.0 100 99.5 77.9 82.8GPT-3 ICE 33.3 100 91.3 100 100 73.1 82.8Table 3: Accuracy on the R ECENT subset, byMEND, 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-2ROME 53.6 31.6 44.4 94.9 9.9 38.9 45.5MEMIT 58.4 30.5 49.8 100 20.0 36.2 49.1MEND 62.5 16.7 14.6 91.3 17.7 30.1 38.8GPT-J ROME 53.8 40.8 49.9 93.8 15.2 39.4 48.8MEMIT 53.0 35.7 48.2 95.6 18.2 39.9 48.4GPT-NEOROME 61.6 49.4 57.1 100 30.8 50.7 58.3ICE 78.6 90.0 55.6 100 100 61.9 81.0LLAMA ROME 54.3 35.5 49.5 96.0 17.8 38.9 48.7ICE 71.1 73.8 80.3 100 100 69.6 82.5GPT-3 ICE 69.0 83.3 89.7 100 100 100 90.3Table 4: Accuracy on the R ANDOM subset, byMEND, 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, thesechanges are mostly applied at a surface-level with-out propagating to other related facts. Moreover,we observe that our ICE baseline obtains the bestoverall results. Specifically, it outperforms ROMEby more than 10 points for GPT-NEO and 29 pointsfor LLAMA, on average across subsets. AlthoughGPT-3 with ICE performs best on average, the 7BLLAMA is highly competitive, performing betteror similarly on the R ECENT and POPULAR subsets.Next, comparing results across evaluation cri-teria shows that some ripple effects are handledbetter than others. For example, while SubjectAliasing accuracy is consistently high ( ≥ 86.8across all settings), the accuracy on other crite-ria is generally lower and varies greatly betweenmodels, methods, and edits (e.g., Logical Gener-alization accuracy for ROME on GPT-J is 53.8 onLG CI CII SA PV RS Avg.GPT-2ROME 5.7 46.4 21.8 100 100 18.5 48.7MEMIT 6.7 45.2 21.2 100 100 24.3 49.6MEND 25.9 10.7 5.4 100 100 21.2 43.9GPT-J ROME 5.5 44.1 21.0 98.6 99.0 22.3 48.4MEMIT 7.0 45.9 23.7 100 100 24.8 50.2GPT-NEOROME 36.4 29.4 41.6 100 100 50.8 59.7ICE 37.5 92.4 40.1 100 100 74.4 74.1LLAMA ROME 22.0 37.4 16.2 100 100 20.6 49.4ICE 57.2 85.1 67.6 100 100 78.0 81.3GPT-3 ICE 31.0 86.1 65.6 100 100 83.8 77.7Table 5: Accuracy on the P OPULAR subset, byMEND, ROME, MEMIT, and the ICE baseline,on GPT-2, GPT-J, GPT-NEO,L LAMA, and GPT-3.Figure 6: Accuracy averaged over evaluation criteriaof 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 thePOPULAR subset).Results Across Model Size We analyze howediting performance on R IPPLEEDITS is influencedby the model size. To this end, we further evalu-ate ROME on smaller versions of GPT-2 – with345M (GPT2-M) and 762M (GPT2-L) parame-ters, and plot the average accuracy over the threesubsets as a function of model size. Figure 6presents the results, showing that editing perfor-mance increases with model size, with ROMEobtaining substantially higher accuracy when ap-plied to larger models. Nevertheless, our results(Tables 3, 4, 5) show that when using ICE, the7B LL AMA is competitive with the much largerGPT-3, suggesting that simply scaling the modelsize may not be sufficient to fix the drawbacks ofcurrent editing methods.292MEND ROME MEMITRelation Specificity 34.4 37.6 39.1Logical Generalization 39.1 26.5 29.0Compositionality I 17.0 37.9 35.3Compositionality II 13.6 37.7 39.1Table 6: Accuracy of MEND, ROME, andMEMIT, using GPT-2, averaged over the threeRIPPLEEDITS splits - RECENT,R ANDOM and POPULAR.Figure 7: The average accuracy of GPT-2 on differentevaluation criteria in RIPPLEEDITS. Results are averagedover 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-2across our evaluation criteria, averaged over thethree subsets. Interestingly, MEND outperformsROME and MEMIT in Logical Generalization ,but is worse in Compositionality I and Compo-sitionality II , suggesting that different methodsmight better capture different types of rippleeffects.Results Across Data Splits The subsets ofRIPPLEEDITS differ in whether edited facts are coun-terfeit or real, and in the popularity of the editedentities. These differences allow us to control forthe edit severity, as popular entities are expected tointroduce larger ripple effects (see§3). In Figure 7,we show the accuracy on each subset and evalua-tion criterion, averaged over the different editingmethods. Comparing R ANDOM and P OPULAR, thatdiffer in the popularity of the edited entities, wesee that while Logical Generalization accuracyis substantially higher for R ANDOM, Preservationaccuracy is higher for POPULAR. This suggests that,although retaining correct knowledge is easier forpopular entities, modifying other facts that log-ically follow from an edit is harder for popularentities, which could be explained by the severityNo effect Abstaining NoiseGPT-2 ROME 27% 31% 42%ICE 32% 27% 41%GPT-NEOROME 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 failuresof ROME and ICE, on GPT-2, GPT-N EO,a n dLLAMA.of these edits (i.e., the high number of facts thatare semantically related to them).5.3 Error AnalysisROME versus ICE We qualitatively analyzethe effect induced by KE methods to the model’sknowledge. To this end, for each of ROME andour ICE baseline and each of the models GPT-2,GPT-NEO,a n dL L AMA, we sample 200 testqueries from RIPPLEEDITS on which the model failspost-editing. We then label these failures usingthree categories: (a) no effect, for cases when themodel predicts the original object, i.e., the edit in-troduced no ripple effect, (b) abstaining, when themodel abstains from answering by generating textlike ‘‘unknown’’ or ‘‘a mystery’’ , and (c) noise,when the model generates an incorrect object orunrelated text. Table 7 presents the results, show-ing that in most cases ( ≥ 68% across all settings)factual editing introduces erroneous changes to themodel’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 whileICE causes the model to abstain from answering.GPT-3 versus LL AMA using ICE We furtherlooked into the performance on the LG tests, whereapplying ICE to GPT-3 is notably inferior to ICEon LL AMA (see Tables 3, 4, 5). Specifically, wecollected responses from each of the models to 100random LG queries, and analyzed them using thesame categories as described above. We observedthat GPT-3 abstains from answering the querymuch more often than LL AMA (49% of the casesfor GPT-3 compared to only 28% in LL AMA),which could explain the lower performance ofICE on GPT-3 on these queries.2936 Conclusion and DiscussionWe introduce the notion of ripple effects in knowl-edge editing, suggesting that editing a particularfact implies further updates of related facts. Weadditionally propose evaluation criteria for rippleeffects and create RIPPLEEDITS, a diagnostic bench-mark designed to evaluate how well KE methodshandle the ripple effects of various edits. We eval-uate prominent KE methods and show that theyoften fail to introduce consistent edits that capturethe ripple effects of an edit, suggesting that fu-ture development of KE methods should considerthose effects more carefully. Last, we show that asimple in-context editing method achieves the bestresults on R IPPLEEDITS, highlighting the potentialof such editing approaches.Notably, our benchmark covers a small fractionof all possible ripple-edits. For example, one couldconsider ripple effects that involve more than twohops, and explore the graph structure of differentedits. In addition, while we focus on ripple effectsof single edits, future work can consider the effectof editing multiple facts in a single batch. Finally,it would be interesting to consider cases wheremodels succeed in capturing ripple-edits, and an-alyze how these are implemented mechanisticallyin the transformer architecture (Geva et al., 2023).Limitations Our data generation pipeline relieson information from an existing knowledge-base(WIKIDATA in our case), which could be incom-plete or outdated. While R IPPLEEDITS does not aimto cover all the possible ripple-edits in W IKI-DATA, these concerns might be a major issuewhen seeking a comprehensive evaluation or con-sidering domain-specific knowledge-bases, whichoften tend to be incomplete. A possible solutionto explore in that case is to use LMs internalknowledge instead of an external knowledge-base(Cohen et al., 2023).With R IPPLEEDITS focusing on the ripple effectof edits, it does not include tests, such as para-phrasing of the edit and subject specificity, thatevaluate the edit itself and are covered by exist-ing benchmarks (e.g., CounterFact). In addition,it does not verify that many other facts that aredistantly related to the edit, i.e., triplets that arenot included in the close neighbourhood of theedit, were retained post-editing. For example, weexpect that editing the capital of France wouldnot affect the population of Poland, yet this is notexplicitly checked. We note that building such anevaluation is hard, since there are many facts toconsider and it is unclear how to determine auto-matically which triplets should and should not beaffected by a certain edit.AcknowledgmentsWe thank Maor Ivgi and Gal Elidan for valu-able feedback and constructive suggestions. Thiswork is supported in part by the Israeli ScienceFoundation.ReferencesSidney Black, Stella Biderman, Eric Hallahan,Quentin Anthony, Leo Gao, Laurence Golding,Horace He, Connor Leahy, Kyle McDonell,Jason Phang, Michael Pieler, Usvsn SaiPrashanth, Shivanshu Purohit, Laria Reynolds,Jonathan Tow, Ben Wang, and SamuelWeinbach. 2022. GPT-NeoX-20B: An open-source autoregressive language model. In Pro-ceedings of BigScience Episode #5 – Workshopon 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.9Tom B. Brown, Benjamin Mann, Nick Ryder,Melanie Subbiah, Jared Kaplan, PrafullaDhariwal, Arvind Neelakantan, Pranav Shyam,Girish Sastry, Amanda Askell, SandhiniAgarwal, Ariel Herbert-Voss, GretchenKrueger, Tom Henighan, Rewon Child, AdityaRamesh, Daniel M. Ziegler, Jeffrey Wu,Clemens Winter, Christopher Hesse, MarkChen, Eric Sigler, Mateusz Litwin, ScottGray, Benjamin Chess, Jack Clark, ChristopherBerner, Sam McCandlish, Alec Radford, IlyaSutskever, and Dario Amodei. 2020. Languagemodels are few-shot learners. In Advancesin Neural Information Processing Systems33: Annual Conference on Neural Informa-tion Processing Systems 2020, NeurIPS 2020,December 6–12, 2020, virtual .Mark Chen, Jerry Tworek, Heewoo Jun, QimingYuan, Henrique Ponde de Oliveira Pinto, JaredKaplan, Harri Edwards, Yuri Burda, NicholasJoseph, Greg Brockman, Alex Ray, Raul Puri,Gretchen Krueger, Michael Petrov, Heidy294Khlaaf, Girish Sastry, Pamela Mishkin, BrookeChan, Scott Gray, Nick Ryder, Mikhail Pavlov,Alethea Power, Lukasz Kaiser, MohammadBavarian, Clemens Winter, Philippe Tillet,Felipe Petroski Such, Dave Cummings, MatthiasPlappert, Fotios Chantzis, Elizabeth Barnes,Ariel Herbert-Voss, William Hebgen Guss,Alex Nichol, Alex Paino, Nikolas Tezak, JieTang, Igor Babuschkin, Suchir Balaji, ShantanuJain, William Saunders, Christopher Hesse,Andrew N. Carr, Jan Leike, Josh Achiam, VedantMisra, Evan Morikawa, Alec Radford, MatthewKnight, Miles Brundage, Mira Murati, KatieMayer, Peter Welinder, Bob McGrew, DarioAmodei, Sam McCandlish, Ilya Sutskever, andWojciech Zaremba. 2021. Evaluating large lan-guage models trained on code. ArXiv preprint ,abs/2107.03374. https://arxiv.org/abs/2107.03374Roi Cohen, Mor Geva, Jonathan Berant,and Amir Globerson. 2023. Crawling theinternal knowledge-base of language models. InFindings of the Association for ComputationalLinguistics: EACL 2023 , pages 1856–1869,Dubrovnik, Croatia. Association for Computa-tional Linguistics. https://doi.org/10.18653/v1/2023.findings-eacl.139Damai Dai, Li Dong, Yaru Hao, Zhifang Sui,Baobao Chang, and Furu Wei. 2022. Knowl-edge neurons in pretrained transformers. InProceedings of the 60th Annual Meeting ofthe 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.581Nicola 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.522Bhuwan Dhingra, Jeremy R. Cole, Julian MartinEisenschlos, 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 00459Konstantin 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 2022edition. Metaphysics Research Lab, StanfordUniversity.Mor Geva, Jasmijn Bastings, Katja Filippova,and Amir Globerson. 2023. Dissecting recall offactual associations in auto-regressive languagemodels. arXiv preprint arXiv:2304.14767 .https://doi.org/10.18653/v1/2023.emnlp-main.751Mor Geva, Roei Schuster, Jonathan Berant, andOmer Levy. 2021. Transformer feed-forwardlayers are key-value memories. In Proceed-ings of the 2021 Conference on EmpiricalMethods 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.446Anshita Gupta, Debanjan Mondal, AkshayKrishna Sheshadri, Wenlong Zhao, XiangLorraine Li, Sarah Wiegreffe, and NiketTandon. 2023. Editing commonsense knowl-edge in gpt. https://arxiv.org/abs/2305.14956Peter Hase, Mona Diab, Asli Celikyilmaz, XianLi, 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 ofthe European Chapter of the Association forComputational Linguistics , pages 2714–2731,Dubrovnik, Croatia. Association for Computa-tional Linguistics. https://doi.org/10.18653/v1/2023.eacl-main.199Benjamin Heinzerling and Kentaro Inui. 2021.Language models as knowledge bases: Onentity representations, storage capacity, andparaphrased queries. In Proceedings of the16th Conference of the European Chapterof 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.153295Evan Hernandez, Belinda Z. Li, and JacobAndreas. 2023a. Inspecting and editing knowl-edge representations in language models.https://arxiv.org/abs/2304.00740Evan Hernandez, Belinda Z. Li, and JacobAndreas. 2023b. Measuring and manipulatingknowledge representations in language models.ArXiv preprint, abs/2304.00740.Jason Hoelscher-Obermaier, Julia Persson, EsbenKran, Ioannis Konstas, and Fazl Barez. 2023.Detecting edit failures in large language mod-els: An improved specificity benchmark. InFindings of the Association for ComputationalLinguistics: ACL 2023 , pages 11548–11559,Toronto, Canada. Association for Computa-tional Linguistics. https://doi.org/10.18653/v1/2023.findings-acl.733Joel Jang, Seonghyeon Ye, Sohee Yang, JoongboShin, Janghoon Han, Gyeonghun Kim,Stanley Jungkyu Choi, and Minjoon Seo. 2022.Towards continual knowledge learning of lan-guage models. In The Tenth InternationalConference on Learning Representations, ICLR2022, 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, NovaDasSarma, Eli Tran-Johnson, Scott Johnston,Sheer El-Showk, Andy Jones, Nelson Elhage,Tristan Hume, Anna Chen, Yuntao Bai, SamBowman, Stanislav Fort, Deep Ganguli, DannyHernandez, 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. ArXivpreprint, abs/2207.05221. https://arxiv.org/abs/2207.05221Nora Kassner, Oyvind Tafjord, Hinrich Sch ¨utze,and Peter Clark. 2021. BeliefBank: Addingmemory to a pre-trained language model fora systematic notion of belief. In Proceed-ings of the 2021 Conference on EmpiricalMethods 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.697Angeliki Lazaridou, Adhiguna Kuncoro, ElenaGribovskaya, Devang Agrawal, Adam Liska,Tayfun Terzi, Mai Gimenez, Cyprien deMasson d’Autume, Tom ´as Kocisk ´y, SebastianRuder, Dani Yogatama, Kris Cao, SusannahYoung, and Phil Blunsom. 2021. Mind thegap: Assessing temporal generalization in neu-ral language models. In Advances in NeuralInformation Processing Systems 34: AnnualConference on Neural Information ProcessingSystems 2021, NeurIPS 2021, December 6-14,2021, virtual, pages 29348–29363.Omer Levy, Minjoon Seo, Eunsol Choi, and LukeZettlemoyer. 2017. Zero-shot relation extrac-tion via reading comprehension. InProceedingsof the 21st Conference on ComputationalNatural Language Learning (CoNLL 2017) ,pages 333–342, Vancouver, Canada. Associa-tion for Computational Linguistics. https://doi.org/10.18653/v1/K17-1034Patrick S. H. Lewis, Ethan Perez, AleksandraPiktus, Fabio Petroni, Vladimir Karpukhin,Naman Goyal, Heinrich K ¨uttler, Mike Lewis,Wen-tau Yih, Tim Rockt ¨aschel, SebastianRiedel, and Douwe Kiela. 2020. Retrieval-augmented generation for knowledge-intensiveNLP tasks. In Advances in Neural InformationProcessing Systems 33: Annual Conference onNeural Information Processing Systems 2020,NeurIPS 2020, December 6-12, 2020, virtual .Pengfei Liu, Weizhe Yuan, Jinlan Fu, ZhengbaoJiang, Hiroaki Hayashi, and Graham Neubig.2023. Pre-train, prompt, and predict: A sys-tematic survey of prompting methods in naturallanguage processing. ACM Computing Surveys,55(9):1–35. https://doi.org/10.1145/3560815Alex Mallen, Akari Asai, Victor Zhong,Rajarshi Das, Daniel Khashabi, and HannanehHajishirzi. 2023. When not to trust lan-guage models: Investigating effectiveness ofparametric and non-parametric memories. InProceedings of the 61st Annual Meeting ofthe Association for Computational Linguistics(Volume 1: Long Papers) , pages 9802–9822,296Toronto, Canada. Association for Computa-tional Linguistics. https://doi.org/10.18653/v1/2023.acl-long.546Kevin Meng, David Bau, Alex Andonian, andYonatan Belinkov. 2022. Locating and edit-ing factual associations in gpt. Advancesin 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 onLearning Representations.Eric Mitchell, Charles Lin, Antoine Bosselut,Chelsea Finn, and Christopher D. Manning.2022. Fast model editing at scale. In The TenthInternational Conference on Learning Repre-sentations, ICLR 2022, Virtual Event, April25-29, 2022. OpenReview.net.Yasumasa Onoe, Michael Zhang, ShankarPadmanabhan, Greg Durrett, and EunsolChoi. 2023. Can LMs learn new entitiesfrom descriptions? Challenges in propagat-ing injected knowledge. In Proceedings ofthe 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.300Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida,Carroll L. Wainwright, Pamela Mishkin, ChongZhang, Sandhini Agarwal, Katarina Slama,Alex Ray, John Schulman, Jacob Hilton, FraserKelton, Luke Miller, Maddie Simens, AmandaAskell, Peter Welinder, Paul Christiano,Jan Leike, and Ryan Lowe. 2022. Traininglanguage models to follow instructions with hu-man feedback. https://arxiv.org/abs/2203.02155Matthew E. Peters, Mark Neumann, Robert Logan,Roy Schwartz, Vidur Joshi, Sameer Singh, andNoah A. Smith. 2019. Knowledge enhancedcontextual word representations. In Proceed-ings of the 2019 Conference on EmpiricalMethods in Natural Language Processing andthe 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-1005Fabio Petroni, Tim Rockt¨aschel, Sebastian Riedel,Patrick Lewis, Anton Bakhtin, Yuxiang Wu,and Alexander Miller. 2019. Language modelsas knowledge bases? InProceedings of the 2019Conference on Empirical Methods in NaturalLanguage Processing and the 9th InternationalJoint 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-1250Alec Radford, Jeffrey Wu, Rewon Child, DavidLuan, Dario Amodei, and Ilya Sutskever. 2019.Language models are unsupervised multitasklearners. 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.04888Adam Roberts, Colin Raffel, and Noam Shazeer.2020. How much knowledge can you packinto the parameters of a language model?In Proceedings of the 2020 Conference onEmpirical Methods in Natural LanguageProcessing (EMNLP) , pages 5418–5426, On-line. Association for Computational Linguis-tics. https://doi.org/10.18653/v1/2020.emnlp-main.437Taylor Shin, Yasaman Razeghi, Robert L. LoganIV, Eric Wallace, and Sameer Singh. 2020.AutoPrompt: Eliciting knowledge from lan-guage models with automatically generatedprompts. 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.346Chenglei Si, Zhe Gan, Zhengyuan Yang,Shuohang Wang, Jianfeng Wang, Jordan LeeBoyd-Graber, and Lijuan Wang. 2023. Prompt-ing GPT-3 to be reliable. In The EleventhInternational Conference on Learning Repre-sentations.Hugo Touvron, Thibaut Lavril, Gautier Izacard,Xavier Martinet, Marie-Anne Lachaux,297Timoth´ee Lacroix, Baptiste Rozi `ere, NamanGoyal, Eric Hambro, Faisal Azhar, AurelienRodriguez, Armand Joulin, Edouard Grave, andGuillaume Lample. 2023. Llama: Open andefficient foundation language models. ArXivpreprint, abs/2302.13971. https://arxiv.org/abs/2302.13971Ruize Wang, Duyu Tang, Nan Duan, ZhongyuWei, Xuanjing Huang, Jianshu Ji, GuihongCao, Daxin Jiang, and Ming Zhou. 2021a.K-Adapter: Infusing knowledge into pre-trainedmodels with adapters. In Findings of theAssociation 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.121Xiaozhi Wang, Tianyu Gao, Zhaocheng Zhu,Zhengyan Zhang, Zhiyuan Liu, Juanzi Li,and Jian Tang. 2021b. KEPLER: A uni-fied model for knowledge embedding andpre-trained language representation. Transac-tions of the Association for ComputationalLinguistics, 9:176–194. https://doi.org/10.1162/tacl_a_00360Yunzhi Yao, Shaohan Huang, Li Dong, FuruWei, 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 InternationalPublishing. https://doi.org/10.1007/978-3-031-17120-8_11Yunzhi Yao, Peng Wang, Bozhong Tian, SiyuanCheng, Zhoubo Li, Shumin Deng, HuajunChen, and Ningyu Zhang. 2023. Editing largelanguage models: Problems, methods, andopportunities. https://arxiv.org/abs/2305.13172Ningyu Zhang, Shumin Deng, Xu Cheng, Xi Chen,Yichi Zhang, Wei Zhang, and Huajun Chen.2021. Drop redundant, shrink irrelevant: Se-lective knowledge injection for languagepretraining. In Proceedings of the ThirtiethInternational 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/552Xikun Zhang, Antoine Bosselut, MichihiroYasunaga, Hongyu Ren, Percy Liang,Christopher D. Manning, and Jure Leskovec.2022. Greaselm: Graph reasoning enhancedlanguage models. In The Tenth InternationalConference on Learning Representations, ICLR2022, Virtual Event, April 25-29, 2022 .OpenReview.net.Zhengyan Zhang, Xu Han, Zhiyuan Liu, XinJiang, Maosong Sun, and Qun Liu. 2019.ERNIE: Enhanced language representation withinformative entities. In Proceedings of the57th Annual Meeting of the Association forComputational Linguistics , pages 1441–1451,Florence, Italy. Association for Computa-tional Linguistics. https://doi.org/10.18653/v1/P19-1139Ce Zheng, Lei Li, Qingxiu Dong, Yuxuan Fan,Zhiyong Wu, Jingjing Xu, and Baobao Chang.2023. Can we edit factual knowledge byin-context learning? https://doi.org/10.18653/v1/2023.emnlp-main.296Zexuan Zhong, Zhengxuan Wu, Christopher D.Manning, Christopher Potts, and Danqi Chen.2023. Mquake: Assessing knowledge editingin language models via multi-hop ques-tions. https://doi.org/10.18653/v1/2023.emnlp-main.97129812345678910111213# 原论文复现的解码修订
本批继承[原论文复现协议](../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解码为可打印的 `<unmapped_52463>`;保留原始id,按错误答案计分。既不删除该输出类别,也不遮蔽logits,不改变生成、损失、参数、梯度或训练样本。正常token继续使用作者的解码。新增回归测试覆盖真实52,463长度tokenizer及这个补齐类别。
使用相同固定镜像,先对全部18,986条测试池执行训练前评价、完整模型batch1024的两次FP16更新、保存、最终评价及新进程重载。此验证通过后,另立冻结源码并提交两个百万迭代任务;不覆盖v1失败记录和冻结源,不把工程重试计为新世界或科学重复。
来源、原始代码、PDF、依赖锁和镜像构建证据继续保存在v1材料目录;修订后的来源为本目录 `source/`,冻结配置和执行锁保存在本目录。W&B组为 `implicit-reasoning-paper-reproduction-v2`。12345678910111213141516171819202122232425262728293031323334{ "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" } ]}1234567891011{ "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"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182{ "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."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364"""Freeze and run new learning/use experiments without touching historical batches."""
from __future__ import annotations
import argparseimport fcntlimport hashlibimport jsonimport shutilimport subprocessimport sysimport timeimport tracebackfrom 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() )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397"""Freeze and execute sequential research stages on explicitly assigned GPUs."""
from __future__ import annotations
import argparseimport fcntlimport hashlibimport importlibimport jsonimport osimport shutilimport subprocessimport sysimport timeimport tracebackfrom datetime import datetime, timezonefrom 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()12345678910111213141516171819"""Analytical examples for research on shared structure and editability."""
from .experiments import run_minimal_examplefrom .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",]12345"""Support ``python -m llm_memory_editability``."""
from .cli import main
raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503"""Paired geometric-supervision coverage in the established complete GPT task.
All arms retain full-token CE and all-example first-hop CE. Coverage changesonly a multiplicative mask on the per-example geometric objective; every armexecutes the same forward and backward operations, including the zero mask."""
from __future__ import annotations
import hashlibimport jsonimport osimport shutilimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_jsonfrom .grok_loop_model import flopsfrom .latent_scaling import build_world, model_digestfrom .representation_alignment import new_modelfrom .representation_alignment import pack_training as pack_base_trainingfrom .storage_composition import data_digest, evaluate, file_hashfrom .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 result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549"""Paired interventions on MLP output and same-layer sequence cache.
Oracle bridge hints define an assisted diagnostic, not an identified naturalreasoning circuit. Cache interventions do not change model parameters."""
from __future__ import annotations
import contextlibimport copyimport hashlibimport jsonimport reimport timefrom collections import Counterfrom pathlib import Path
import numpy as npimport 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 result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410"""A frozen small GQA / gated-delta mechanism experiment.
Both models use RMSNorm, SwiGLU and tied token embeddings. The hybrid is adeliberately 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 hashlibimport mathfrom pathlib import Path
import numpy as npimport torchfrom torch import nnfrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399"""Audit saved edit predictions and describe failures without selecting successes."""
import argparseimport csvimport hashlibimport jsonfrom collections import Counter, defaultdictfrom 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""Equal-parameter residual branches from old-world activation directions."""
import time
import numpy as npimport torchfrom torch import nn
from .bios_data import ANSfrom .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")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""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 result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455"""Offline donor-state interventions on frozen crossover models.
Truth is used to match donor/recipient pairs and score outputs, never supplied asan answer or bridge to the model. This is a causal diagnostic, not an editor."""
import csvimport jsonfrom pathlib import Path
import numpy as np
from .bios_cross import CHAINS, make_cross_worldfrom .bios_data import EOS, array_hash, rng_for, write_jsonfrom .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"), }, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280"""Locked world-level inference for the narrower shortcut confirmation.
This module consumes independently audited endpoint counts, never query outcomesfor selecting hypotheses. Nested seeds, organizations, chains and supports areaveraged within a world before any inferential calculation."""
import itertoolsimport 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)}, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250"""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 argparseimport fcntlimport hashlibimport jsonimport osimport timefrom contextlib import contextmanagerfrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from . import bios_cross_train as frozen_trainerfrom .bios_cross import CHAINS, CONDITIONS, audit, documents, make_cross_world, qa_schedulefrom .bios_data import array_hash, write_jsonfrom .bios_model import Attention, CausalLMfrom .bios_organization_train import atomic_numpy_savefrom .bios_path_diagnostics import autonomous_two_step
RECORD_LENGTH = 6DOCUMENT_LENGTH = 60CHECKPOINTS = (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
@contextmanagerdef 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().gitattributes+2
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/slow_documentation_tests.txtAdded+11
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/sort_auto_mappings.pyAdded+124
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/__init__.pyAdded
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_configuration.pyAdded+16
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_feature_extraction.pyAdded+5
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_image_processing.pyAdded+5
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_modeling.pyAdded+33
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_pipeline.pyAdded+33
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_processing.pyAdded+6
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_tokenization.pyAdded+5
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/test_module/custom_tokenization_fast.pyAdded+8
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/tests_fetcher.pyAdded+1260
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/tf_ops/onnx.jsonAdded+245
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/update_metadata.pyAdded+339
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/update_tiny_models.pyAdded+200
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/utils.pyAdded+27
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/visualization.ipynbAdded+170
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/README.mdAdded+77
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/cosine_metrics.ipynbAdded+198
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/cross_query_semantic_patching.ipynbAdded+214
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/data_preparation.ipynbAdded+985
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/logit_lens.ipynbAdded+201
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/upstream/notebooks/training_dynamics.ipynbAdded
docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/validation.jsonAdded+76
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/contract-tests.logAdded+2
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/execution-lock.jsonAdded+3
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/frozen-config.jsonAdded+237
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/fullpool-smoke.logAdded+349
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.pdfAdded+3
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.txtAdded+1482
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.pdfAdded+3
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.txtAdded+1400
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/protocol.mdAdded+13
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/smoke-config.jsonAdded+34
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/configs/experiment-tracking-defaults.jsonAdded+11
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/configs/implicit-reasoning-paper-reproduction-v2.jsonAdded+82
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/scripts/execute_learning_use.pyAdded+364
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/scripts/run_memory_interface_next.pyAdded+397
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/__init__.pyAdded+19
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/__main__.pyAdded+5
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/alignment_coverage.pyAdded+503
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/architecture_bridge.pyAdded+549
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/architecture_bridge_toy.pyAdded+410
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_analysis.pyAdded+399
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_branch.pyAdded+127
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_capacity.pyAdded+48
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_causal_paths.pyAdded+455
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_confirmation_stats.pyAdded+280
docs/development-artifacts/implicit-reasoning-paper-reproduction-v2/source/src/llm_memory_editability/bios_context_control.pyAdded+250